Your First API Call
Adding AI to an app means calling a model provider's API from your server: you send messages, it returns generated content. This track uses Anthropic's Claude API with the official Python SDK, inside a Flask app. The same architecture (server-side calls, secrets in env vars, streaming, tools, structured output, cost control) applies to OpenAI and other providers through their own SDKs.
Get a key and keep it secret
Create an API key in the provider console and store it as an environment variable. Never put it in frontend JavaScript, Git or client apps: anyone could read it and spend your money.
export ANTHROPIC_API_KEY="sk-ant-..." # locally; on Render/Railway use the dashboard
pip install anthropic
A first request
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
system="You are a concise assistant for a web development learning platform.",
messages=[{"role": "user", "content": "Explain what a REST API is in two sentences."}],
)
for block in response.content:
if block.type == "text":
print(block.text)
print(response.usage.input_tokens, response.usage.output_tokens)
model: which model to use. Model IDs change as new versions ship; keep the ID in configuration, not scattered through code.system: stable instructions for the whole conversation.messages: the conversation, alternatinguserandassistant.response.contentis a list of blocks (text, thinking, tool use). Check each block'stypebefore reading.text.usagetells you tokens used, which is what you pay for.
Choosing a model
| Model (ID) | Use for |
|---|---|
Claude Opus 5.5 (claude-opus-5-5) |
the default: complex reasoning, coding, agents |
Claude Sonnet 5.5 (claude-sonnet-5-5) |
fast, capable, high-volume production work |
Claude Haiku 5.5 (claude-haiku-5-5) |
simple, very high-volume tasks (classification, routing) |
Prices and model lists change; check the provider's model and pricing pages when you build.
Conversations are stateless
The API does not remember previous calls. To continue a chat, send the full history each time:
history = [
{"role": "user", "content": "My name is Ada."},
{"role": "assistant", "content": "Nice to meet you, Ada!"},
{"role": "user", "content": "What is my name?"},
]
client.messages.create(model="claude-opus-5-5", max_tokens=16000, messages=history)
Store history in your database per conversation and trim or summarise it when it grows long.
Exercise
Write a script that asks the user a programming question, sends it with a helpful system prompt, prints the answer and the token usage, and keeps the conversation going for three turns.
Check yourself
- Why must the API key stay on the server?
- Why check
block.typebefore reading text? - How does the model "remember" earlier messages?
Votre progression est enregistrée dans ce navigateur uniquement.
Envoyer pour relecture (10 points)