---
title: "401 Invalid API Key: 6 Checks to Fix It in 2026 (With Commands)"
description: "An invalid api key 401 is rarely a broken key. It is usually a stray space, an env var, the wrong base URL, an auth header or project scope. Six checks, each with a command."
url: https://cdnping.org/en/blog/api-401-invalid-api-key
language: en
published: 2026-11-26
category: "Troubleshooting"
tags: ["API key","401","authentication","troubleshooting","OpenAI","Anthropic"]
source: cdnping.org
license: Free to quote and summarize with a link to the url above.
---
# 401 Invalid API Key: 6 Checks to Fix It in 2026 (With Commands)

When you hit `invalid api key` or `401 Unauthorized`, don't regenerate the key yet. In most cases the key was altered before it reached the server, sent to the wrong place, or sent to a service that doesn't recognize it. A 401 means "the server didn't recognize who you are." The six checks below are ordered from most to least common, and each can be verified with a single command.

## What is a 401 actually telling you?

HTTP 401 means authentication failed: the request carried no credentials, or the credentials were rejected. It is a different problem from 403 (authenticated, but not permitted) and 429 (rate limit or quota). Error text varies by provider. OpenAI commonly returns `Incorrect API key provided`; Anthropic commonly returns `authentication_error` with `invalid x-api-key`. Treat each provider's official documentation as the source of truth for exact wording and error codes. For the meaning of other status codes, see [AI API error codes 400 to 529: what each means and which to retry](/en/blog/ai-api-error-codes-400-to-529-cheatsheet).

## 1. Did the key pick up a space or newline when you copied it?

This is the most common cause. A key copied from a web page, a chat window or a PDF may carry a trailing space or newline, or an invisible character at the start.

```bash
# Print the key's length and its boundaries (printf avoids adding a newline)
printf '%s' "$OPENAI_API_KEY" | wc -c
printf '[%s]\n' "$OPENAI_API_KEY"
# Check for invisible characters
printf '%s' "$OPENAI_API_KEY" | od -c | head
```

There should be no space just inside the brackets, and the `od -c` output should not show `\r`, `\n` or odd multibyte characters. When you put the key in a `.env` file, also make sure there is no stray space after a quoted value.

## 2. Is the environment variable actually set where it matters?

Running `export` in one terminal doesn't mean your IDE, another terminal or a background process can see it.

```bash
echo "${OPENAI_API_KEY:0:8}"   # show only the first few characters, never the whole key
env | grep -i -E 'api_key|auth_token|base_url' | sed 's/=.*/=<hidden>/'
```

Common pitfalls:

- You edited `~/.bashrc` or `~/.zshrc` but didn't open a new terminal or run `source`.
- An IDE launched from a desktop icon doesn't read your shell config files.
- The same variable is defined in several places and an old value overrides the new one. Check the project's `.env`, system environment variables and the tool's own config file.
- On Windows, variables set with `setx` only apply to windows opened afterward.

If you use Claude Code, also watch for having both a subscription login and an API key configured. See [Claude Code auth conflict warning and how to fix 401](/en/blog/claude-code-auth-conflict-warning) and [Claude Code: API key login vs. subscription login, and how to switch](/en/blog/claude-code-api-key-login).

## 3. Do the key and the base URL match?

Each key is valid only on the service that issued it. Sending an OpenAI key to Anthropic's endpoint, or sending a key from a relay or aggregator to the official endpoint, returns 401. The reverse fails too: putting an official key into a tool that points at a third-party gateway.

What to check:

- Whether the "endpoint / Base URL" in your tool is the provider you intend to use.
- Whether the path at the end of the URL matches what the tool expects. Some tools require `/v1`, others append it themselves, and a duplicated or missing segment breaks the request. Follow the tool's documentation.
- Whether the config file still holds an address you used before.

A wrong Base URL is very common in "OpenAI Compatible" setups such as Cline. See [Cline OpenAI Compatible setup returns 401 or 404: what to put in Base URL](/en/blog/cline-openai-compatible-401-404-errors).

## 4. Is the auth header correct?

Different API formats use different auth headers:

| API format | Typical auth header | Notes |
| --- | --- | --- |
| OpenAI format | `Authorization: Bearer <key>` | Many compatible services follow this convention |
| Anthropic format | `x-api-key: <key>` | Also requires an `anthropic-version` header; check the official docs for the value |

The most direct test is curl, which bypasses every tool in between:

```bash
# OpenAI format: list models and print only the status code
curl -s -o /dev/null -w '%{http_code}\n' \
  https://api.openai.com/v1/models \
  -H "Authorization: Bearer $OPENAI_API_KEY"

# Anthropic format
curl -s -o /dev/null -w '%{http_code}\n' \
  https://api.anthropic.com/v1/models \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01"
```

A 200 means the key and the headers are fine, so the problem is in your tool's configuration. A 401 means you should print the response body too (drop `-o /dev/null`) and read the error message. If curl can't even return a status code, that is a network-layer problem rather than a 401; see [curl SSL_ERROR_SYSCALL: what to do](/en/blog/ssl-error-syscall-tls-handshake-fail).

## 5. Was the key revoked or deleted?

A key you deleted, one revoked by an organization admin, or one disabled by the platform will all turn into a 401. Check the provider's console key list to confirm the key still exists and is in good standing. If a key was ever pushed to a public repo or pasted into a chat, revoke it and create a new one rather than continuing to use it.

Also make sure the key belongs to the account and organization you expect. If the account or organization itself has been disabled, the error usually carries a corresponding message; see [Anthropic API organization disabled: causes, scope and what to do](/en/blog/anthropic-api-organization-disabled). In that situation, appeal through official channels or contact official support. Don't try to work around it by switching environments.

## 6. Are the project and permission scope right?

An OpenAI key can belong to a project and be restricted to certain endpoints and models. A key from project A accessing project B's resources, or a key restricted to read-only, can produce an authentication or permission error (401 or 403, depending on what actually comes back). For details, see [How to use OpenAI project API keys: per-project permissions and limits](/en/blog/openai-project-api-keys-permissions).

Running out of quota usually returns 429, not 401, so don't mix the two when troubleshooting.

## A quick checklist

1. Use `printf '[%s]'` to confirm there are no extra characters around the key.
2. Use `env` to confirm the current process really sees the right variable.
3. Confirm the key and the base URL belong to the same service.
4. Make one standalone curl request with the correct auth header and read the status code.
5. In the console, confirm the key isn't revoked and that its project and organization are correct.
6. If curl succeeds but the tool fails, recheck the tool's settings against its documentation.

You can also check [cdnping's API status page](/en/status) first to confirm the official endpoint was up at the time, so you don't mistake an outage for a configuration problem.

## If you'd rather not juggle keys and accounts

If you just want to use models in tools like Claude Code and Codex, you could look at AGI Plan. AGI Plan is a commercial partner of cdnping. It is a monthly-subscription, multi-provider LLM aggregation gateway, paid in RMB with no overseas credit card required. For Claude Code and Codex you only change the endpoint to its address and use the key it issues, and the same quota can be switched between multiple capability groups. It is compatible with both the OpenAI and Anthropic API formats, so the principles in checks 3 and 4 above still apply: use its key with its address. The service states that it is not an officially authorized channel, and some models are available only outside mainland China; see the [models page](https://agiplan.dev/models) for specifics. For setup steps, see the [getting started guide](https://agiplan.dev/startup).

## Next step

Start with the curl test from check 4. It splits the problem cleanly into "the key itself" or "the tool's configuration." The former sends you back to checks 1, 5 and 6; the latter to checks 2 and 3. If the error code isn't 401, go to the [error code cheat sheet](/en/blog/ai-api-error-codes-400-to-529-cheatsheet) for the matching fix.
