Sub topic 8
Checking That It Works Without Printing the Key
You have a key stored in an environment variable or a .env file, and your code reads it. This chapter shows how to confirm the whole chain works without the key appearing in your terminal, logs, or screenshots. It assumes you can run shell commands, read short Python snippets, and know that an HTTP API answers requests with numeric status codes.
What "it works" means
A working setup passes three separate checks. Each one fails in a different way, so run them in order.
- Presence. The variable exists in the process that needs it.
- Shape. The value has no stray whitespace, quotes, or truncation.
- Acceptance. The provider accepts the key and answers with a success status.
You can run all three without ever printing the secret. Print facts about the key, such as whether it exists and how long it is. Never print the key itself.
Check 1: Is the variable set?
The first example from earlier in this tutorial prints only the length:
export LLM_API_KEY="paste-your-key-here"
echo "${#LLM_API_KEY} characters set"${#LLM_API_KEY} is the shell's length operator. A result of 0 characters set means the variable is empty or missing. If you only need a yes or no answer, this form avoids printing anything about the value:
if [ -n "${LLM_API_KEY:-}" ]; then echo "set"; else echo "missing"; fiThe :- makes the test safe even if you run the shell with set -u, which otherwise aborts on unset variables.
Shell checks only tell you about the shell. A program started from an IDE, a service manager, or a container has its own environment, and it may not have your variable. Run the same check from inside the program you care about.
Check 2: Does the process see a well-formed key?
Most "my key doesn't work" problems come from the value, not the key. Common causes:
- A trailing newline or space copied from the console.
- Quotation marks that became part of the value. This happens with
docker run --env-file, which keeps quotes literally.python-dotenvstrips them. - A key pasted twice, or cut off in the middle.
Test for these without printing the value:
import os
api_key = os.environ.get("LLM_API_KEY")
if not api_key:
print("missing or empty")
elif api_key != api_key.strip():
print("has leading or trailing whitespace")
elif api_key[0] in "\"'" or api_key[-1] in "\"'":
print("has quote characters around it")
else:
print(f"present, {len(api_key)} characters")Compare the length to the key length shown in your provider console or documentation. If your provider uses a known prefix, you can test api_key.startswith("prefix-"). That prints nothing secret and catches a swapped or wrong-provider key.
Avoid printing the last four characters "to identify it". Many consoles show a masked tail, so it feels safe. But a short tail narrows nothing down for you, and it trains you to print parts of secrets. Length and a boolean prefix test are enough.
Check 3: Does the provider accept it?
The only proof that a key is valid is a request to the provider. Send the smallest request that requires authentication, and print only the status code. This is the pattern from the earlier example, wrapped into a reusable script:
import os
import sys
import requests
API_URL = "https://api.example.com/v1/chat" # placeholder: use your provider's documented endpoint
MESSAGES = {
401: "key rejected: wrong, revoked, or malformed",
403: "key valid but not allowed to do this",
404: "endpoint or model not found: check the URL and model name",
429: "rate limit or spend limit reached",
}
def main() -> int:
api_key = os.environ.get("LLM_API_KEY")
if not api_key:
print("FAIL: LLM_API_KEY is not set")
return 1
if api_key != api_key.strip():
print("FAIL: key has leading or trailing whitespace")
return 1
print(f"OK: key present, {len(api_key)} characters")
try:
response = requests.post(
API_URL,
headers={"Authorization": f"Bearer {api_key}"},
json={"prompt": "Say hello"},
timeout=30,
)
except requests.RequestException as exc:
print(f"FAIL: could not reach the provider ({type(exc).__name__})")
return 2
status = response.status_code
if 200 <= status < 300:
print(f"OK: provider accepted the request (status {status})")
return 0
print(f"FAIL: status {status}: {MESSAGES.get(status, 'unexpected response')}")
return 3
if __name__ == "__main__":
sys.exit(main())The script never prints the key, the request headers, or the response body. It reports only type(exc).__name__ for network errors, because some exception messages include request details. Different exit codes (1, 2, 3) let a CI job or shell script tell the failure kinds apart.
Reading the status code
| Status | Likely meaning | First thing to check |
|---|---|---|
| 2xx | Key accepted | Nothing. Move on. |
| 401 | Key missing, wrong, or revoked | Check 2 again, then the console |
| 403 | Key is valid but lacks permission | Key scope, project, or model access |
| 404 | Wrong URL or model name | Provider docs |
| 429 | Rate limit or spend limit | Usage page and limits |
| 5xx | Provider-side problem | Provider status page, retry later |
Some providers return 400 for malformed requests and use their own error bodies. Check your provider's documentation for exact codes. A 400 usually means the key passed authentication and your request body is wrong, which is progress.
The same check with curl
curl is handy for a quick test, but it has two traps. The -v flag prints request headers, including your Authorization header. Putting the key directly in the command line makes it visible to other users through the process list, and it lands in shell history. This version avoids both:
printf 'Authorization: Bearer %s\n' "$LLM_API_KEY" \
| curl -s -o /dev/null -w "%{http_code}\n" \
-X POST "https://api.example.com/v1/chat" \
-H @- \
-H "Content-Type: application/json" \
-d '{"prompt": "Say hello"}'printf is a shell built-in, so the key is not exposed as a command-line argument. -H @- tells curl to read header lines from standard input (supported since curl 7.55). -s hides the progress meter, -o /dev/null discards the body, and -w "%{http_code}\n" prints only the status. The URL is again a placeholder.
Prove that the check can fail
A check that has never failed might be broken. After you see success once, deliberately break it:
- Unset the variable and run the script. You should see
FAIL: LLM_API_KEY is not setand exit code 1. - Set a clearly fake value such as
export LLM_API_KEY="not-a-real-key"and run it again. A real endpoint should answer 401.
Then restore the real value in a new shell session, so the fake one does not stay in your environment. Check the exit code with echo $? right after each run.
Keeping the check itself safe
A verification script is code that handles a secret, so the same rules apply.
- Log status codes and error categories, not headers or full request objects.
- Do not print
response.request.headersor the result ofvars(response.request). - Treat response bodies with care. Error bodies from some APIs echo parts of the request, so print them only after you have seen what your provider returns.
- Run the check from the same place the real code runs: your laptop, the CI job, and the deployed service each need their own run.
- Keep test requests tiny. Each successful call may be billed, so a one-line prompt and a short output limit keep a health check cheap.
Exercise
Your script prints "OK: key present, 52 characters", but the provider answers 401. The console says the key is 51 characters long. What is the most likely cause, and how do you confirm it without printing the key?
Show answer
The value probably has one extra character, most likely a trailing newline or space copied from the console, or a quote character kept by a loader such as docker --env-file. Confirm it by testing api_key != api_key.strip() and by checking whether the first or last character is a quote, printing only the boolean results. Then fix the stored value and run the check again. A length mismatch alone is enough to explain a 401.
Exercise
A teammate debugging a failed request adds print(response.request.headers) to the script and pastes the output into a chat. What went wrong, and what should the team do next?
Show answer
The headers include the Authorization: Bearer <key> line, so the key is now in the chat. Treat it as leaked: revoke the key in the provider console, create a new one, and update every place that uses it. Remove the print statement and log only the status code and error type in future.