Anthropic Python SDK Setup: Your First Claude API Call Step by Step
👋 In plain words: To use Claude from Python you need three things: an API key, the official anthropic package, and a few lines of code. This lesson sets them up one step at a time, sends your first message, and shows how to read every part of Claude’s reply.
Every lesson after this one assumes you can call Claude from Python. In this lesson you will create a key, install the official SDK in a virtual environment, send your first Messages API request, read the response object field by field, hold a two-turn conversation, and fix the three setup errors almost everyone hits.
🔑 Key terms
- API key: a secret string that identifies your account to the Claude API. Treat it like a password.
- SDK: Software Development Kit. Here, the official
anthropicPython package that wraps the HTTP API. - Messages API: the endpoint
POST /v1/messagesthat every Claude request goes through. - Content block: one piece of Claude’s reply, such as a
textblock or atool_useblock. - Token: the unit Claude reads and writes, roughly a short word or part of a word. You pay per token.
🪜 The steps at a glance
- Create an API key in the Claude Console.
- Create a project folder and a virtual environment.
- Install the
anthropicpackage. - Store the key in an environment variable.
- Send your first request.
- Read the response object.
- Hold a multi-turn conversation.
- Fix the common setup errors.
🪜 Step 1: Create an API key
- Sign in to the Claude Console at platform.claude.com.
- Open API Keys and create a key. Give it a clear name, such as
ravi-laptop-dev. - Pick a workspace. Workspaces let an organisation separate keys, limits and spend for each team or environment.
- Copy the key once. It starts with
sk-ant-. You cannot view it again later.
🪜 Step 2: Create a project and a virtual environment
A virtual environment keeps this course’s packages away from your other Python projects. The SDK needs a supported Python 3 version; this course uses Python 3.12 or later.
⌨️ Terminal
mkdir claude-course
cd claude-course
python -m venv .venv
.venv\Scripts\activate
On macOS or Linux, the last line is source .venv/bin/activate. Your prompt now starts with (.venv).
🪜 Step 3: Install the SDK
⌨️ Terminal
pip install anthropic
Check what you installed. This course was built with version 2.13.0 of the SDK, released on PyPI in November 2026.
📄 check_version.py
import sys
import anthropic
print("Python ", sys.version.split()[0])
print("anthropic", anthropic.__version__)⌨️ Terminal
python check_version.py🖥️ Output
Python 3.15.1
anthropic 2.13.0
requirements.txt file (anthropic==2.13.0) for any project you share or run in CI. Unpinned SDK upgrades are a classic source of “it worked yesterday” bugs.🪜 Step 4: Store the key in an environment variable
The SDK reads ANTHROPIC_API_KEY from the environment automatically, so your code never contains the key.
⌨️ Terminal · Windows PowerShell, current session
$env:ANTHROPIC_API_KEY = "sk-ant-...your key..."
⌨️ Terminal · macOS / Linux
export ANTHROPIC_API_KEY="sk-ant-...your key..."
To keep it across sessions, set it in your user environment variables (Windows) or your shell profile (macOS/Linux). For team projects, use a secrets manager or your CI system’s secret store.
ANTHROPIC_API_KEY is not set, it checks ANTHROPIC_AUTH_TOKEN and then a profile saved by Anthropic’s ant auth login command. For this course, an environment variable is the simplest option.🪜 Step 5: Send your first request
Create first_call.py:
📄 first_call.py
import anthropic
client = anthropic.Anthropic() # finds ANTHROPIC_API_KEY by itself
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[
{"role": "user", "content": "Give me 3 short test case titles for a login page."}
],
)
for block in response.content:
if block.type == "text":
print(block.text)⌨️ Terminal
python first_call.py🖥️ Output (sample run)
1. Login succeeds with a valid username and password
2. Login fails with an incorrect password and shows an error
3. Login button stays disabled while both fields are empty
The three required parameters:
model: which Claude model answers.claude-opus-5-5is the current Opus. Lesson 8 compares the models and their prices.max_tokens: the upper limit on the length of the reply. It is a ceiling, not a target. If Claude hits it, the reply is cut off.messages: the conversation so far, a list of{"role": ..., "content": ...}items. The first message must have the roleuser.
response.content[0] is always text. A reply can contain several blocks, such as thinking, text and tool_use. Loop over the blocks and check block.type, as the script does.🪜 Step 6: Read the response object
The reply is a Message object with more than text. Print its most useful fields:
📄 inspect_response.py
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[{"role": "user", "content": "What does HTTP status 429 mean? One sentence."}],
)
print("id :", response.id)
print("model :", response.model)
print("stop_reason :", response.stop_reason)
print("input_tokens:", response.usage.input_tokens)
print("output_tokens:", response.usage.output_tokens)
print("request id :", response._request_id)
print("text :", response.content[0].text)⌨️ Terminal
python inspect_response.py🖥️ Output (sample run)
id : msg_01DdePz5S8a4mHcTyz2ZRzdL
model : claude-opus-5-5
stop_reason : end_turn
input_tokens: 29
output_tokens: 41
request id : req_019fFmTae363PZGAFiYLrjT2
text : HTTP 429 Too Many Requests means you sent more requests than the server allows in a given time, so you should wait and retry.
| Field | What it tells you | Why you care |
|---|---|---|
id |
Unique ID of this message | Log it with your app’s own request ID |
model |
The model that actually answered | Confirms which model you were billed for |
stop_reason |
Why Claude stopped: end_turn, max_tokens, stop_sequence, tool_use, pause_turn or refusal |
Decides what your code does next |
usage.input_tokens / output_tokens |
Tokens read and written | Cost tracking (Lesson 44) |
_request_id |
The request-id header |
Send it to Anthropic support when reporting a problem |
stop_reason is one of the most tested fields. end_turn means Claude finished. max_tokens means the reply was cut off and is not complete. tool_use means Claude is waiting for you to run a tool. refusal means Claude declined. Always check it before showing text to a user.🪜 Step 7: Hold a multi-turn conversation
The API is stateless. To continue a conversation, send the earlier messages again, including Claude’s own replies with the role assistant.
📄 chat.py
import anthropic
client = anthropic.Anthropic()
history = []
def ask(question: str) -> str:
history.append({"role": "user", "content": question})
response = client.messages.create(model="claude-opus-5-5", max_tokens=1024, messages=history)
answer = "".join(b.text for b in response.content if b.type == "text")
history.append({"role": "assistant", "content": answer})
return answer
print("Q1:", ask("I test an e-commerce site. Name one risky area to test first."))
print("Q2:", ask("Give me two test ideas for that area."))
print("messages sent on the last call:", len(history) - 1)⌨️ Terminal
python chat.py🖥️ Output (sample run)
Q1: Checkout and payment: a bug there loses money directly.
Q2: 1) Pay with a card that is declined and check that no order is created. 2) Refresh the page during payment and check you are not charged twice.
messages sent on the last call: 3
historygrows by two items on every turn: your question and Claude’s answer.- The second question says “that area” without naming it. Claude understands because the first answer, “Checkout and payment”, was sent again.
- The last call sent 3 messages: question 1, answer 1 and question 2. Longer chats cost more input tokens on every call. Lesson 19 shows how to manage that.
🪜 Step 8: Fix the common setup errors
These are the errors new users hit most, with the exception class the Python SDK raises.
| Symptom | Exception | Cause and fix |
|---|---|---|
| Error says no API key or authentication method was found | raised before or at the request | The environment variable is not set in this terminal. Set it again, or restart your IDE after setting a user variable. |
401 authentication_error |
anthropic.AuthenticationError |
The key is wrong, revoked or has extra spaces or quotes. Create a new key and paste it carefully. |
404 not_found_error mentioning the model |
anthropic.NotFoundError |
The model ID is misspelled or not available to your organisation. Copy the exact ID, for example claude-opus-5-5. |
400 invalid_request_error |
anthropic.BadRequestError |
The request shape is wrong, for example the first message is not user or max_tokens is missing. Read the error message: it names the field. |
Here is the 404 case in action. The model ID uses a dot instead of a hyphen:
📄 wrong_model.py
import anthropic
client = anthropic.Anthropic()
try:
client.messages.create(
model="claude-opus-5.5", # wrong: should be claude-opus-5-5
max_tokens=100,
messages=[{"role": "user", "content": "Hi"}],
)
except anthropic.NotFoundError as e:
print("Status :", e.status_code)
print("Type :", e.body["error"]["type"])
print("Message:", e.body["error"]["message"])⌨️ Terminal
python wrong_model.py🖥️ Output (sample run)
Status : 404
Type : not_found_error
Message: model: claude-opus-5.5
- Catch the specific exception class, not a bare
except Exception. Lesson 11 builds a full error-handling chain with retries. e.bodyholds the parsed JSON error body, so you can log the error type and message.
🌍 Real-world example: Ravi’s first day
Ravi set ANTHROPIC_API_KEY in PowerShell, then opened VS Code from the Start menu. His script failed with an authentication error. VS Code had started before the variable existed in that session. He set the key as a user environment variable, restarted VS Code, and the call worked.
🧪 Practice Questions
Question 1. A script prints response.content[0].text and occasionally crashes with an AttributeError. What is the most likely cause?
- A. The API key expired between calls
- B. The first content block is sometimes not a text block, for example a thinking or tool_use block
- C. max_tokens is too high
- D. The SDK version is too new
Show answer
Answer: B. A reply can contain several content blocks of different types. Code should loop over the blocks and check block.type before reading .text.
Question 2. A support bot shows answers that end mid-sentence. The logs show stop_reason values of “max_tokens” for those replies. What does this mean?
- A. Claude finished normally
- B. The reply hit the max_tokens ceiling and is incomplete
- C. Claude is waiting for a tool result
- D. The request was rate limited
Show answer
Answer: B. max_tokens means the output limit stopped generation. The text is incomplete and should not be shown as a finished answer.
Question 3. Which two practices keep an Anthropic API key safe during local development? (Choose 2.)
- A. Read it from the ANTHROPIC_API_KEY environment variable
- B. Hard-code it in a constant at the top of the script
- C. Use a separate, clearly named key for development
- D. Commit it to a private Git repository
Show answer
Answer: A and C. Environment variables keep the key out of code, and separate named keys can be revoked without affecting production. Hard-coded or committed keys leak easily, even in private repositories.
Question 4. In a multi-turn chat, the second answer ignores what was said in the first turn. What is the most likely bug?
- A. The model has no memory feature enabled
- B. The code does not send the earlier user and assistant messages again
- C. The temperature is too low
- D. The first message used the role user
Show answer
Answer: B. The Messages API is stateless. Each request must include the conversation history the model should see.
📝 Assignment
- Task 1: Set up the project, install the SDK and run
first_call.pywith your own key.
✅ Done when: you see three test case titles printed. - Task 2: Extend
inspect_response.pyto printresponse.to_json()and findstop_reasonandusagein the JSON.
✅ Done when: you can point to both fields in the printed JSON. - Task 3: Lower
max_tokensto 10 infirst_call.pyand printstop_reason.
✅ Done when: you seemax_tokensand can explain why the text is cut off. - Stretch: Turn
chat.pyinto an interactive loop that reads questions withinput()until you typequit, and prints the total input tokens used.
✅ Done when: the token total grows with every turn.
❓ Frequently Asked Questions
🤔 How do I get an Anthropic API key?
Sign in to the Claude Console, open API Keys and create a key in a workspace. Copy it once and store it in an environment variable or secrets manager.
🤔 Which Python version does the Anthropic SDK need?
Use a currently supported Python 3 release. This course uses Python 3.12 or later with anthropic 2.13.0.
🤔 Is the Claude API free?
No. You pay per input and output token, and the price depends on the model. Lesson 8 lists current prices and Lesson 44 shows how to track cost.
🤔 Why does my reply contain more than one content block?
Claude can return thinking, text and tool_use blocks in one reply. Always loop over the blocks and check each block’s type.
🤔 Do I need the SDK, or can I call the API with requests?
You can call the HTTP API directly, but the official SDK handles authentication, retries, timeouts, streaming and typed responses for you. Use the SDK in Python projects.
🏁 Summary
- Create a key in the Console, store it in
ANTHROPIC_API_KEY, and never put it in code. - Install
anthropicin a virtual environment and pin the version. messages.create()needsmodel,max_tokensandmessages; the reply is a list of content blocks.- Check
stop_reasonbefore trusting the text, and logusageand the request ID. - The API is stateless: send the history for multi-turn chats, and catch specific exception classes for errors.
Next, continue with Claude Tokens and Context Windows: Counting Tokens in Python.
Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.