Tickd.ai
API errors

Gemini API 401 Unauthorized Error: How to Fix

Updated 10/10/2026

A 401 Unauthorized error (often accompanied by an INVALID_ARGUMENT or API_KEY_INVALID message) means the Gemini API cannot validate your request credentials. This issue prevents your application from interacting with the Gemini models, stalling development.

This guide explains how to troubleshoot and resolve Gemini API 401 errors across Google AI Studio and Vertex AI integrations.

1. Verify and Regenerate Your API Key

The most common cause of a 401 error is an invalid, deleted, or mistyped API key.

  1. Log in to [Google AI Studio](https://aistudio.google.com/).
  2. Click on Get API key in the top navigation bar.
  3. Check the list of active keys. If you do not see your key, or if you suspect it has been deleted, click Create API key.
  4. Select your Google Cloud project and generate a new key.
  5. Copy the key immediately. *Note: You cannot retrieve the key string again once you close the window.*

2. Configure Your Environment Variables Correctly

Hardcoding API keys into your application code is insecure and often leads to formatting errors. The recommended method is to load the key from an environment variable. The Google Gen AI SDKs look for a specific variable name by default.

For Linux/macOS: Open your terminal and set the environment variable: ```bash export GEMINI_API_KEY="your_actual_api_key_here" ``` To make this persistent, add the line above to your shell profile file (e.g., `~/.bashrc` or `~/.zshrc`).

For Windows (Command Prompt): ```cmd set GEMINI_API_KEY="your_actual_api_key_here" ```

For Windows (PowerShell): ```powershell $env:GEMINI_API_KEY="your_actual_api_key_here" ```

In Python Code: Make sure your SDK initialization reads the variable correctly. If you pass the key manually, ensure you are not passing an empty string or the literal text `"GEMINI_API_KEY"`.

`python import os import google.generativeai as genai

Best practice: Retrieve from environment api_key = os.environ.get("GEMINI_API_KEY")

if not api_key: raise ValueError("GEMINI_API_KEY environment variable not set.")

genai.configure(api_key=api_key) `

3. Match the SDK to the Correct Endpoint

A frequent source of 401 errors is mixing up Google AI Studio credentials with Google Cloud Vertex AI credentials. They use different authentication pathways.

  • Google AI Studio (Gemini API): Uses simple API keys. You initialize using google.generativeai in Python, or @google/generative-ai in Node.js.
  • Google Cloud Vertex AI: Uses OAuth 2.0, Service Account JSON keys, or Application Default Credentials (ADC). You initialize using google.cloud.aiplatform or the dedicated Vertex AI SDK wrapper.

If you attempt to use an AI Studio API key with a Vertex AI initialization flow, the server will reject the request with a 401 unauthorized status.

4. Format Your Raw HTTP Requests Correctly

If you are calling the Gemini REST API directly using curl or an HTTP library (like Axios or requests) instead of the official SDK, you must pass the API key either in the query string or in the request headers.

Method A: Query Parameter (Recommended for direct REST) Append `?key=YOUR_API_KEY` to the end of the request URL:

`bash curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=YOUR_API_KEY" \ -H 'Content-Type: application/json' \ -d '{"contents": [{"parts":[{"text": "Explain quantum computing in one sentence."}]}]}' `

Method B: Header Authentication Alternatively, pass the key via the `x-goog-api-key` header:

`bash curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent" \ -H "Content-Type: application/json" \ -H "x-goog-api-key: YOUR_API_KEY" \ -d '{"contents": [{"parts":[{"text": "Hello"}]}]}' ` Do not use standard HTTP Bearer authorization headers (e.g., Authorization: Bearer YOUR_API_KEY) for standard Google AI Studio keys, as this causes authentication handshake failures.

5. Check Cloud Project Constraints and Restrictions

If your API key is valid but you still receive 401 errors, your Google Cloud Platform (GCP) project settings may be blocking the requests:

  1. Go to the [Google Cloud Console](https://console.cloud.google.com/).
  2. Navigate to APIs & Services > Credentials.
  3. Click on the API key you are using and look at API restrictions.
  4. Ensure the key is either unrestricted or explicitly allowed to call the Generative Language API.
  5. Check if your project's billing status is in good standing. A suspended GCP project will reject incoming API key verifications.

When to Escalate

If you have verified that your key is active, you are using the correct SDK matching your endpoint, and raw curl requests still fail with a 401 error, check the [Google Cloud Status Dashboard](https://status.cloud.google.com/) for authentication system disruptions.

If services are operating normally, post a query on the [Google AI Forum](https://discuss.asgard.com/) or contact Google Cloud Support if your project is linked to an active enterprise support plan.

While you're here

Tickd is more than troubleshooting — these three are free and take seconds.

Agent BuilderDesign your own AI agent and export it to ChatGPT, Claude, Gemini or Grok.Build one free