How to Fix Google Gemini 'API Key Not Valid' Errors
Get Gemini API requests working by enabling the API, fixing key restrictions, and using the right endpoint.
Gemini returns 'API key not valid' for several reasons that go beyond a wrong key. The Generative Language API may not be enabled, the key may have HTTP referrer or IP restrictions that block your server, or you may be calling the wrong endpoint. This guide checks each cause.
- A Google AI Studio or Google Cloud account
- An API key created in AI Studio or the Cloud console
- curl to test the endpoint
Step 1: Test the key against the real endpoint
Gemini keys are passed as a query parameter or an x-goog-api-key header. Test with a minimal request so you can see the exact error.
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
-H "content-type: application/json" \
-d '{ "contents": [{ "parts": [{ "text": "ping" }] }] }'Step 2: Enable the Generative Language API
If you created the key in Google Cloud rather than AI Studio, the API itself may be disabled for that project. Enable the Generative Language API in the Cloud console, then wait a minute for it to propagate.
Step 3: Check key restrictions
In the Cloud console you can lock a key to specific HTTP referrers, IP addresses, or apps. A key restricted to a website referrer will fail when called from a server. For server use, restrict by IP or leave it for testing, then tighten later.
Step 4: Confirm the model name
Using a model name that does not exist or is not available to your account can surface as a request error. Use a current model id like gemini-2.0-flash and confirm it appears in the models list endpoint.
Result
After enabling the Generative Language API and removing a leftover referrer restriction, the same curl call returns generated text. The most frequent culprit was the disabled API on a Cloud-created project.
Watch related tutorials
16:10
12:25
14:45
20:30
22:15
35:20