Gemini API 400 "API key not valid. Please pass a valid API key." (API_KEY_INVALID)

This is the response the Gemini API (generativelanguage.googleapis.com, the endpoint behind Google AI Studio keys) gives when a request carries a key string it does not recognise. It arrives as HTTP 400 with status INVALID_ARGUMENT, not as a 401, and the same body comes back from models.list, generateContent and interactions. The key reached Google; Google did not accept it. This page shows the error reproduced today and how to tell which mistake produced it.

The 30-second answer

The exact error

{
  "error": {
    "code": 400,
    "message": "API key not valid. Please pass a valid API key.",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.ErrorInfo",
        "reason": "API_KEY_INVALID",
        "domain": "googleapis.com",
        "metadata": {
          "service": "generativelanguage.googleapis.com"
        }
      },
      {
        "@type": "type.googleapis.com/google.rpc.LocalizedMessage",
        "locale": "en-US",
        "message": "API key not valid. Please pass a valid API key."
      }
    ]
  }
}

Source: reproduced today. This is the unedited body returned for curl -s "https://generativelanguage.googleapis.com/v1beta/models?key=AIzaSyBOGUS_not_a_real_key_000000000000" with HTTP status 400. The key in that command is a made-up string.

Verified against the live endpoint and SDK — 9 November 2026

Environment: macOS (Darwin), curl 8.7.1, Python 3.11.9, google-genai==3.0.0 installed fresh with pip install google-genai. Every key used was a bogus string, no GOOGLE_* or GEMINI_* variable was set in the shell, and nothing was billed. Because no real key was used, these tests show what a wrong key returns; they cannot show how Google treats a valid key that has been restricted, deleted or blocked.

1. What each way of sending a key returned. All requests went to https://generativelanguage.googleapis.com/v1beta.

RequestHTTPstatusreason / message
GET /models?key=BOGUS400INVALID_ARGUMENTAPI_KEY_INVALID
GET /models with x-goog-api-key: BOGUS400INVALID_ARGUMENTAPI_KEY_INVALID (identical body)
POST /models/gemini-flash-latest:generateContent, bogus key in header400INVALID_ARGUMENTAPI_KEY_INVALID (identical body)
POST /interactions, bogus key in header400INVALID_ARGUMENTAPI_KEY_INVALID (same object, wrapped in a JSON array)
Bogus key with a trailing space or newline (%20, %0A, or a space in the header)400INVALID_ARGUMENTAPI_KEY_INVALID
Bogus key wrapped in double quotes (query or header)400INVALID_ARGUMENTAPI_KEY_INVALID
No key at all (GET and POST)403PERMISSION_DENIED"Method doesn't allow unregistered callers…" (below)
Empty key: ?key= or an empty x-goog-api-key header403PERMISSION_DENIEDsame as no key
Authorization: Bearer BOGUS401UNAUTHENTICATEDCREDENTIALS_MISSING, "Expected OAuth 2 access token…"

The no-key response, pasted in full:

{
  "error": {
    "code": 403,
    "message": "Method doesn't allow unregistered callers (callers without established identity). Please use API Key or other form of API consumer identity to call this API.",
    "status": "PERMISSION_DENIED"
  }
}

So the status code tells you which side of the problem you are on: 403 "unregistered callers" means your variable is empty or never reached the request; 400 API_KEY_INVALID means a non-empty string arrived and was rejected; 401 means the key was sent as a Bearer token, which this endpoint reads as an OAuth credential.

2. What google-genai 3.0.0 raises. Against the live endpoint with genai.Client(api_key=BOGUS):

### LIVE models.generate_content, api_key=bogus
  -> google.genai.errors.ClientError
  mro: ClientError > APIError > Exception > BaseException
  str(e): 400 INVALID_ARGUMENT. {'error': {'code': 400, 'message': 'API key not valid. Please pass a valid API key.', 'status': 'INVALID_ARGUMENT', 'details': [...
  e.code = 400
  e.status = 'INVALID_ARGUMENT'
  e.message = 'API key not valid. Please pass a valid API key.'

### LIVE interactions.create, api_key=bogus
  -> google.genai._gaos.lib.compat_errors.BadRequestError
  str(e): Error code: 400 - [{'error': {'code': 400, 'message': 'API key not valid. Please pass a valid API key.', ...

### Client() with no key and no env vars
  -> builtins.ValueError
  str(e): No API key was provided. Please pass a valid API key. Learn how to create an API key at https://ai.google.dev/gemini-api/docs/api-key.

(The two long str(e) lines are truncated here with ...; they continue with the same JSON shown above.) models.list() raised the same ClientError. Note that client.interactions raises a different class from client.models, so an except errors.ClientError written for generate_content will not catch it. With no key, or with GEMINI_API_KEY="", the SDK fails locally with ValueError before any request is made.

3. Which environment variables the SDK reads, and what it does to the value. From google/genai/_api_client.py in 3.0.0, get_env_api_key() reads GOOGLE_API_KEY and GEMINI_API_KEY and returns env_google_api_key or env_gemini_api_key or None. A local server on 127.0.0.1 captured the header the SDK actually sent:

GEMINI_API_KEY only            -> x-goog-api-key: 'gemini-var-bogus'
GOOGLE_API_KEY only            -> x-goog-api-key: 'google-var-bogus'
both set                       -> x-goog-api-key: 'google-var-bogus'
  [log WARNING google_genai._api_client] Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.
both set + api_key= in code    -> x-goog-api-key: 'code-arg-bogus'

trailing space    env='AIzaSyBOGUS_not_a_real_key_000000000000 '    -> header='AIzaSyBOGUS_not_a_real_key_000000000000'
trailing newline  env='AIzaSyBOGUS_not_a_real_key_000000000000\n'   -> header='AIzaSyBOGUS_not_a_real_key_000000000000'
leading space     env=' AIzaSyBOGUS_not_a_real_key_000000000000'    -> header='AIzaSyBOGUS_not_a_real_key_000000000000'
double-quoted     env='"AIzaSyBOGUS_not_a_real_key_000000000000"'   -> header='"AIzaSyBOGUS_not_a_real_key_000000000000"'

The first five lines and the last four are condensed from the script output (the header value is quoted exactly as captured). The SDK calls .strip() on the key, so stray whitespace is removed, but literal quote characters are sent as part of the key. The same local server returned the 400 body above and received exactly one request per call: the SDK did not retry it.

4. What the official docs say today. Google's API key page (it now redirects to aistudio.google.com/docs/api-key) says: "Set the environment variable GEMINI_API_KEY or GOOGLE_API_KEY… If both are set, GOOGLE_API_KEY takes precedence", which matches the SDK source. Its REST example sends the key in the x-goog-api-key header. The troubleshooting guide says not to retry client errors such as 400 "as they indicate issues like invalid API keys", and sends key problems back to the API key page. Neither page quotes the "API key not valid" string or the API_KEY_INVALID reason.

Not verified: the response for a real key that has been deleted, restricted, blocked or created for a different product. Whether trailing whitespace breaks a real key in a raw HTTP request is also untested, since a bogus key fails either way. One doc mismatch to be aware of: the API errors page lists authentication / 401 for a "missing, invalid, or expired" key on the Interactions API, but a bogus key sent to /v1beta/interactions today returned the 400 above, with and without the Api-Revision: 2026-05-20 header.

Cause 1: The string your app sends is not the key you copied

Evidence: reproduced (sections 1 and 3). Check the variable without printing the secret. This script was run today:

import os
for name in ("GOOGLE_API_KEY", "GEMINI_API_KEY"):
    k = os.environ.get(name)
    if k is None:
        print(name, "not set")
        continue
    quoted = k[:1] in ("'", '"') or k[-1:] in ("'", '"')
    print(name, "length", len(k), "quoted", quoted, "whitespace", k != k.strip(), "empty", k == "")

Output with a deliberately quoted bogus value:

GOOGLE_API_KEY not set
GEMINI_API_KEY length 41 quoted True whitespace False empty False

Fix: if quoted is True, remove the quote characters wherever the value is defined. A shell export GEMINI_API_KEY="..." strips the quotes for you; whether your .env loader, container runtime or CI secret store does the same was not tested here, so check the value as your process sees it. If you build requests by hand rather than through the SDK, strip whitespace yourself.

Cause 2: A different variable is winning

Evidence: reproduced and doc-cited (sections 3 and 4). When both variables exist, GOOGLE_API_KEY is used. That name is easy to have set already for another Google service, and its value will be sent to the Gemini API in place of your GEMINI_API_KEY.

Fix: run the script above. If both names print a length, unset the one you do not intend to use, or pass the key explicitly with genai.Client(api_key=...), which overrode both variables in the test. The SDK's warning only appears if Python logging is configured to show WARNING level.

Cause 3: The key itself is wrong, truncated or belongs to something else

Evidence: reproduced for any unrecognised string. Take the app out of the picture and test the key directly, using the header form from Google's docs. This prints only the status code:

curl -s -o /dev/null -w "%{http_code}\n" \
  "https://generativelanguage.googleapis.com/v1beta/models" \
  -H "x-goog-api-key: $GEMINI_API_KEY"

With a bogus value this printed 400 today. Google's troubleshooting guide says this endpoint "only validate[s] that your API key exists", so a 200 rules out API_KEY_INVALID for that key; it does not prove that generateContent is enabled for the project.

Fix: if you get 400 here, copy the key again from the Google AI Studio API keys page, or create a new one there, and update the variable.

Cause 4: Key states that Google documents but whose error text we could not confirm

Each of these needs a real key in that state to test. They are listed with what is and is not established.

FAQ

Why is an invalid Gemini API key a 400 and not a 401? That is what the endpoint returned today: HTTP 400, INVALID_ARGUMENT, reason API_KEY_INVALID. No key at all returned 403. A 401 appeared only when the key was sent as Authorization: Bearer. Google's API errors page lists a 401 authentication code for the Interactions API, but a bogus key sent to /v1beta/interactions still returned the 400 in our test.

Which environment variable does the Gemini Python SDK read? google-genai 3.0.0 reads GOOGLE_API_KEY and GEMINI_API_KEY. If both are set, GOOGLE_API_KEY wins and the SDK logs a warning. An api_key= argument to genai.Client() overrides both. Google's API key page states the same precedence.

Should I retry a Gemini "API key not valid" error? No. Google's troubleshooting guide says not to retry client errors such as 400 because they indicate issues like invalid API keys. google-genai 3.0.0 sent exactly one request when it received this 400 and raised immediately.

Does a 200 from the models list endpoint prove my key works? It proves the key exists, which rules out API_KEY_INVALID. Google notes that GET /v1beta/models does not check project tier eligibility or billing status, so generateContent can still fail with a different error.


Related

Verified on 9 November 2026: error body and status codes reproduced with curl 8.7.1 against generativelanguage.googleapis.com using bogus keys only; SDK exceptions, environment variable precedence and key stripping reproduced with google-genai 3.0.0 on Python 3.11.9 (live endpoint plus a local capture server); documentation quotes taken from Google's API key, troubleshooting and API errors pages fetched the same day. Behaviour of real restricted, deleted, blocked or Vertex AI keys was not tested.