Skip to content

Lesson 15 ยท The Claude API

Your First Claude API Request

Send your first Claude API request: set up a key safely, call the Messages API with Python or curl, read content blocks and stop reasons, and keep history.

The Claude API lets your own program send messages to Claude. It is how you add Claude to a website, a script or an internal tool. API use is billed by usage, separately from the app subscription price, although as of December 2026 the pricing page lists included API credits for some paid plans. None of the real API code in this lesson runs on this site.

Set up

  1. Create an account in the Claude Console and create an API key.
  2. Store the key in an environment variable named ANTHROPIC_API_KEY.
  3. Install the official SDK: pip install anthropic for Python, or npm install @anthropic-ai/sdk for JavaScript and TypeScript.

Before you put it in an application

A first script and a real service differ in a few important ways. Check these before other people use your code:

  • Where the key lives. Use your platform's secret storage, not a file in the project. Use separate keys for development and production.
  • Who can call it. If a web page calls your server and your server calls Claude, require sign-in or rate limits. Otherwise strangers can spend your money through your endpoint.
  • How large input can be. Limit the length of user text and the size of files before you send them.
  • What you log. Log the request ID, model, token counts, latency and stop reason. Store user content only if you need it and are allowed to.
  • What users see. Show a helpful message for errors, cut-off answers and declined requests, and never a raw stack trace.

Common first errors

If the first call fails, read the error type and message. An authentication error usually means that the key is missing, mistyped or not visible to the process, for example because you set the environment variable in a different terminal. An invalid request error usually names the field that is wrong, such as a missing max_tokens or a mistyped model ID. A billing error means that the account's payment setup needs attention. Change one thing at a time and try again.

The system prompt in an application

Treat the system prompt as part of your program. Describe the assistant's job, audience, limits and what to do with requests outside its job. Keep it in version control and test changes against a fixed set of inputs, including hostile ones. Do not put secrets in it: assume that a determined user may get the model to reveal what the prompt says. It also cannot enforce access rules. If a user must not see some data, your code must keep that data out of the request in the first place, whatever the system prompt says.

An API key spends your money. Never put it in browser code, mobile apps, public repositories, screenshots or chats. Call the API from your own server, set spending limits, and revoke a key at once if it leaks.

The raw HTTP request

This lesson uses the Messages API: a POST to https://api.anthropic.com/v1/messages.

Terminal
curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2026-10-21" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-opus-5-5",
    "max_tokens": 1000,
    "messages": [{"role": "user", "content": "Explain DNS in two sentences."}]
  }'

The x-api-key header identifies you, and anthropic-version picks the API version; the value above is the one used in the documentation as of December 2026. Three body fields are required: model, max_tokens (a ceiling on output) and messages.

The same call in Python

Python
import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY

response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1000,
    system="You explain networking to beginners. Use plain words.",
    messages=[{"role": "user", "content": "Explain DNS in two sentences."}],
)

if response.stop_reason == "refusal":
    print("The model declined the request.")
else:
    for block in response.content:
        if block.type == "text":
            print(block.text)
    if response.stop_reason == "max_tokens":
        print("[answer was cut off]")

print(response.usage.input_tokens, response.usage.output_tokens)

The system instruction is a top-level parameter, separate from the conversation in messages.

Reading the response

response.content is a list of blocks. A block can be text, thinking, a tool request or another type. Do not assume that the first block is the text. Loop over the list and check block.type.

stop_reason says why generation stopped:

Value Meaning
end_turn Finished normally
max_tokens Hit your output limit, so it may be incomplete
stop_sequence Reached one of your stop sequences
tool_use Wants you to run a tool
pause_turn A long server-tool turn paused; send it back to continue
refusal Declined to answer
model_context_window_exceeded Ran out of context; treat as cut off

A successful HTTP response can still be incomplete or declined, so always check.

This stand-in handles hand-made dictionaries shaped like responses. It calls nothing.

Python Stand-in: read blocks and stop reasons safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In the first made-up response, code that read the text from the first block would fail, because that block is not a text block.

Conversations are stateless

The Messages API does not remember your earlier calls. For a multi-turn chat, you send the history each time, with user and assistant turns.

Python
history = []

def ask(question):
    history.append({"role": "user", "content": question})
    response = client.messages.create(
        model="claude-opus-5-5", max_tokens=1000, messages=history
    )
    history.append({"role": "assistant", "content": response.content})
    return response

Append the whole content list, not only the text, so that other block types are preserved. History grows with every turn, and so does the input you pay for.

Python Stand-in: see how history grows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Older tutorials may show temperature, top_p or top_k, or start the assistant's reply for it ("prefill"). According to Anthropic's API reference as of December 2026, the sampling parameters are rejected under the current API version, and prefill is rejected on current models. Steer with clear instructions, and use structured outputs for fixed formats.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which three body fields does a basic Messages request require?

    These three are required. The key goes in a header.
  2. 2. How should you get the text from a response?

    Content is a list that can hold several block types.
  3. 3. What does the stop reason max_tokens mean?

    Treat the result as truncated.
  4. 4. How does the Messages API know about an earlier turn?

    The Messages API is stateless.

Summary

  • Keep API keys on the server and out of code and repositories.
  • Send model, max_tokens and messages; system is top-level.
  • Filter content blocks by type and check stop_reason.
  • You manage the conversation history.

Next: Choosing Models: Tokens, Thinking and Effort

Your progress is saved in this browser. No account needed.