How to make your first Claude API call in Python or Node

Day 3, 25 minutes · beginner

Goal of this lessonSend your first Claude API request from a Python or Node script and read the reply, the stop reason and the token usage.

Why it matters

Everything you will ever build on the Claude API starts with one request: send a message, get a message back. Once you have done that from your own script, the rest of this course is variations on it.

Today Linde asks Claude for a short thank you note to a happy customer, from a script on her own computer. You write that script, run it and then look inside the answer. The answer is more than text: it tells you why Claude stopped writing and how many tokens the request used, which is what you pay for. At the end you have a working first call and notes that you will compare against tomorrow.

What actually goes over the wire

Your script sends a request to the Messages endpoint: POST https://api.anthropic.com/v1/messages. POST means "here is some data, do something with it". Without an SDK you would send it yourself, with three headers (small labels on the request):

  • your key, in the Authorization header after the word Bearer, or in the older x-api-key header that many examples in the docs still use;
  • anthropic-version: the version of the API you expect, 2026-10-21 on the day this was written;
  • content-type: application/json.

The SDK sets all three for you, reads the key from ANTHROPIC_API_KEY and also retries some failed requests. That is why this course uses it.

The body of the request is JSON (a plain text format for data) with three required parts:

{
  "model": "claude-opus-5-5",
  "max_tokens": 1000,
  "messages": [
    { "role": "user", "content": "Write a two sentence thank you ..." }
  ]
}
  • model: which Claude model answers. claude-opus-5-5 is the one the docs suggest when you are unsure. Lesson 4 is about choosing.
  • max_tokens: the most tokens Claude may write in its answer. A token is a small piece of text, often part of a word. It is a ceiling, not a target.
  • messages: the conversation so far. Today that is one message with the role user, which is you.

What comes back

The response is a message from the assistant, which is Claude. Shortened, it looks like this:

{
  "id": "msg_...",
  "type": "message",
  "role": "assistant",
  "model": "claude-opus-5-5",
  "content": [
    { "type": "text", "text": "Thank you so much ..." }
  ],
  "stop_reason": "end_turn",
  "usage": { "input_tokens": 41, "output_tokens": 52 }
}
  • content is a list of blocks, not one string. Today you only need the blocks of type text. Other kinds of blocks exist (for thinking and for tools), so the script loops over the list and picks the text blocks, as the docs do. Do not assume the first block is the text.
  • stop_reason says why Claude stopped. end_turn means it finished on its own. max_tokens means it hit your ceiling and the answer is cut off. Lesson 6 covers the others.
  • usage has the input tokens (what you sent) and the output tokens (what Claude wrote). Your bill is based on these numbers.
  • id identifies this one message. For questions to support you need a different value, the request ID: in Python it is message._request_id.

Your numbers will differ from the example. Claude's wording can change from run to run, and the token counts follow the text.

The steps

  1. Turn on the virtual environment in your project folder.
  2. Create the script: load the key, make a client, send one message, print the text blocks, the stop reason and the usage.
  3. Run it and read the note Claude wrote for Linde.
  4. Print the whole response once, so you know what is in it.
  5. Write down the reply, the stop reason and the two token counts.

Follow the steps below.

If it does not work

  • AuthenticationError or a 401: the SDK found no valid key. Run check_key.py from lesson 2 again.
  • ModuleNotFoundError: No module named 'anthropic': the virtual environment is not turned on. Turn it on and try again.
  • An error about temperature: you copied code from an older tutorial. The current API version rejects temperature, top_p and top_k with a 400 error; leave them out.

Today's actions

Ticks are not saved without an account

Do it in Claude API

Claude API

  1. Open a terminal in your harbour-lane-replies folder and turn on the virtual environment again: source .venv/bin/activate on macOS or Linux, .venv\Scripts\Activate.ps1 on Windows.
  2. Create first_call.py with this code. It loads your key from .env, sends one message and prints the reply, the stop reason and the token counts.
    from dotenv import load_dotenv
    import anthropic
    
    load_dotenv()
    client = anthropic.Anthropic()
    
    message = client.messages.create(
        model="claude-opus-5-5",
        max_tokens=1000,
        messages=[
            {
                "role": "user",
                "content": "We are Harbour Lane Tea Co, a small online tea shop. Write a two sentence thank you to a customer who loved our Earl Grey.",
            }
        ],
    )
    
    for block in message.content:
        if block.type == "text":
            print(block.text)
    
    print("---")
    print("stop_reason:", message.stop_reason)
    print("input tokens:", message.usage.input_tokens)
    print("output tokens:", message.usage.output_tokens)
  3. Run python first_call.py. After a few seconds you see the thank you note, a line of dashes and three lines with numbers.
  4. Add the line print(message.to_json()) at the end of the file and run it again. Now you see the whole response: find id, model, content, stop_reason and usage.
  5. For Node instead of Python: save this as first_call.mjs and run node --env-file=.env first_call.mjs. To see the whole response, add console.log(JSON.stringify(message, null, 2)); at the end.
    import Anthropic from "@anthropic-ai/sdk";
    
    const client = new Anthropic();
    
    const message = await client.messages.create({
      model: "claude-opus-5-5",
      max_tokens: 1000,
      messages: [
        {
          role: "user",
          content: "We are Harbour Lane Tea Co, a small online tea shop. Write a two sentence thank you to a customer who loved our Earl Grey."
        }
      ]
    });
    
    for (const block of message.content) {
      if (block.type === "text") {
        console.log(block.text);
      }
    }
    
    console.log("---");
    console.log("stop_reason:", message.stop_reason);
    console.log("input tokens:", message.usage.input_tokens);
    console.log("output tokens:", message.usage.output_tokens);
  6. If you get an error: AuthenticationError (401) means the key is wrong, revoked or expired, so run check_key.py again. A billing_error (402) means a problem with your billing or payment details: check the Billing page in the Console.
  7. Copy the reply, the stop reason and the two token counts into a new file first-call-notes.txt. You compare against them in lesson 4.

Note: You can also try a prompt with no code at all in the playground of the Claude Console, at platform.claude.com/playground. The API credits page lists the playground among what your API credits pay for.

Paid planPay as you go: buy prepaid credits in the Claude Console (minimum 5 US dollars). There is no free tier. Max, Ultra and Team plans include monthly API credits.

Checked on 4 December 2026 · Source: Claude API docs: Get started with Claude (opens in a new tab)

Create a free account to save your progress. Sign in or sign up