Module 4

Your First API Call

Tool use and structured outputs are where most API labs begin. Here you run a small version of both, so a live lab is your second time seeing them and not your first.

About 40 minPreps you for: API labs: tool use and structured outputs
â„šī¸
Not a programmer? Do Task 2 anyway
You do not need to understand every line. Copy the file, run it, and read the output. Seeing a real reply come back to your own laptop makes everything after this concrete. Task 3 is optional for you.

What an API call is

The Claude app is a chat window made for people. The API is the same models, made for programs. Your code sends a request with three things, and gets a response back:

You sendMeaning
modelWhich Claude to use, such as claude-haiku-5-5.
max_tokensThe most the reply is allowed to be. A safety cap on length and cost.
messagesThe conversation so far, as a list of turns. Each turn has a role (user or assistant) and content.

The response contains the reply text, a stop_reason saying why the model stopped, and a usage count of tokens in and out. Tokens are what you are billed for.

đŸ–Ĩī¸ Hands-on task 2Everyone⏱ 10 min

Hello, Claude

  1. Open a terminal, cd into your bootcamp-primer folder and activate the virtual environment (Module 3, step 8).
  2. Create a file named hello_claude.py in that folder and paste this in. Any text editor works, including Notepad or TextEdit in plain text mode.
hello_claude.py
import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from your environment

message = client.messages.create(
    model="claude-haiku-5-5",
    max_tokens=200,
    messages=[
        {"role": "user", "content": "In two sentences, what is an AI agent?"}
    ],
)

# The reply is a list of blocks. Pick the text one (some models add a thinking block first).
answer = next(block.text for block in message.content if block.type == "text")
print(answer)
print("---")
print("Tokens in:", message.usage.input_tokens, "| Tokens out:", message.usage.output_tokens)
  1. Run it.
Mac
python3 hello_claude.py
Windows
python hello_claude.py
  1. Change the question inside the quotes to something from your own work, and run it again.

Notice there is no key in the file. anthropic.Anthropic() finds it in the environment variable you set in Module 3. That is the habit to keep.

✓ Done when: the terminal prints a two-sentence answer, then a line like Tokens in: 22 | Tokens out: 120. Your numbers will differ a little.

If Task 2 fails

Error mentionsCause and fix
authentication_error or 401The key is missing or wrong. Open a new terminal and check the variable is set: echo $ANTHROPIC_API_KEY on Mac, echo $env:ANTHROPIC_API_KEY on Windows. Do this in private, as it prints your key.
credit balance too lowThe key works but the Console account has no credits. Add about $5 under Billing.
No module named anthropicThe virtual environment is not active. Run the activate line from Module 3.
not_found_error for the modelThe model name was mistyped. Copy it again from the file above.

Tool use: how a model "does" things

In Module 1 you read that the model never runs a tool itself. Here is what that looks like in practice. It takes two API calls:

Call 1You send the question plus a description of your tool.
Claude repliesNot with an answer, but with a request: "run get_session_time with session = Lab 2".
Your codeRuns the real function and gets the result.
Call 2You send the result back. Claude writes the final answer.

Wrap those steps in a while loop that repeats until Claude stops asking for tools, and you have an agent. That loop is the first thing built in Level 10, Lesson 81.

đŸ–Ĩī¸ Hands-on task 3Developers⏱ 20 min

A tool and a JSON answer

Part A: tool use. Save this as tool_use.py and run it.

tool_use.py
import anthropic

client = anthropic.Anthropic()
MODEL = "claude-haiku-5-5"

# 1. Describe the tool. Claude never runs it. It only asks you to.
tools = [
    {
        "name": "get_session_time",
        "description": "Look up the start time of a workshop session by its name.",
        "input_schema": {
            "type": "object",
            "properties": {
                "session": {"type": "string", "description": "Session name, e.g. 'Lab 2'"}
            },
            "required": ["session"],
        },
    }
]

# 2. Your real function. In a real agent this would hit a database or an API.
AGENDA = {"lab 0": "Day 1, 10:00 AM", "lab 1": "Day 1, 11:00 AM", "lab 2": "Day 1, 2:15 PM"}

def get_session_time(session: str) -> str:
    return AGENDA.get(session.lower(), "No session by that name")

messages = [{"role": "user", "content": "When does Lab 2 start?"}]

# 3. First call: Claude decides it needs the tool.
response = client.messages.create(model=MODEL, max_tokens=300, tools=tools, messages=messages)
print("stop_reason:", response.stop_reason)

# 4. Run the tool Claude asked for, and send the result back.
if response.stop_reason == "tool_use":
    tool_call = next(block for block in response.content if block.type == "tool_use")
    print("Claude asked for:", tool_call.name, tool_call.input)
    result = get_session_time(**tool_call.input)

    messages.append({"role": "assistant", "content": response.content})
    messages.append({
        "role": "user",
        "content": [{"type": "tool_result", "tool_use_id": tool_call.id, "content": result}],
    })

    # 5. Second call: Claude turns the tool result into an answer.
    final = client.messages.create(model=MODEL, max_tokens=300, tools=tools, messages=messages)
    answer = next(block.text for block in final.content if block.type == "text")
    print("Answer:", answer)

Then try these, one at a time, and watch what changes:

  1. Change the question to "When does Lab 9 start?". The tool returns "No session by that name". How does Claude handle it?
  2. Change the question to "What is 2 + 2?". What is the stop_reason now, and why?
  3. Rewrite the tool's description to something vague like "does stuff". Does Claude still call it? This is why tool descriptions get so much attention.

Part B: structured output. Save this as structured_output.py and run it.

structured_output.py
import json
import anthropic

client = anthropic.Anthropic()

email = """Hi, this is Priya from Acme Corp. Our invoice #4471 for $2,350 was due
on Nov 3 and we were charged twice. Please refund the duplicate. Thanks!"""

response = client.messages.create(
    model="claude-haiku-5-5",
    max_tokens=300,
    messages=[{"role": "user", "content": f"Extract the details from this email:\n\n{email}"}],
    output_config={
        "format": {
            "type": "json_schema",
            "schema": {
                "type": "object",
                "properties": {
                    "customer_name": {"type": "string"},
                    "company": {"type": "string"},
                    "invoice_number": {"type": "string"},
                    "amount_usd": {"type": "number"},
                    "request_type": {"type": "string", "enum": ["refund", "question", "complaint", "other"]},
                },
                "required": ["customer_name", "company", "invoice_number", "amount_usd", "request_type"],
                "additionalProperties": False,
            },
        }
    },
)

text = next(block.text for block in response.content if block.type == "text")
data = json.loads(text)  # guaranteed to parse and match the schema
print(json.dumps(data, indent=2))
print("Refund amount:", data["amount_usd"])

The output_config block hands Claude a JSON schema. The reply is then guaranteed to parse and to contain exactly those fields, so the last line can safely read data["amount_usd"]. Without a schema you would be picking a number out of free text and hoping. Try adding a field of your own, such as due_date, to both properties and required.

✓ Done when: (a) tool_use.py prints stop_reason: tool_use, the tool request, and an answer containing 2:15 PM, and (b) structured_output.py prints a JSON object and Refund amount: 2350.

What it cost

All three files together use well under two thousand tokens. On Haiku 5.5, at $0.10 per million input tokens and $0.50 per million output tokens, that is a small fraction of one cent. You can check your actual spend any time in the Console under Usage.

You will also hear about vision, which means sending an image as part of a message. It uses the same messages shape you just saw, with an image block next to the text. No prep needed.

Next: MCP in 30 minutes.