TroubleshootingBeginner

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.

8 minBeginner

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.

test.sh
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.

Google Cloud Console
APIs & Services > Library
Generative Language API
Status: DISABLED
[ ENABLE ]
A disabled API returns a key-not-valid style error even with a correct key.

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.

zsh - gemini
{ "error": { "code": 400, "message": "API key not valid. Please pass a valid API key.", "status": "INVALID_ARGUMENT" } }
Often caused by a referrer restriction blocking a server call.
$

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.

AI Studio keys are simpler
For getting started, a key created directly in Google AI Studio usually has the API enabled and no restrictions, which removes two of the most common causes at once.

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

Tags
#gemini#google#api keys#400