How do I fix an "invalid API key" or 401 error with AI APIs?
1 Answer
A 401 error, often reported as "unauthorized," "invalid API key" or "authentication error," means the AI provider could not verify who is making the request. It is one of the most common problems when starting with AI APIs, and it is almost always a configuration issue.
Common causes:
1. The key was copied incorrectly, with missing characters or extra spaces or line breaks.
2. The environment variable is not loaded, so your code sends an empty key.
3. You are using a key from one provider with another provider's API, for example an OpenAI key with Anthropic's endpoint.
4. The key was deleted, revoked or rotated in the dashboard.
5. The key belongs to a different project or organisation than the one you are trying to access.
6. The header format is wrong. Different providers expect the key in different headers.
7. Billing is not set up, or the account has no credits, which some providers report as authentication or permission errors.
A step-by-step checklist:
1. Print a safe check. In your code, temporarily print the length of the key and its first few characters, never the full key, to confirm it is loaded.
2. Check the environment variable name. A typo like OPENAI_KEY instead of OPENAI_API_KEY is very common.
3. Restart your terminal, editor or server after setting environment variables, because running processes do not pick up new values.
4. Generate a new key in the provider's console and replace the old one.
5. Confirm the endpoint matches the provider.
6. Use the official SDK, which handles headers correctly.
7. Check billing and credits in the dashboard.
8. Check project and organisation settings, if the provider uses them.
9. Test with a minimal example from the official documentation to isolate the problem.
Security practices to follow:
Never hard-code API keys in source code.
Never commit keys to Git. Use a .env file listed in .gitignore, or a secrets manager.
Never put keys in front-end JavaScript or mobile apps, where anyone can extract them. Call the AI API from your own back-end server.
If a key is exposed, for example pushed to GitHub, revoke it immediately and create a new one. Automated bots scan public repositories for leaked keys within minutes.
Use separate keys for development and production, and set spending limits.
A 403 error is different: it usually means your key is valid but lacks permission for the requested model or feature. Check your account's access and tier.