Calling the real API safely: keys, environment variables, spending limits

Study time
≈ 3 h (estimate)
Needs
L1-M01-L04, L1-M02-L05
Updated
2026-11-06

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L1-M03 LLM API Testing · Duration: ~165 min (estimate, including the independent exercise) · Previous: L1-M02-L05 · Next: L02 - Testing request parameters: max_tokens, stop sequences, system and removed parameters

1. Introduction

From this module on, you test real code that uses the official SDK: the integration layer that the product uses to talk to the model. In the lab, the SDK is pointed at a fake API running on your machine; the real API is used only in an optional live test. In L1-M01-L04 you read the response JSON; here you use the official SDK (anthropic for Python) and check how the product's code uses it.

Calling the real API carries three risks that ordinary software testing rarely meets:

  1. A leaked API key. A key is money: whoever has the key can spend your company's money.
  2. Cost. Every request costs money, and a broken test loop can send thousands of requests.
  3. Data. Everything you send is processed by the provider.

This lesson teaches how to set things up to test safely, and introduces the module's main tool: a fake API running on your machine, so you can test the real SDK without a real key and without spending money.

2. Learning objectives

  1. Explain the three risks of calling the real API (key, cost, data) and one measure for each risk.
  2. Configure the API key through an environment variable, and verify with a test that the application reports an error at startup if the key is missing.
  3. Calculate the cost of a request from usage and the price table, and use a budget guard to block requests that exceed the budget.
  4. Run the integration-layer test suite with the real SDK pointed at a fake API, and distinguish it from a live test.
  5. Verify that the key sits only in a header, not in the body of the request.

3. Prerequisites and tools

  • L1-M01-L04 (request, response, stop reason, usage) and L1-M02 (the prompt is an artifact).
  • Python and pytest at the level of L1-M01 and L1-M02, including conftest.py and fixtures.
  • You do not need an API key for this lesson. The live test is optional and costs money (section 8.6).

4. Concepts

4.1 API keys and environment variables

An API key is a secret string used to authenticate with the provider. An environment variable is a value set outside the code, which the operating system passes to the program when it runs, for example ANTHROPIC_API_KEY. Putting the key in an environment variable instead of in the code keeps the key from being committed to Git.

Everyday example. An API key is like the card that opens the till in a coffee shop: whoever holds the card can open the till, and the machine does not ask who they are. Nobody tapes the card to the counter for convenience (a key in the code); the card stays in the shift manager's pocket (an environment variable), and it is handed over in person at the change of shift.

A .env file holds environment variables in the form NAME=value for convenience during development. Rules:

  • .env is always in .gitignore. This lab already has a .gitignore that blocks .env.
  • Commit only .env.example, a sample file with no real values.
  • The key is used only on the server side. Never put the key in code that runs in a browser or a mobile app, because users can read it.

Good vs bad. The same job: let the code read the key. The bad way puts the key in the code:

# tutor_client.py, committed to Git
client = anthropic.Anthropic(api_key="sk-ant-REAL-KEY-HERE")

The good way: the code holds no key, make_client() reads ANTHROPIC_API_KEY from the environment, and the two files have different roles:

# .env.example (committed): names only, no values
# ANTHROPIC_API_KEY=

# .env (listed in .gitignore, never committed)
ANTHROPIC_API_KEY=sk-ant-REAL-KEY-HERE

Why: anything that reached Git can be read by anyone who can read the repo, or any copy of it, even after you delete the line in a later commit. A leaked key must be revoked, not just deleted.

4.2 Cost

Providers charge per token, with different prices for input and output. Anthropic's price table on 2026-10-31 [R1], base prices per million tokens (MTok):

Model Input Output
Claude Opus 5.5 $4 / MTok $20 / MTok
Claude Sonnet 5.5 $2 / MTok $10 / MTok
Claude Haiku 5.5 (prompts up to 100,000 tokens) $0.10 / MTok $0.50 / MTok

Prices change. Do not hard-code prices without recording the date and the source. The lab records both in lab/budget.py.

Formula: cost = (input_tokens × input_price + output_tokens × output_price) / 1,000,000, with the token counts taken from the response's usage (L1-M01-L04).

Everyday example. It is like a delivery fee where pick-up and drop-off are charged separately. Here there are two "meters": input tokens (what you send) and output tokens (what the model writes). On all three models in the table, one output token costs 5 times one input token, so long answers are what make the bill grow.

Worked example. One LinguaBot question on Sonnet 5.5 ($2 input, $10 output per MTok): 1,200 input tokens, the model answers with 350 tokens, and max_tokens is 1,024.

  1. Input part: 1,200 × 2 = 2,400.
  2. Actual output part: 350 × 10 = 3,500.
  3. Actual cost: (2,400 + 3,500) / 1,000,000 = $0.0059.
  4. Worst case, the model uses all 1,024 tokens: (2,400 + 1,024 × 10) / 1,000,000 = 12,640 / 1,000,000 ≈ $0.0126, more than twice the actual cost. Section 4.3 uses this number.

4.3 Two layers of cost protection

  1. The account's spending limit. According to the rate limits documentation [R2], each tier (the account's level on the Claude Console; each level has its own limits) has a monthly spend cap (for example the Start tier: $500), and you can set your own lower limit on the Billing page of the Claude Console. When the limit you set is reached, requests get error 400 with a message starting with You have reached your specified API usage limits. When the tier's cap is reached, requests get error 429, with no retry-after header, and error.details.error_code is enforced_spend_limit_reached [R2].
  2. A budget guard in the test code. Before each request, compute the worst case (assume the model uses all of max_tokens) and refuse if it exceeds the budget of the test run.

Everyday example. A bank card has a spending limit set by the bank (the tier's cap), and you can set a lower limit yourself in the app (the self-set limit). A budget guard is the habit of asking before you order: "if this dish is the most expensive it can be, do I still have enough money?", instead of ordering first and reading the bill afterwards.

Worked example (real run). The question from section 4.2, with a budget of $0.03 for the whole run. Run it from the lab folder:

python - <<'EOF'
from lab.budget import BudgetGuard, cost_usd

print(f"one reply, actual (1,200 in / 350 out): ${cost_usd('claude-sonnet-5-5', 1200, 350):.4f}")
print(f"one reply, worst case (max_tokens=1024): ${cost_usd('claude-sonnet-5-5', 1200, 1024):.4f}")
guard = BudgetGuard(limit_usd=0.03)
for i in range(1, 6):
    try:
        guard.check("claude-sonnet-5-5", 1200, 1024)
        guard.record("claude-sonnet-5-5", 1200, 350)
        print(f"request {i}: allowed, spent ${guard.spent_usd:.4f}")
    except RuntimeError as e:
        print(f"request {i}: refused ({e})")
EOF

Output (2026-11-06, Linux; Python 3.14.6 and 3.12.3 give identical results):

one reply, actual (1,200 in / 350 out): $0.0059
one reply, worst case (max_tokens=1024): $0.0126
request 1: allowed, spent $0.0059
request 2: allowed, spent $0.0118
request 3: allowed, spent $0.0177
request 4: refused (budget: worst case $0.0303 exceeds limit $0.0300)
request 5: refused (budget: worst case $0.0303 exceeds limit $0.0300)

Line by line: request 4 is refused although only $0.0177 has been spent, because the guard checks $0.0177 + $0.0126 = $0.0303 > $0.03. A guard based on the actual cost would let all 5 requests through ($0.0295) and would only notice an overrun too late, if one answer were longer than usual.

4.4 Fake API: testing the real SDK without a real model

The fake API (lab/fake_api.py) is a small HTTP server running on your machine. It replies with exactly the JSON structure and server-sent events in the documentation, with content chosen by the test. The real SDK is pointed at it with the base_url parameter.

Kind of test What it calls Cost Stable What it can verify
Unit test (L1-M01, L1-M02) Our own code, no HTTP 0 Yes Pure logic
Test with the fake API (this module) Real SDK + real HTTP + fake server 0 Yes How our code uses the SDK; error handling; the request that is sent
Live test (real integration) The real API Costs money Not fully (L1-M01-L03) The real API returns what we assumed

Common misconception: "A test with a fake has no value because it is not the real API." A fake lets you test things that cannot be tested reliably against the real API, such as a 529 error, a timeout or a rate limit, exactly when you want them. But a fake does not prove that the real API behaves the same way. That is why you still need a small number of live tests (section 8.6), and the fake must be kept in line with the documentation.

Everyday example. Learning to drive on a practice course: you can create hard situations yourself (a hill start, reversing into a bay) as often as you like, with no fuel cost and no danger. But passing the course does not prove you can drive in rush-hour traffic. The fake API is the practice course, the live test is the real road: you need both, in different amounts.

5. Technical deep dive

5.1 Where the SDK reads the key

The Python SDK reads the key from the ANTHROPIC_API_KEY environment variable when you do not pass a key in code. The lab observed with anthropic 2.3.0 (2026-10-31):

  • The client is created without an error even when there is no key. The error (TypeError: Could not resolve authentication method...) only appears when the first request is sent.
  • That is why the lab's make_client() calls require_api_key() to fail right at startup, instead of when the first learner sends a question.
  • The SDK sends the key in the Authorization: Bearer ... header. (The curl example in the documentation uses the x-api-key header [R3].) The two ways differ, so every mechanism that redacts sensitive data must handle both.
  • The SDK sends the anthropic-version: 2026-10-21 header by itself. The documentation says that the SDKs handle this version header automatically [R4].

Everyday example. An HTTP request is like a parcel. The headers are what is written on the outside (sender, authentication code, version), the body is the goods inside (JSON with the model, the messages...). The key belongs on the outside, and the goods inside must never contain it.

Good vs bad. Same goal, "the key does not leak in the request":

Weak test Good test
assert ask(client, "hi").ok: only knows the request succeeded Reads api.requests[0], asserts the key is in the authorization header and not in the body (the test in section 8.4)

The weak test still passes if a later change accidentally copies the key into the body, because it never looks at what was sent.

5.2 The Python you need for this lesson

  • monkeypatch is a built-in pytest fixture. monkeypatch.setenv("NAME", "value") sets an environment variable, monkeypatch.delenv("NAME") removes it, and monkeypatch.setattr(module, "NAME", value) replaces a value in a module. Every change takes effect only within one test and is undone automatically when the test ends. Everyday example: like borrowing a meeting room; you rearrange the tables for your meeting, and when you are done the room goes back to how it was for the next people.
  • A fixture with yield: the code before yield runs before the test (for example starting the fake API), the value after yield is handed to the test, and the code after yield runs when the test is done (for example shutting down the server). In conftest.py, with FakeClaudeAPI() as fake: yield fake does both.
  • pytest.param attaches a marker to one value of parametrize, for example pytest.param(" ", marks=pytest.mark.xfail(strict=True, reason="...")). If you put xfail on the whole test function, the values that pass become XPASS, and strict=True treats XPASS as FAIL.

5.3 The lab's conftest.py: never use real credentials

The fake_credentials fixture (autouse, meaning it applies to every test automatically) sets ANTHROPIC_API_KEY to a fake key and removes the other credential variables. Thanks to this, even if your machine has a real key, the offline tests cannot send it. The live test is excluded from this fixture with the live marker.

Everyday example. A bank lets new tellers practise on a training machine with training cards. Even if a trainee has a real card in their wallet, the training machine is set up to accept only training cards, so no real transaction can happen during practice.

6. The QA perspective

  • What to test: a missing key gives a clear error at startup; the key never appears in the body, logs or error messages; every test run has a cost limit; the live test does not run by default.
  • Why: a leaked key and a surprise invoice are incidents with real financial consequences.
  • What can go wrong: the key is committed; the key is in frontend code; a test loops forever calling the real API; CI runs the live test on every commit.
  • Expected behaviour: the offline tests run anywhere without a key; the live test runs only when explicitly enabled and with a budget.
  • How to detect it: tests with the fake API record every request; a budget guard; scanning the repo for strings that look like keys before committing.
  • How to report it: for a security defect, do not paste the real key into the bug report. Record the location and how to reproduce it, then ask for the key to be revoked immediately.

7. Real-world scenarios

Scenario 1 - A key in a mobile app (fictional). An English-learning app calls the API directly from the app to "save on servers", and the key sits in the installation package. A user unpacks the app and gets the key. Lesson for the tester: check the architecture. Requests to the model provider must go through our own backend.

Scenario 2 - An expensive test loop (fictional). A regression test runs 500 sentences, each 5 times, with max_tokens=4096 on the most expensive model, on every commit. The monthly invoice shoots up. Measure: offline tests on every commit; the live test runs on a schedule, with a budget guard and a spending limit on the Console.

8. Hands-on tutorial

8.1 Setup

cd academy-content/code-labs/l1-m03
python3 -m venv .venv
source .venv/bin/activate          # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt

requirements.txt pins anthropic==2.3.0 and pytest==9.2.0. This lesson does not need a key.

8.2 Lab structure

code-labs/l1-m03/
├── lab/
│   ├── fake_api.py       # server giả, nói đúng cấu trúc của Messages API
│   ├── tutor_client.py   # tầng tích hợp của LinguaBot (code được test)
│   ├── budget.py         # bảng giá + budget guard
│   ├── streaming.py      # L04
│   ├── cassette.py       # L05
│   └── demo.py           # demo cho từng bài: python -m lab.demo l01
├── tests/
│   ├── conftest.py       # key giả, fixture api và client
│   └── live/             # live test tùy chọn (tốn tiền)
└── .env.example

In English, the comments read: the fake server, speaking exactly the structure of the Messages API; LinguaBot's integration layer (the code under test); price table and budget guard; a demo for each lesson; fake key, the api and client fixtures; optional live tests (they cost money).

8.3 Running the demo

python -m lab.demo l01

Actual output (2026-10-31):

result: ok=True reason=complete request_id=req_fake_0001 usage=10/3
sent anthropic-version: 2026-10-21
key appears in body: False
cost of 1,000 in / 500 out on claude-opus-5-5: $0.0140
request 1: allowed, spent $0.0068
request 2: refused (budget: worst case $0.0136 exceeds limit $0.0100)
request 3: refused (budget: worst case $0.0136 exceeds limit $0.0100)

Reading the result:

  • request_id=req_fake_0001: the SDK reads the request ID from the response's request-id header. Put the request ID in the bug report so the provider's team can look it up [R3].
  • The key is not in the body.
  • Budget guard: the budget is $0.01; the worst case of one request (200 input tokens, at most 300 output tokens on Opus 5.5) is $0.0068. The second request is refused because $0.0068 × 2 = $0.0136 exceeds the budget. The guard counts the worst case, not the actual cost.

8.4 Running the tests

python -m pytest tests/test_l01_setup.py -v

Expected result: 8 passed. The whole lab: python -m pytest -rs gives 60 passed, 1 skipped (not counting tests you add yourself). The skipped test is the live test.

def test_sdk_sends_version_and_key_only_in_a_header(client, api):
    ask(client, "hi")
    sent = api.requests[0]
    assert sent["headers"]["anthropic-version"] == "2026-10-21"
    assert sent["headers"]["authorization"] == f"Bearer {FAKE_KEY}"   # anthropic 2.3.0 behaviour
    assert FAKE_KEY not in str(sent["body"])

This test is a characterization test (L1-M01-L01) for the behaviour of SDK 2.3.0. If a new SDK release changes how the key is sent, the test will flag it, and you update the sensitive-data redaction to match.

8.5 Troubleshooting

Symptom Cause Fix
RuntimeError: ANTHROPIC_API_KEY is not set when running your own demo Your code calls make_client() outside a test Set the environment variable, or run through pytest (which uses a fake key)
ModuleNotFoundError: No module named 'anthropic' The requirements are not installed in the venv python -m pip install -r requirements.txt
The tests hang for a long time A firewall blocks connections to 127.0.0.1 Allow local connections, or run in another terminal

8.6 Live test (optional, costs money)

tests/live/test_live_smoke.py sends one real request and runs only when you explicitly enable it.

Safe steps:

  1. Create a separate key for learning on the Claude Console, and set a low spending limit (for example a few dollars).
  2. The lab does not read the .env file by itself. Load the key into the shell so that it does not end up in the command history:
    • macOS/Linux: read -s ANTHROPIC_API_KEY && export ANTHROPIC_API_KEY (type the key when asked; the key is not shown and is not saved in the history), or set -a; source .env; set +a if you use .env.
    • Windows PowerShell: $env:ANTHROPIC_API_KEY = Read-Host and then $env:RUN_LIVE = "1".
  3. Run (macOS/Linux): RUN_LIVE=1 python -m pytest -m live -s. Read the test first so you know what it sends.
  4. After running: unset ANTHROPIC_API_KEY (PowerShell: Remove-Item Env:ANTHROPIC_API_KEY), and revoke the key on the Console if you no longer use it.

The worst-case cost of one run is small (one request, max_tokens=100, at most 3 sends because of retries), but the steps above matter more than that figure: they are the habits you will use at work. The default model is claude-opus-5-5. You can set LIVE_MODEL to a cheaper model (for example claude-haiku-5-5): that is your cost decision. The course team has not run this live test while writing the lesson (2026-10-31), so there is no sample output yet.

9. Independent exercise

Problem: require_api_key() was written to block an invalid key right at startup.

Tasks:

  1. Copy exercises/test_l01_key_check.py into tests/. Test with two values: the empty string "" and a string of spaces only " ".
  2. Record which value is not blocked.
  3. Write a bug report: title, steps to reproduce, expected, actual, severity, and a proposed fix.

Test data: "" and " ".

Deliverable: the test file and the bug report. The starter file already marks only the " " value with xfail(strict=True) using pytest.param (section 5.2): after you write the assert, the "" case passes and the " " case is reported as XFAIL. Do not put xfail on the whole function.

Acceptance criteria: the test runs; the observed result is recorded correctly; the bug report is reproducible and does not contain a real key.

Hint: read the condition in require_api_key() carefully. Is the string " " "empty"?

9.1 Extra exercise: the budget of a live test run

Problem (about 20 minutes): before a live test run, your lead asks: "With this budget, how many requests will the guard allow?" You answer with a function, and the function is compared with the real BudgetGuard.

Requirements:

  1. Copy exercises/test_l01_extra_budget.py into tests/.
  2. Write requests_allowed(model, input_tokens, typical_output_tokens, max_tokens, limit_usd) with cost_usd() and arithmetic only. Do not use BudgetGuard: the test blocks it.
  3. Run python -m pytest tests/test_l01_extra_budget.py.

Test data: the four cases in CASES, including the demo of section 8.3 and the worked example of section 4.3.

Acceptance criteria: untouched, 4 failed with a TODO message; when done, 4 passed.

Hint: the guard checks the worst case before each request, but records the actual cost after it. Two common shortcuts both fail: dividing the budget by the actual cost, or by the worst-case cost. Work out the example of section 4.3 by hand first (the guard allows 3 requests), then run.

9.2 Real-world scenario: reviewing the "Explain a word" pull request

Context (fictional): a pull request adds an "Explain a word" feature to LinguaBot. The PR description says:

  • The mobile app calls the Claude API directly; the key sits in the app's config.js, "temporary, it will move to the backend later".
  • A .env file with the real key is committed "so that CI can run".
  • A new test test_explain_word_live lives in tests/ without the live marker: 200 words, one Opus 5.5 request per word with about 150 input tokens and max_tokens=2048, run on every commit.
  • To make debugging easier, the code logs all headers of every request.

Your task: write a review note for the PR: a list of risks ordered by severity, each with evidence, impact, a test or review step that would catch it, and a proposed fix. Compute the worst-case cost of the new test for one run.

A good answer has:

  • all four risks, with the key in the app and the key in Git at the highest severity;
  • a request to revoke the committed key, not just delete the file;
  • the worst-case cost of the new test, with the calculation from the price table in section 4.2, and a note that retries can multiply that number;
  • for each risk, a concrete test or check (for example a test that the key is not in the logs, the live marker, a budget guard);
  • no real key anywhere in the note itself.

10. Knowledge check

0/20 done · Results are kept in this browser only.

P02 · True or false

A test run against the fake API proves that the real API will return exactly the same thing.

P03 · Short answer

(Calculation) A request on Claude Sonnet 5.5 uses 2,000 input tokens and 400 output tokens. Using the price table in the lesson, what does it cost?

P04 · Short answer

Why does the budget guard count max_tokens instead of the actual number of output tokens?

P05 · Short answer

(Scenario) A colleague wants to run the live test on every commit "to be safe". How do you propose organising the tests?

P06 · Match

Using the table in §4.4, match each kind of test with what it can verify.

P08 · Multiple choice

According to §5.2, if you put pytest.mark.xfail(strict=True) on the whole test function that has the two values "" and " ", and the "" case passes, how does pytest report the "" case?

P09 · True or false

If your machine has a real ANTHROPIC_API_KEY, the lab's offline tests will send that real key to the fake API.

P10 · Spot the bug

The check function below is copied from BudgetGuard in lab/budget.py but has one defect. Find it.

def check(self, model, input_tokens_estimate, max_tokens):
    worst = cost_usd(model, input_tokens_estimate, max_tokens)
    if worst > self.limit_usd:
        raise RuntimeError(f"budget: worst case ${self.spent_usd + worst:.4f} exceeds limit ${self.limit_usd:.4f}")
    return worst

P11 · Recall

Lesson: L1-M02-L05

L1-M02-L05: for test results to be comparable between runs, what must a test report record?

P12 · Put in order

Put the safe steps for running the live test in order, following §8.6.

  1. Load the key into the shell so that it does not end up in the command history
  2. Create a separate key for learning on the Claude Console and set a low spending limit
  3. unset ANTHROPIC_API_KEY, and revoke the key on the Console if you no longer use it
  4. Read the test, then run RUN_LIVE=1 python -m pytest -m live -s

P13 · Short answer

You find a real API key in a commit of the repo. What does your bug report contain, and what does it not contain?

P15 · Multiple choice

In the worked example of §4.3 (Sonnet 5.5, a $0.03 budget), why is request 4 refused?

P16 · Fill in the blank

From the worked example of §4.2: a Sonnet 5.5 request with 1,200 input tokens and 350 output tokens costs $; if the model uses all 1,024 of max_tokens, it costs about $.

P17 · True or false

Committing a .env.example file that contains only the line # ANTHROPIC_API_KEY= (no value) is safe.

P18 · Select all that apply

According to §5.1 and §6, which checks detect a key that is sent or stored in the wrong place?

P19 · Apply now

In code-labs/l1-m03, run the code from the worked example of §4.3, then run it again with limit_usd=0.05.

Checklist

P20 · Apply now

In code-labs/l1-m03, do the extra exercise in §9.1: copy exercises/test_l01_extra_budget.py into tests/ and run python -m pytest tests/test_l01_extra_budget.py.

Checklist

11. Summary

  • Concepts: the three risks (key, cost, data); environment variables and .env; the account's spending limits (400 when your own limit is reached, 429 with no retry-after when the tier's cap is reached); the budget guard; the fake API, as distinct from a live test.
  • Skills: configure a key safely; calculate cost; run real-SDK tests against the fake API; verify the request that is sent.
  • Traps: a key in the frontend; the live test on every commit; trusting the fake as you trust the real API; hard-coding prices without recording the source.
  • You can now: set up a safe test environment for an LLM integration.

12. References

ID Title Publisher URL Accessed Relevance
R1 Pricing Anthropic https://platform.claude.com/docs/en/about-claude/pricing 2026-10-31 Per-MTok prices of Opus 5.5, Sonnet 5.5, Haiku 5.5
R2 Rate limits (spend limits, spend cap) Anthropic https://platform.claude.com/docs/en/api/rate-limits 2026-10-31 Spend cap per tier; 400 when your own limit is reached; 429 enforced_spend_limit_reached
R3 Claude API errors (request ID) Anthropic https://platform.claude.com/docs/en/api/errors 2026-10-31 The request-id header; the curl example uses x-api-key
R4 Versions Anthropic https://platform.claude.com/docs/en/api/versioning 2026-10-31 The anthropic-version header; the SDK handles it

Version note: the SDK behaviour in this lesson is that of anthropic 2.3.0, observed on 2026-10-31. Prices and limits change; check R1 and R2 again before each teaching round.

Key terms (English ↔ Vietnamese)

English Tiếng Việt
API key Khóa bí mật để xác thực khi gọi API
Environment variable Biến môi trường
SDK (Software Development Kit) Bộ thư viện chính thức để gọi API
Spend limit / spend cap Giới hạn chi tiêu tự đặt / trần chi tiêu của tier
Budget guard Cơ chế chặn request vượt ngân sách
Fake API Server giả trả lời theo cấu trúc của API thật
Live test Test gọi API thật
Request ID Mã định danh của một request, dùng khi báo lỗi