Sub topic 2
Authenticating with an API key
This chapter covers how an API key proves who you are, how to send it, and how to keep it out of places where it can leak. It assumes you can use a terminal, set environment variables, read JSON, and recognize HTTP status codes such as 401 and 403. You should also have seen a basic HTTP request to an LLM endpoint, as in the previous chapter.
What an API key is
An API key is a long secret string that your provider issues to your account or project. The server uses it to answer two questions about each request:
- Who is calling? This is authentication. The key maps to an account, a project, or a service.
- What may they do, and who pays? This is authorization and billing. Usage is metered against the owner of the key, and the key may be limited to certain models or operations.
A key is a bearer credential. Whoever holds the string is treated as the owner. There is no second factor and no check of where the request came from. If someone copies your key from a public repository, they can spend your money and read whatever your account's API exposes, until you revoke the key.
Because of this, treat an API key like a password. Anything that applies to passwords also applies to keys: don't share them, don't commit them, don't paste them into chats or screenshots, and rotate them when in doubt.
Sending the key: the Authorization header
In the chat-completions request shape used throughout this tutorial, the key travels in an HTTP header on every request:
Authorization: Bearer <your key>The word Bearer is the authentication scheme. It tells the server that the rest of the header value is a token whose holder is the caller. The key does not go in the JSON body and should not go in the URL.
Providers differ here. Some use a different header name, such as x-api-key, and some require extra version headers. The Authorization: Bearer form is common, but confirm it in your provider's documentation.
Why not the URL?
A key in a query string such as ?api_key=... ends up in many places that headers do not: server access logs, proxy logs, browser history, and the Referer header sent to other sites. Headers are far less likely to be logged by default. Prefer headers whenever the provider allows it.
Reading the key from the environment
Never write the key into source code. Read it at runtime from an environment variable. Set it in your shell:
export OPENAI_API_KEY="paste-your-key-here"
export LLM_MODEL="your-model-name"Then use it in a request. The shell expands $OPENAI_API_KEY before curl runs, so the key never appears in the script file:
curl https://api.openai.com/v1/chat/completions \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d @- <<EOF
{
"model": "$LLM_MODEL",
"messages": [
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what an API key is in one sentence."}
]
}
EOFNote that typing export OPENAI_API_KEY=... at a prompt stores the key in your shell history. Many shells let you avoid that by starting the command with a space (depending on the HISTCONTROL setting) or by loading the variable from a protected file instead.
The same approach works in Python:
import os
import requests
URL = "https://api.openai.com/v1/chat/completions"
HEADERS = {
"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
"Content-Type": "application/json",
}
payload = {
"model": os.environ["LLM_MODEL"],
"messages": [
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what a token is in one sentence."},
],
}
resp = requests.post(URL, headers=HEADERS, json=payload, timeout=30)
resp.raise_for_status()
data = resp.json()
choice = data["choices"][0]
print(choice["message"]["content"])
print("finish_reason:", choice["finish_reason"])
print("usage:", data["usage"])os.environ['OPENAI_API_KEY'] raises a KeyError if the variable is missing. That is a useful failure: the program stops at startup with a clear cause instead of sending an empty credential and getting a confusing server error later.
The request flow
The diagram shows what happens to the key on a single call.
Authentication errors
When authentication fails, the server returns an error status before it looks at your prompt. No tokens are generated, so these failures are cheap and quick to diagnose.
| Status | Typical meaning | Common causes |
|---|---|---|
| 401 | The server could not authenticate you | Missing header, typo in the key, extra whitespace or newline, revoked or expired key, wrong provider |
| 403 | You are authenticated but not allowed | Key lacks permission for the model or endpoint, account region or policy restriction |
| 429 | Rate or quota limit | Often a spending cap or exhausted credit, covered in a later chapter |
Exact status codes and error body formats vary by provider. Some return 403 where others return 401, so read the error message in the body.
Common mistakes
- A trailing newline or space copied along with the key. If you load a key from a file, strip it:
key = open(path).read().strip(). - Quoting problems in the shell. Single quotes stop variable expansion, so
-H 'Authorization: Bearer $OPENAI_API_KEY'sends the literal text$OPENAI_API_KEY. Use double quotes, as in the example above. - The variable is set in one terminal but not in the one running the program. Check with
test -n "$OPENAI_API_KEY" && echo set, which reports whether it is set without printing the value. - Using a key from one provider against another provider's endpoint.
- Using a key that belongs to a different project than the model you requested.
Where keys must not go
Keep keys out of the following places:
- Source code and committed config files, including notebooks. Once a key is in git history, deleting the line does not remove it from earlier commits.
- Client-side code such as browser JavaScript or mobile apps. Anything shipped to a user's device can be extracted. Call the LLM API from your own server, and let the client call your server.
- Shared documents, chat messages, tickets, and screenshots.
- Application logs, error reports, and crash dumps. Redact the
Authorizationheader before logging requests. - Container images. A key baked in with
ENVor copied into a layer stays in the image.
A .env file is a common local convention for holding variables. If you use one, add it to .gitignore before you create it, so it cannot be staged by accident:
echo ".env" >> .gitignoreLimiting the damage
You cannot make a leaked key harmless, but you can reduce what a leak costs.
- Use one key per application and per environment (development, staging, production). Then you can revoke one without breaking the others, and usage reports show which service spends what.
- Set the narrowest permissions the provider offers. Some providers let you restrict a key to specific models or endpoints.
- Set a monthly spending limit or budget alert on the account, if available.
- Rotate keys on a schedule and whenever someone with access leaves the team.
- Use a secret manager in production rather than plain environment files. Cloud platforms and orchestrators can inject secrets into a process at start time, with access control and audit logs.
Responding to a leak
If a key may have been exposed, act in this order:
- Revoke or delete the key in the provider's console. This ends the exposure.
- Create a replacement and deploy it through your normal secret mechanism.
- Check usage and billing for activity you do not recognize.
- Find how it leaked, for example a commit, a log line, or a shared screenshot, and fix that path.
Rewriting git history is not a substitute for revoking. Assume anyone who could see the key has already copied it, since automated scanners watch public repositories for secrets within minutes.
A small startup check
A helper that fails early with a clear message saves time. This one verifies that the key is present and looks plausible without ever printing it:
import os
import sys
def load_api_key(name="OPENAI_API_KEY"):
key = os.environ.get(name, "").strip()
if not key:
sys.exit(f"{name} is not set. Export it before running this program.")
return key
API_KEY = load_api_key()
print(f"Loaded key ending in ...{API_KEY[-4:]}")Showing only the last four characters lets you tell keys apart without exposing the secret. For very short test keys, skip even that.
Summary
- An API key is a bearer credential. Anyone who has the string can act as you.
- Send it in the
Authorization: Bearerheader, not in the URL or body. - Read it from an environment variable or a secret manager. Never hard-code it.
- A 401 means the key was not accepted. A 403 means the key was accepted but lacks permission.
- Use separate, narrowly scoped keys, set spending limits, and revoke first if a key leaks.
Exercise
Your script sends this header with curl: -H 'Authorization: Bearer $OPENAIAPIKEY'. The variable is set correctly in your shell, yet the server returns 401. What is the most likely cause, and how do you fix it?
Show answer
Single quotes prevent the shell from expanding variables, so the server receives the literal text "$OPENAIAPIKEY" as the key. Use double quotes instead: -H "Authorization: Bearer $OPENAIAPIKEY".
Exercise
A teammate commits a key to a repository and then pushes a second commit that deletes it. Is the problem solved? List the steps you would take.
Show answer
No. The key remains in the git history and may already have been copied by scanners. Revoke the key in the provider console first, create and deploy a replacement through a secret mechanism, review usage for unfamiliar activity, and then find and fix how the key got into the commit (for example, add .env to .gitignore).
Exercise
Why should a browser-based chat application not call the LLM API directly with your key, and what is the alternative?
Show answer
Any code sent to the browser can be read by the user, so the key would be exposed and could be reused by anyone. Instead, the browser calls your own server, which holds the key, applies your rules and limits, and forwards the request to the LLM API.