Gemini API Key Invalid or Restricted — Fix (2026) | AI Error Hub
GeminiAuthSeverity: HighHTTP 403

Gemini API Key Invalid or Restricted (403 PERMISSION_DENIED)

Your API key was rejected. Common causes: key restrictions (referrer/IP/API), expired key, Generative Language API not enabled in project, or trying to use an AI Studio key for Vertex AI (they're different auth systems).

Error code: PERMISSION_DENIEDHTTP: 403Category: AuthenticationLast tested: Nov 15, 2026
Quick Fix (TL;DR)

Verify: (1) key is correct and not truncated, (2) Generative Language API is enabled in your Google Cloud project, (3) API restrictions include Generative Language API, (4) IP/referrer restrictions match your caller, (5) you're using an AI Studio key on generativelanguage.googleapis.com (not Vertex AI, which needs service accounts). Regenerate the key if unsure.

The Error Messages You're Seeing

Response body variants
HTTP/1.1 403 Forbidden

{
  "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"
  }
}

Variants:
"API key not valid. Please pass a valid API key."
"Requests from referer <URL> are blocked."
"Requests from this IP address are blocked."
"Generative Language API has not been used in project 
<PROJECT> before or it is disabled."
"API key expired. Please renew the API key."

Key Types Reference

DeploymentAuth methodWhere to create
AI Studio (default)API keyaistudio.google.com/apikey
Vertex AI (recommended)Service account + ADCGoogle Cloud IAM console
Vertex AI (also works)API key (limited)Google Cloud APIs & Services
Local devgcloud auth application-default logingcloud CLI

What Actually Causes This Error

28%
Generative Language API not enabledProject exists but API disabled; must enable in APIs & Services.
22%
Wrong key type for endpointAI Studio key sent to Vertex AI endpoint or vice versa.
18%
Referrer/IP restriction blocks callerKey locked to *.mysite.com but backend has no referer.
15%
API restriction excludes Generative LanguageKey limited to specific APIs; Gemini not in the list.
10%
Key truncated / whitespace / leaked-and-revokedEnv var corruption; key posted publicly then auto-revoked.
7%
Billing account issuePaid tier requires linked billing; disabled billing revokes access.

Fixes That Work (Tested Nov 2026)

1Diagnose Which Failure Path

Python · diagnostic checks
import os, requests from google import genai def diagnose_gemini_auth(): key = os.environ.get("GEMINI_API_KEY") # 1. Key present? if not key: return "GEMINI_API_KEY env var not set" if len(key.strip()) != len(key): return "Key has leading/trailing whitespace" if not key.startswith("AIza"): return "Key doesn't match Google API key format (should start AIza)" # 2. Direct HTTP call — see raw error r = requests.get( "https://generativelanguage.googleapis.com/v1beta/models", params={"key": key} ) if r.status_code == 200: return "Key works! Try SDK call again." err = r.json().get("error", {}) msg = err.get("message", "") if "has not been used" in msg or "disabled" in msg: return "Enable Generative Language API in Cloud Console" if "expired" in msg: return "Key expired — regenerate at aistudio.google.com/apikey" if "referer" in msg.lower() or "referrer" in msg.lower(): return "Referrer restriction blocking backend calls" if "IP" in msg: return "IP restriction blocking your server's IP" if "not valid" in msg: return "Key rejected — likely wrong project or revoked" return f"Unknown: {msg}" print(diagnose_gemini_auth())

2AI Studio Key Setup Correctly

Python · clean AI Studio setup
import os from google import genai # AI Studio - simple, API key based # Get key from: https://aistudio.google.com/apikey client = genai.Client( api_key=os.environ["GEMINI_API_KEY"] # uses generativelanguage.googleapis.com ) # Recommended key restrictions (Cloud Console → APIs → Credentials): # 1. Application restrictions: "HTTP referrers" for browser apps # OR "IP addresses" for backend # OR "None" for local dev (risky in prod) # 2. API restrictions: "Restrict key" → select "Generative Language API" # 3. Set an expiration if for a specific project # Test resp = client.models.generate_content( model="gemini-2.5-flash", contents="Say hi" ) print(resp.text)

3Vertex AI Service Account Setup

Python · Vertex AI with ADC (recommended)
from google import genai # Vertex AI - use Application Default Credentials (ADC) # Setup once: # Local dev: gcloud auth application-default login # GKE/Cloud Run: workload identity attached automatically # Servers: set GOOGLE_APPLICATION_CREDENTIALS to service account JSON client = genai.Client( vertexai=True, project="my-project", location="us-central1" # NO api_key — uses ADC ) # Required IAM roles on the service account or user: # roles/aiplatform.user (or narrower: aiplatform.endpoints.predict) # Serviceusage.consumer if querying quotas # Verify auth pre-flight import google.auth credentials, project = google.auth.default() print(f"Auth as: {credentials.service_account_email if hasattr(credentials, 'service_account_email') else 'user'}") print(f"Project: {project}") resp = client.models.generate_content( model="gemini-2.5-flash", contents="Hello" )
Prefer ADC over service account JSON files

Application Default Credentials automatically picks the right auth for each environment (local, Cloud Run, GKE, GCE, etc.). Service account JSON files in code repos are a top security incident source. Use workload identity in cloud, gcloud in local dev.

Preventing This Error Going Forward

  • Enable Generative Language API in Cloud Console before creating key.
  • Restrict keys to specific APIs. Prevents accidental misuse.
  • Use IP restrictions for backend keys, referrer for browser keys.
  • Never commit keys to git. Google scans and auto-revokes.
  • Rotate keys quarterly. Set expiration when possible.
  • Use ADC for Vertex AI, keys for AI Studio. Don't mix.
  • Add diagnostic health check at app startup. Catch auth breakage fast.
AR
Tested by Ahmed R.
Researcher · AI Error Hub
Last verified: Nov 15, 2026 · SDK: google-genai 0.8+

Frequently Asked Questions

Officially no — they're different auth systems. Vertex AI supports API keys in some contexts now but the canonical auth is service accounts + ADC. Simpler mental model: keys for AI Studio, ADC for Vertex.

Most common: key committed to public GitHub → Google auto-revoked. Also: billing account disabled, quota project deleted, org policy blocking public API access, expiration reached. Check Cloud Console audit logs.

Store in secret manager (GCP Secret Manager, AWS Secrets Manager, Vault). Load at app startup, never log. Apply IP restrictions matching your server's egress IP. Never expose to client.

No — backend calls don't send a Referer header. Referrer restrictions only make sense for browser JavaScript calls. For server, use IP restrictions or leave unrestricted (with tight API restrictions).

Free tier is only available on AI Studio API keys. Vertex AI always bills through your GCP account (with initial $300 credit for new accounts). Use AI Studio for prototyping, migrate to Vertex for enterprise features.