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
- Test the key outside your app first: send it to
GET /v1beta/modelswith curl (command below). A 200 means the key exists and your app is sending something else. - Look at what your app really sends: a key wrapped in literal quotes is sent with the quotes.
google-genai3.0.0 strips spaces and newlines but not quotes. - Check both variables: if
GOOGLE_API_KEYandGEMINI_API_KEYare both set, the SDK usesGOOGLE_API_KEY. A stale value there overrides a goodGEMINI_API_KEY. - A missing key is a different error: no key or an empty key returned 403
PERMISSION_DENIED, not this 400. - Do not retry: the request will fail the same way until the key changes.
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.
| Request | HTTP | status | reason / message |
|---|---|---|---|
GET /models?key=BOGUS | 400 | INVALID_ARGUMENT | API_KEY_INVALID |
GET /models with x-goog-api-key: BOGUS | 400 | INVALID_ARGUMENT | API_KEY_INVALID (identical body) |
POST /models/gemini-flash-latest:generateContent, bogus key in header | 400 | INVALID_ARGUMENT | API_KEY_INVALID (identical body) |
POST /interactions, bogus key in header | 400 | INVALID_ARGUMENT | API_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) | 400 | INVALID_ARGUMENT | API_KEY_INVALID |
| Bogus key wrapped in double quotes (query or header) | 400 | INVALID_ARGUMENT | API_KEY_INVALID |
| No key at all (GET and POST) | 403 | PERMISSION_DENIED | "Method doesn't allow unregistered callers…" (below) |
Empty key: ?key= or an empty x-goog-api-key header | 403 | PERMISSION_DENIED | same as no key |
Authorization: Bearer BOGUS | 401 | UNAUTHENTICATED | CREDENTIALS_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.
- Unrestricted standard key. Doc-cited: "The Gemini API rejects requests from unrestricted standard keys." Which error those requests receive is not stated and not verified. Fix per the docs: in AI Studio, hover the Unrestricted label, choose Add restrictions, then Restrict to Gemini API only.
- Key restricted to other APIs. Doc-cited: if a key's API restrictions in the Cloud console exclude the Generative Language API, "Gemini API requests using this key will fail". Error text not verified. Fix per the docs: create a separate key in AI Studio for Gemini.
- Dormant key. Doc-cited: since 7 May 2026 unrestricted keys that have been dormant for an extended period are blocked and show a Blocked tag in AI Studio. Error text not verified. Fix: generate a new key.
- Leaked key. Doc-cited as a different error: 403
PERMISSION_DENIEDwith "Your API key was reported as leaked. Please use another API key." Not reproduced. - Deleted key. Not verified. The docs describe deleting keys but do not say what a deleted key returns. It is plausible that it returns this 400, but that is an assumption.
- Key from the wrong project. Not verified, and the docs point the other way: project-level problems (verification, free-tier eligibility, billing) are documented as 403
PERMISSION_DENIED, and "creating a new API key in the same project won't resolve the error". - Vertex AI versus AI Studio key. Not verified. What is established from the SDK source is that
GOOGLE_GENAI_USE_VERTEXAIandGOOGLE_GENAI_USE_ENTERPRISEare read from the environment and change which backend the client targets, withGOOGLE_CLOUD_PROJECTandGOOGLE_CLOUD_LOCATION. If one of those is set unintentionally, your key is not going where you think. How each backend responds to the other's credentials was not tested.
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
- Gemini API 429 rate limit: causes and fixes
- OpenAI AuthenticationError: invalid API key
- Anthropic API authentication_error
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.