Your First AI API Call in Python (Step-by-Step for Beginners)
Go from chatting with AI to building with it. A beginner-friendly, step-by-step guide to making your first AI API call in Python: getting a key, keeping it safe, sending a message, adding a system prompt, building a tiny chatbot and keeping costs under control.

Chatting with an AI in a browser is useful. Calling it from code is where things get exciting: you can summarise 500 support tickets, classify feedback automatically or build your own assistant into a product. This guide takes you from zero to a working AI program in Python in about 15 minutes.
We'll use Anthropic's Claude API with its official Python library. The ideas (API key, messages, system prompt, tokens) are the same across all the major AI providers.
What you need
- Python 3.10 or newer. Check with
python --version. - An API key from the provider's developer console (for Claude, that's the Claude Console). API usage is billed separately from chat subscriptions and is charged per token, so add a small amount of credit and set a spending limit.
- A terminal and a text editor. Or skip the setup and use Google Colab in your browser.
Step 1: Install the library
pip install anthropic
Step 2: Keep your API key safe
Your API key is like a password linked to your billing. Never paste it into your code, and never commit it to GitHub. Put it in an environment variable instead.
macOS / Linux:
export ANTHROPIC_API_KEY="your-key-here"
Windows (PowerShell):
$env:ANTHROPIC_API_KEY="your-key-here"
The library reads ANTHROPIC_API_KEY automatically, so your code never contains the key.
Step 3: Send your first message
Create a file called hello_ai.py:
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=1000,
messages=[
{"role": "user", "content": "Explain what an API is in two sentences."}
],
)
for block in response.content:
if block.type == "text":
print(block.text)
Run it:
python hello_ai.py
You should see a short explanation of APIs. Congratulations: you just built your first AI-powered program.
What each part means
| Part | What it does |
|---|---|
model |
Which AI model to use. Providers publish a list of current models with their prices. |
max_tokens |
The maximum length of the reply, in tokens (roughly ¾ of a word each). |
messages |
The conversation so far, as a list of user and assistant turns. |
response.content |
The reply, as a list of blocks. We print the text blocks. |
Step 4: Give it a role with a system prompt
A system prompt sets the AI's behaviour for the whole conversation: its role, tone and rules.
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=1000,
system="You are a friendly tutor for complete beginners. Use simple words and one everyday analogy.",
messages=[
{"role": "user", "content": "What is cloud computing?"}
],
)
Try changing the system prompt to "You are a strict senior engineer. Answer in 3 bullet points." and see how much the answer changes.
Step 5: Build a tiny chatbot
The API doesn't remember previous calls. To have a conversation, you send the whole history each time. Here's a complete terminal chatbot:
import anthropic
client = anthropic.Anthropic()
history = []
print("Chat with the AI (type 'quit' to exit)")
while True:
user_text = input("You: ").strip()
if user_text.lower() in {"quit", "exit"}:
break
history.append({"role": "user", "content": user_text})
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=1000,
system="You are a helpful, concise assistant.",
messages=history,
)
reply = "".join(b.text for b in response.content if b.type == "text")
print(f"AI: {reply}\n")
# Keep the assistant's reply so the next turn has full context
history.append({"role": "assistant", "content": response.content})
Notice the last line: we add the assistant's reply to history. That's all "memory" is in a basic chatbot. It's also why long chats get more expensive: every turn re-sends everything before it.
Step 6: Do something useful with it
Here's a small script that classifies customer feedback, the kind of task that saves real time:
import anthropic
client = anthropic.Anthropic()
feedback = [
"The course was great but the videos kept buffering.",
"I can't log in since yesterday.",
"Loved the labs, please add more on Kubernetes!",
]
for item in feedback:
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=50,
system=(
"Classify the feedback as exactly one word: "
"praise, bug, or feature_request. Reply with the word only."
),
messages=[{"role": "user", "content": item}],
)
label = "".join(b.text for b in response.content if b.type == "text").strip()
print(f"{label:16} | {item}")
Keeping costs under control
- Set a monthly spending limit in the provider's console before you start.
- Check
response.usageto see input and output tokens for each call. - Use a smaller, cheaper model for simple jobs like classification, and the most capable model for complex reasoning. Compare prices on the provider's pricing page.
- Cap
max_tokenswhen you only need a short answer. - Test on 10 items before running on 10,000.
Common errors and fixes
| Error | Usual cause | Fix |
|---|---|---|
| Authentication error (401) | Key missing or wrong | Check the environment variable is set in the same terminal you run Python from |
| Rate limit (429) | Too many requests too fast | Slow down; the library retries automatically a couple of times |
| Model not found (404) | Typo or retired model name | Copy the exact model ID from the provider's model list |
ModuleNotFoundError: anthropic |
Library installed in a different Python | Run python -m pip install anthropic |
Where to go next
Once a single API call works, the next steps are tool calling (letting the AI use your functions), RAG (answering from your own documents) and agents. The free course AI for Beginners has hands-on Google Colab labs for all of these, so you can run real code without installing anything. When you're ready to build production AI apps, continue with AI Builder.