Home → Help

401 invalid API key — when the key looks right but still fails

A 401 means the request reached the API and the key was rejected — which is good news. The URL is right; only the credential is wrong.

What you are seeing

Why it happens

This is worth separating from the HTML-instead-of-JSON case. Getting a clean JSON 401 proves your base URL is correct and the request is being routed properly. You are one small fix away rather than debugging the wrong layer.

The most common cause is not a wrong key at all — it is an invisible character. Copying from a terminal or a web UI often picks up a trailing newline or a non-breaking space, and the comparison fails on a key that looks identical on screen.

Confirm it is this

Print the key's length and check it against what the dashboard shows. An off-by-one is the giveaway:

# Python
import os
k = os.environ["API_KEY"]
print(len(k), repr(k[-4:]))

# shell
printf '%s' "$API_KEY" | wc -c

If repr() shows '\n' or the length is one more than expected, that is your answer.

How to fix it

  1. Strip whitespaceTrim the key when you read it from an environment variable or a file. A trailing newline is invisible in every UI and breaks every comparison.
  2. Check the header nameOpenAI-style endpoints expect Authorization: Bearer KEY. Anthropic-style endpoints expect x-api-key. Sending the right key in the wrong header returns 401 with no hint about which mistake you made.
  3. Check what the key is allowed to reachOn gateways where keys are scoped to a plan or group, a valid key can still be refused for a model outside its scope. Some return 401 rather than a clearer error. List the models your key can see before assuming the key itself is bad.
  4. Confirm the key still existsDeleted and rotated keys usually fail as 401 rather than 404. If you rotated recently, make sure the running process was restarted — a long-lived process keeps the old value in memory.
On APICLAN you can list what a key can reach with curl https://apiclan.us/v1/models -H "Authorization: Bearer YOUR_KEY". Keys are scoped to one group, so a key made for one plan will not work on another.

Related

Unexpected token '<' when calling an OpenAI-compatible API404 on /v1/chat/completions when the endpoint clearly exists

Last checked 2026-08-24. Written from problems diagnosed on a live OpenAI-compatible gateway, not collected from other sites.