Tickd.ai
API errors

How to Fix OpenAI API Error 401 (Unauthorized)

Updated 11/29/2026

An HTTP 401 Unauthorized error from the OpenAI API indicates that your request failed to authenticate. This means the API gateway rejected your credentials before processing any data.

This guide covers how to identify the exact cause of a 401 error and the steps required to resolve it in your codebase.

Understand Why the 401 Error Occurs

A 401 Unauthorized status code occurs for one of four reasons: 1. Invalid API Key: The key you are passing contains a typo, is missing characters, or has been deleted from the OpenAI developer dashboard. 2. Incorrect Headers: Your code is not formatting the HTTP Authorization header correctly. 3. Failed Environment Variable Loading: Your code is trying to read an environment variable that is empty or not loaded into system memory. 4. Incorrect Organization Selection: Your key belongs to an organization that is different from the one hardcoded in your request headers.

Follow these steps in order to isolate and fix the authentication failure.

Agent Builder turns a task you repeat into a reusable assistant with setup text for each app.

Tickd is independent and not affiliated with any AI company.

Open Agent Builder

1. Verify Your API Key is Active

First, confirm that the API key you are using actually exists and is active:

  1. Log in to the [OpenAI Platform Dashboard](https://platform.openai.com/).
  2. Navigate to API Keys in the left sidebar.
  3. Look at your list of active keys. If the key you are using has been deleted, you must generate a new one.
  4. If you are using a restricted key, verify that its permissions allow access to the specific endpoints (e.g., /v1/chat/completions) you are calling.

2. Test the Key with a Raw cURL Request

To rule out issues with your SDK, library, or framework, test your API key using a direct HTTP request in your terminal. Replace $OPENAI_API_KEY with your actual plaintext key:

`bash curl https://api.openai.com/v1/models \ -H "Authorization: Bearer $OPENAI_API_KEY" `

  • If this returns a JSON list of models: Your API key is valid. The issue lies within your application's code, SDK initialization, or environment variable loader.
  • If this still returns a 401 error: Your API key itself is invalid. Generate a brand-new API key from the dashboard and try again.

3. Fix Environment Variable Loading Issues

Most developers run into 401 errors because their application fails to read the API key from an environment variable, resulting in sending a null, undefined, or empty string to OpenAI.

Python Fix If you are using Python, ensure you are loading your `.env` file before initializing the client:

`python import os from dotenv import load_dotenv from openai import OpenAI

Explicitly load the .env file load_dotenv()

Verify the key is loaded in memory api_key = os.getenv("OPENAI_API_KEY") if not api_key: raise ValueError("OPENAI_API_KEY environment variable is empty")

Initialize the client client = OpenAI(api_key=api_key) ```

Node.js Fix In Node.js, ensure `dotenv` is configured at the very top of your entry file (e.g., `index.js` or `server.js`):

`javascript import dotenv from 'dotenv'; dotenv.config();

import { OpenAI } from 'openai';

if (!process.env.OPENAI_API_KEY) { throw new Error("OPENAI_API_KEY is not set in environment variables"); }

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, }); `

4. Check for Hidden Spaces and Formatting Errors

Sometimes, API keys copied from the OpenAI dashboard contain trailing spaces, newlines, or quotation marks inside the environment configuration files.

  • Inspect your .env or system configuration files. Ensure there are no quotes around the key unless explicitly required by your parser:
  • Correct: OPENAI_API_KEY=sk-proj-abc123XYZ...
  • Incorrect: OPENAI_API_KEY="sk-proj-abc123XYZ... " (contains a trailing space inside quotes)
  • Ensure you did not copy-paste the "Project ID" (which starts with proj_) or the "Organization ID" (which starts with org_) into the API key field. OpenAI API keys typically start with sk-.

5. Verify Organization and Project Routing

If your API key is restricted to a specific project or organization, sending requests to the wrong endpoint or passing an incorrect organization header will yield a 401 error.

If you are manually setting the organization header, verify that it matches your developer console settings:

`python # Remove this line if you do not explicitly need to scope to a specific organization client = OpenAI( api_key=os.environ.get("OPENAI_API_KEY"), organization="org-YourActualOrgID" ) `

When to Escalate

If you have confirmed that your API key works via a raw curl request, but fails in your production environment (such as AWS Lambda, Vercel, or Heroku), check your cloud provider's environment variable settings. Cloud platforms often require a redeployment or function restart to apply new environment variables.

If your API key returns a 401 error on both curl and your local environment, and creating a new key does not fix it, check your account standing in the [OpenAI Billing Portal](https://platform.openai.com/settings/organization/billing/overview). Accounts that are suspended, past due, or lacking a valid credit card balance may have their API keys temporarily deactivated, throwing an authorization error.

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