401 Unauthorized or invalid_api_key means thatThe authentication information carried in the current request is not accepted by the target API.. It's usually not a network glitch and shouldn't be resolved by retrying.
Direct answer
Troubleshoot 401 in this order: confirm that the API key and Base URL belong to the same platform, confirm that the request has only one Authorization: Bearer, confirm that the running process loaded the current key, and finally check that the request path contains only one /v1. Use the same key to request /v1/models; if it still returns 401, stop retrying and check the key status and account permissions.
30 seconds to determine where the problem is
First test the model list directly, outside clients such as Cursor or Dify. Use only a key created on AIFast HK: set AIFAST_API_KEY in your local environment. Do not send another provider's key to this endpoint.
if [ -n "$AIFAST_API_KEY" ]; then
curl --connect-timeout 10 --max-time 30 -sS -i \
https://www.aifast.hk/v1/models \
-H "Authorization: Bearer $AIFAST_API_KEY"
else
printf '%s\n' 'AIFAST_API_KEY is not set'
fi
Triage based on results:
| result | Priority check |
|---|---|
| curl also returns 401 | Key content, account status, request header and target platform |
| curl is successful, the client returns 401 | Environment variables, configuration priorities and duplication read by the client Bearer |
| One domain name is successful, another domain name is 401 | Key and Base URL do not belong to the same platform |
| Occasionally successful, occasionally 401 | Inconsistent configuration across instances, an old key still in use, or requests reaching different endpoints |
A 200 model-list response only confirms that this request was accepted. It does not validate generation endpoints, group permissions or balance. If listing is restricted or unsupported, do not conclude that the key is invalid. Check permissions against the provider documentation, then send one short request to the target endpoint with a limited test key. Generation requests may incur charges.
What is the difference between api_key_required and invalid_api_key?
The first usually means required authentication information was not received; the second usually means the supplied credentials were rejected. Error names vary between gateways, so retain both the HTTP status and redacted error body. api_key_required alone does not establish a billing problem.
| Request type | Check first |
|---|---|
| OpenAI Compatible | Clients usually add Authorization: Bearer; do not prepend Bearer in the key field |
| Anthropic Messages or another native protocol | Check authentication and version headers in the target provider's documentation instead of reusing OpenAI settings unchanged |
| Model listing succeeds but generation fails | Compare the host, credential source, model permissions and error body of both requests |
Do not paste the complete key into online Q&A, Issues, logs or screenshots. When debugging, only 3 to 4 digits before and after are reserved to distinguish between different keys.
Why does curl work but the client still prompts invalid_api_key?
This usually means the key is valid but the client is sending different settings. Check whether the client is reading a stale environment variable and whether Bearer is being added twice, whether a workspace setting overrides the Base URL, and whether the request is sent to a different domain. Do not keep creating new keys just because curl succeeds. First compare the redacted key fingerprint, target domain, and request-header source in the client diagnostics.
Also check whether the final URL contains /v1/v1. After confirming the result, return to the client to clean up the duplicate configuration.
Check six positions in order
1. Whether Key and Base URL belong to the same platform
Keys created by third-party platforms cannot be sent directly to the official OpenAI address, and official OpenAI Keys should not be sent to other gateways by default. First confirm that these two configurations come from the same service:
Base URL: https://www.aifast.hk/v1
API Key: in AIindependent API key created in the AIFast console Key
If you are migrating from another platform, you must replace both the Base URL and the Key, not just one.
2. Is the Authorization request header correct?
OpenAI-compatible APIs typically use:
Authorization: Bearer sk-***
Common mistakes include:
- written as
Authenticationor other request headers; - Missing
Bearerand the space before the key; - The client has automatically added
Bearer, but the configuration value includes it again; - There are quotation marks before and after the Key, newlines, or spaces mixed in when copying;
- Reverse proxy does not forward
AuthorizationRequest header.
3. Whether the current process has actually read the new environment variable
Modifying the shell configuration file does not mean that the running program has been updated. First only confirm the existence and length of the variable, do not output the complete content:
test -n "$AIFAST_API_KEY" && echo "Key Loaded, length ${#AIFAST_API_KEY}" || echo "Key not loaded"
IDEs, desktop clients, Docker containers, and system services may not inherit current terminal variables. After modification, the corresponding process should be restarted and checked in its own running environment.
4. Are there multiple sets of configuration coverage?
Check items .env, user-level configuration, workspace configuration and startup parameters. The typical phenomenon is: the terminal curl uses the new Key, but the client still reads the revoked Key from the old configuration file.
Only one authentication source is retained at a time during troubleshooting. After confirming success, restore the required configuration level.
5. Is the Key still available?
Confirm that the Key has not been deleted, disabled, or rotated, and the account status is normal. Do not use production keys for public debugging; create test keys with controlled permissions and balances.
6. Whether the final request was sent to the expected domain name
The Base URL in the client interface is not necessarily equal to the final request address. Confirm via client diagnostic log or server request logging:
- final hostname;
- final path;
- Whether the request passes through an additional proxy;
- The error type and request ID in the response body.
Can be used first Base URL online checker Check the address splicing and go back to the client configuration.
Python SDK minimal validation
import os
from openai import OpenAI
client = OpenAI(
base_url="https://www.aifast.hk/v1",
api_key=os.environ["AIFAST_API_KEY"],
max_retries=0,
timeout=30.0,
)
models = client.models.list()
print("Model-list request succeeded, number of models returned:", len(models.data))
Temporarily turn off automatic retries when troubleshooting 401s. The authentication configuration remains unchanged and resending the same request will not restore itself.
Don’t use these three wrong methods
- Continuously retry 401. It will only amplify the log and request volume, but will not fix the authentication.
- Send the complete key to others for review. The public Key should be revoked and a new Key should be created.
- Change the Key, model, agent and SDK versions at the same time. There are too many variables, and the root cause cannot be confirmed even after success.
Acceptance criteria for repair completion
/v1/modelsUse the target Key to stably return success;- Minimal non-streaming request succeeds and returns parsable body;
- The client log shows that the request was sent to the expected domain name;
- The old key has been revoked, and no plaintext key remains in repositories or logs;
- 401 no longer enters the automatic retry queue.
After authentication succeeds, you can continue usingModel Quality CheckCheck model declarations, tokens, SSE, and tool calls; if 404 occurs or the model does not exist, go toModel not found and /v1/v1 troubleshooting.