Your first API call: Python and the basics
Five lines of code can send a question to an AI model running in a data center somewhere, and get an answer back in your terminal. No website, no chat box, just your code talking directly to the model. That is an API call, and by the end of this lesson you will have made one.
What "APIAPIApplication Programming Interface: a standardised interface that lets applications communicate and exchange data without knowing each other's internal workings.View full definition → call" actually means
An API (Application Programming Interface) is a doorway one piece of software opens so other software can talk to it. When you use ChatGPT in your browser, you are the one typing. With an API, your *code* does the typing and reading instead.
Think of it like ordering at a restaurant:
- You (your code) hand over an order: "a message for the AI."
- The kitchen (the AI provider's servers) does the work.
- A waiter brings back the dish: "the AI's reply."
You never see the kitchen. You just need to know how to order and what comes back.
An SDK (Software Development Kit) is a small toolkit the provider gives you so your code can place that order without fuss. Instead of writing raw web requests, you call a tidy function. We will use one below.
What you need first
Three things:
- Python installed. Python is a programming language known for being readable. If you do not have it, the official Python downloads page walks you through it.
- An API key. This is a secret password that tells the provider "this request is from me, bill my account." You create it in your provider's dashboard (OpenAI, Anthropic, or Google).
- The SDK installed. One command does this.
A word on cost: API calls are not free, but they are cheap for learning. A few hundred test messages usually costs under a dollar. New accounts often include a small free credit.
Install the SDK
Open your terminal (the text-based control panel on your computer) and run one of these:
# For Anthropic's Claude
pip install anthropic
# For OpenAI's ChatGPT models
pip install openai
# For Google's Gemini
pip install google-genaipip is Python's installer. It fetches the toolkit from the internet and sets it up. You only do this once.
Your first call, line by line
Here is a complete, runnable program using Claude. Save it as first_call.py.
import anthropic
client = anthropic.Anthropic(api_key="YOUR_KEY_HERE")
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=200,
messages=[
{"role": "user", "content": "Explain what an API is in one sentence."}
],
)
print(response.content[0].text)Now let us read every line.
import anthropic
This loads the toolkit you installed. "Import" means "bring this tool into my program so I can use it."
client = anthropic.Anthropic(api_key="YOUR_KEY_HERE")
This sets up your connection to the provider. client is just a name we picked for it. The api_key is your secret password. Paste your real key between the quotes.
response = client.messages.create(
This is the actual order. You are telling the client: "create a new message exchange." Everything in the parentheses is the details of your order. The reply gets stored in response.
model="claude-sonnet-4-5"
Which AI model should answer. Providers offer several, trading speed against power. Sonnet is a strong, balanced choice in 2026.
max_tokens=200
A tokentokenA token is the basic unit of text that language models process, often a word fragment, whole word, or punctuation mark rather than a single character.View full definition → is a chunk of text, roughly three-quarters of a word. This caps how long the reply can be, so it cannot ramble forever (and run up your bill). 200 tokens is a short paragraph.
messages=[ ... ]
The conversation itself. Each message has a role and content. Here the role is "user" (that is you), and the content is your actual question.
print(response.content[0].text)
The reply comes back wrapped in structure. This line digs out the plain text and prints it to your screen. content[0] means "the first piece of the response," and .text means "give me the words."
Run it from your terminal:
python first_call.pyYou should see something like: *"An API is a set of rules that lets one software program request services or data from another."*
That is it. You just talked to an AI model in code.
The same idea, different provider
The big three providers work almost identically. Here is the OpenAI version so you can see how little changes:
from openai import OpenAI
client = OpenAI(api_key="YOUR_KEY_HERE")
response = client.responses.create(
model="gpt-5",
input="Explain what an API is in one sentence."
)
print(response.output_text)Same shape: set up a client, send a message, print the reply. Once you understand one, you understand all of them. Google's Gemini SDK follows the same pattern with google-genai.
Your First OpenAI API Call in Python
Keep your key secret
Never paste your API key into a public place: not a GitHub repository, not a shared document, not a screenshot. Anyone with your key can spend your money.
The clean habit is to store the key in an environment variable (a setting your computer holds outside your code). Then your code reads it without the key ever appearing in the file:
import os
import anthropic
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])os.environ["ANTHROPIC_API_KEY"] means "go find the value I saved under that name." You set that value once in your terminal or system settings, and your code stays clean. Start with the key pasted in for your very first test if you like, but switch to this method before you share anything.
Knowledge check
1. What fundamentally distinguishes using an API from using a chatbot in your browser?
2. Using the restaurant analogy from the lesson, what does the 'kitchen' represent?
3. Why does the lesson recommend using an SDK rather than writing requests yourself?
4. Select ALL statements that correctly describe what an API key is and does.
Select all the correct answers.
5. Select ALL things you genuinely need in place before making your first API call.
Select all the correct answers.
How to structure a small AI project
Once your first call works, the mindset shifts from "I sent one message" to "I am building something." A few principles keep beginners out of trouble.
Start with one working call, then change one thing
Get the basic script running before you add anything. Then make one change at a time: a longer prompt, a different model, a bigger max_tokens. If something breaks, you know exactly what caused it.
Put your prompt in a variable
As your prompt grows, pull it out so it is easy to edit:
prompt = """
You are a helpful assistant.
Summarize the following review in one sentence,
then rate the sentiment from 1 to 5.
Review: The coffee was great but the wait was 25 minutes.
"""
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=200,
messages=[{"role": "user", "content": prompt}],
)
print(response.content[0].text)This is where API calls become useful. You can now feed in hundreds of reviews by looping over them, something you could never do by hand in the chat window.
Add a "system" instruction for consistent behavior
A system promptsystem promptThe hidden set of instructions that defines how an AI assistant behaves before any user types a question: its role, tone, limits and rules.View full definition → sets the AI's role and rules for the whole conversation. It keeps every reply on-brand:
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=200,
system="You are a concise assistant. Always answer in under 30 words.",
messages=[{"role": "user", "content": "What is an API?"}],
)Notice the system field is separate from messages. The system prompt is your standing instruction; the messages are the live conversation.
Expect things to break, and read the error
Errors are normal. The two most common for beginners:
- Authentication error: your key is wrong, missing, or has extra spaces. Recheck it.
- Rate limit error: you sent too many requests too fast. Wait a moment and try again.
The error message almost always tells you which one it is. Read it slowly before changing code.
Check the official docs, not random forums
Provider docs are kept current and have copy-paste examples for every model. Anthropic's API getting-started guide is a clean reference. Bookmark your provider's equivalent.
Why this matters
The chat window is great for one-off questions. The API is for *repeatable work*: summarizing 500 support tickets, tagging a spreadsheet, drafting personalized emails, building a small tool a colleague can use. The moment you can call the model from code, the AI stops being a website you visit and becomes a building block you control.
Key Takeaways
- An API call is your code ordering from the AI: you send a message, the provider's servers do the work, you get a reply back. The SDK is the toolkit that makes ordering simple.
- Five lines is enough to start: import the SDK, create a client with your key, send a message, print the reply. Run it before you add anything.
- Guard your API key like a password. Move it into an environment variable before you share any code, so it never appears in a file.
- Change one thing at a time. Pull your prompt into a variable, add a system instruction for consistent behavior, and read error messages carefully when things break.
- Reach for the API when you have repeatable work, like processing many items at once, which the chat window cannot do for you.
What to do, from this lesson
These actions are compiled in the role's Playbook.
- Store API keys in environment variables, never in files