How to Fix OpenAI API Error 401 Invalid API Key
Updated 9/24/2026
An HTTP 401 Unauthorized response from the OpenAI API indicates an authentication failure. This error means the OpenAI servers rejected the credentials provided in your request. If you are building an application with the ChatGPT API, encountering this error will block all generation requests.
This guide covers the systematic steps required to identify why your credentials are being rejected and how to fix the configuration in your code or server environment.
Common Causes of API Error 401 Before modifying your code, it helps to understand why OpenAI throws a 401 error. The most frequent triggers include: * **Incorrect Key Value:** Typographical errors, missing characters, or trailing spaces in the API key string. * **Deleted or Revoked Keys:** The API key was deleted from the OpenAI developer dashboard but remains in your application config. * **Incorrect Environment Variables:** Your application is failing to read the key from the environment, sending a `null`, `undefined`, or empty string instead. * **Incorrect Authorization Header Format:** Custom HTTP requests that do not follow the exact `Authorization: Bearer OPENAI_API_KEY` format. * **Workspace or Project Mismatch:** The key belongs to a specific restricted project or organization that does not have permissions for the endpoint you are calling.
---
How to Fix OpenAI API Error 401
Follow these troubleshooting steps in order to isolate and resolve the authentication failure.
Step 1: Verify the API Key Status in the Dashboard First, confirm that the API key you are using is active and valid within your OpenAI developer platform. 1. Log in to the [OpenAI API Dashboard](https://platform.openai.com/). 2. In the left-hand navigation, click on **API Keys**. 3. Look at your active keys. Ensure the key you are using matches one of the names/truncated values on this list. 4. If you suspect the key was compromised, deleted, or is no longer working, click **Create new secret key**. 5. Copy the newly generated key immediately. *Note: You cannot retrieve this key once you close the modal.*
Step 2: Check Your Code's Environment Variables Hardcoding API keys into your source code is security risk and frequently leads to formatting issues. Most production apps use environment variables. If your code is passing an empty string or `undefined`, you will trigger a 401 error.
If using Node.js, ensure you are importing and running dotenv before initializing the OpenAI client: `javascript require('dotenv').config(); const { OpenAI } = require('openai');
// If process.env.OPENAI_API_KEY is undefined, this will fail with a 401 const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, }); `
If using Python, check that the environment variable is exported in your terminal or loaded via python-dotenv: `python import os from openai import OpenAI
Ensure your terminal has run: export OPENAI_API_KEY="your-actual-key" client = OpenAI( api_key=os.environ.get("OPENAI_API_KEY"), ) ```
To debug, temporarily log the first 5 characters of your loaded key to the console to verify it is reading correctly (never log the entire key in production logs): console.log(process.env.OPENAI_API_KEY.substring(0, 5));
Step 3: Strip Spaces and Quotes from Configuration Files Configuration files (like `.env` or `.yaml` files) sometimes introduce hidden characters that invalidate your key. * **Check for quotes:** Do not wrap your key in single or double quotes in your `.env` file unless your library explicitly requires it. Use `OPENAI_API_KEY=sk-proj-abc123...` instead of `OPENAI_API_KEY="sk-proj-abc123..."`. * **Check for trailing whitespace:** Ensure there are no accidental spaces at the end of the key line in your configuration. A single space at the end of the key will cause the server to reject it.
Step 4: Validate Custom HTTP Request Headers If you are not using the official OpenAI SDK and are making raw `fetch` or `curl` requests instead, a malformed header is a highly common cause of the 401 error.
Your header must follow this exact syntax: Authorization: Bearer YOUR_API_KEY
Example curl request: `bash curl https://api.openai.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer sk-proj-YOUR_ACTUAL_KEY_HERE" \ -d '{ "model": "gpt-4o-mini", "messages": [{"role": "user", "content": "Hello!"}] }' ` Ensure "Bearer" is capitalized and separated from the key by a single space.
Step 5: Verify Organization and Project Restrictions If your user account belongs to multiple OpenAI organizations, or if you use restricted Projects, your key may be tied to a specific project scope. * When generating a new key in the dashboard, check the **Project** dropdown. If you restrict the key to "Project A", any API calls specifying "Project B" (or default organization calls) using that key will fail with a 401 error. * If your code specifies organization headers, ensure they match: * Node.js: `organization: "org-XXXXX"` * Python: `organization="org-XXXXX"`
---