Sub topic 2
Authenticating with an API key
This chapter assumes you can run Python and curl, set environment variables in a terminal, and read HTTP status codes. You should also know that an LLM API call is an HTTPS request carrying JSON.
What an API key does
An API key is a secret string that your provider issues to your account. The server uses it to answer two questions: who is calling, and who gets billed. Anyone who holds the key can make requests that are charged to you, so treat it like a password.
Most chat-completions style APIs read the key from the Authorization header using the Bearer scheme:
Authorization: Bearer sk-your-key-hereSome providers use a different header name, such as x-api-key. Check your provider's documentation for the exact form.
Keep the key out of your code
Never write the key into source files. Code gets committed, shared, and copied into logs and screenshots. Read the key from the environment instead.
Set it in your shell for the current session:
export OPENAI_API_KEY="paste-your-key-here"
export LLM_MODEL="your-model-name"Then reference the variable in a request. The shell expands $OPENAI_API_KEY before curl runs, so the key never appears in your script:
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."}
]
}
EOFIn Python, read the same variable with os.environ:
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": "user", "content": "Say hello."}],
}
resp = requests.post(URL, headers=HEADERS, json=payload, timeout=30)
print(resp.status_code)Using os.environ[...] with square brackets raises a KeyError if the variable is missing. That is the behavior you want, because the program stops at once instead of sending a request with no credentials.
If you keep keys in a .env file for local development, add that file to .gitignore before you create it.
How a failed login looks
When authentication fails, the server answers with a 4xx status code before it does any model work.
| Status | Typical meaning | What to check |
|---|---|---|
| 401 | The key is missing, malformed, expired, or revoked | The header name, the `Bearer ` prefix, stray spaces or newlines in the key |
| 403 | The key is valid but not allowed to do this | Project permissions, model access, region or organization limits |
Do not retry a 401 or 403 automatically. The same key will fail again, so the fix has to come from you.
Common mistakes
- Pasting a key with a trailing newline or quote characters, which makes it invalid.
- Forgetting the word
Bearerand the space after it. - Printing the full request headers while debugging. This writes the key into your logs.
- Sending the key from browser code. Anyone can read it in the network tab, so call the API from a server you control.
- Reusing one key everywhere. Prefer separate keys per project or environment so you can revoke one without breaking the rest.
Exercise
Your script prints 401 even though you are sure the key is correct. Name two things in the request, other than the key's value, that you would check first.
Show answer
Check that the header is Authorization: Bearer <key>, with the word Bearer and a single space. Also check that the key has no trailing newline, extra quotes, or spaces from copy and paste. Confirming the environment variable is set in the same shell session that runs the script is also valid.
Exercise
Why is os.environ["OPENAI_API_KEY"] preferable to os.environ.get("OPENAI_API_KEY", "") for building the header?
Show answer
Indexing raises a KeyError when the variable is missing, so the program fails immediately with a clear cause. The get version silently sends an empty key, and you only see a confusing 401 from the server.