Check an OpenAI API Key With a Models List Request

A request to the models endpoint can check whether your OpenAI API key authenticates and can read that endpoint. Run it from the same environment as your app to catch the common case where one shell has the key and another does not.

Worked example

Output the response status without the bearer token

if [ -n "${OPENAI_API_KEY:-}" ]; then
  printf 'Authorization: Bearer %s\n' "$OPENAI_API_KEY" |
    curl --silent --show-error --output /dev/null \
      --write-out 'HTTP %{http_code}\n' \
      --header @- https://api.openai.com/v1/models
else
  printf 'OPENAI_API_KEY is not set in this shell.\n'
fi

Steps

  1. Load OPENAI_API_KEY into the same shell using your normal secret manager or local environment setup. Use a project key that is allowed to list models.
  2. Run the command below. It prints whether the variable is present and the HTTP status from the API. The key stays out of the displayed output and the curl command-line arguments.
  3. For 401, verify that the app has the intended key and that it has not been revoked. For a permission error, check the project's membership and endpoint permissions before issuing or rotating a key.

What to check

  • HTTP 200 shows that this key can list models. The application's generation endpoint can still have different permissions, access, or quota.
  • Turn off shell execution tracing before running commands that interpolate a secret. Treat HTTP 000 as a transport issue and check whether the shell can reach the API.

References