Getting Started with the Anthropic API in Python: Making Your First Request
Set up your environment, initialize the Anthropic client, and build a simple conversational chatbot script in Python.
Ayodele··6 min read
AI is quickly becoming the backbone of many modern applications, and Anthropic's Claude is one of the most powerful and versatile models out there. If you've been looking for a straightforward, practical way to start building with the Anthropic API using Python, you're in the right place.
In this first part of our series, we're going to set up our environment, initialize the Anthropic client, and build a simple conversational chatbot script.
Prerequisites & Setup
Before we start sending messages to Claude, we need to install the necessary packages and securely configure our API key.
First, let's install the official Anthropic Python SDK along with python-dotenv to manage our environment variables.
pip install anthropic python-dotenv
Next, ensure you have a .env file set up in your project root with your API key:
ANTHROPIC_API_KEY=your_api_key_here
We'll load these environment variables right at the top of our script:
With our environment ready, it's time to instantiate the Anthropic client. This object is your primary entry point for interacting with Claude's API.
# create an api clientfrom anthropic import Anthropicclient = Anthropic()# For this tutorial, we will be using the fast and cost-effective Haiku modelmodel = "claude-haiku-4-5-20251001"
Note on Models: Anthropic regularly updates and retires older models to ensure safety and capacity. The model used here (claude-haiku-4-5-20251001) is active at the time of writing, but always verify current active models in the Claude Model Deprecations documentation.
The Core Concept: The Create Function
The heart of making API requests lies in the client.messages.create() function. This is what securely sends your prompt over to Claude and safely retrieves the generated text.
Let's break down the main components we'll be using:
model: The AI model we're targeting (as set above).
max_tokens: This caps the maximum length of the response (e.g., 100 tokens), preventing unbounded outputs.
messages: A list containing the chronological history of the conversation, ending with the user's latest input.
To make managing the messages list easier, let's define a couple of helper functions:
# helper functions to structure message payloadsdef add_user_message(messages, text): user_message = { "role": "user", "content": text } messages.append(user_message)def add_assistant_message(messages, text): assistant_message = { "role": "assistant", "content": text } messages.append(assistant_message)
Now, let's wrap our API call into a clean chat function:
# make a requestdef chat(messages): message = client.messages.create( model=model, max_tokens=100, messages=messages ) return message.content[0].text
Note: The raw message object returned by the API contains a wealth of metadata (like token usage, stop reasons, and ID trackers). Since we just want the direct text response for now, we use message.content[0].text.
Putting It All Together: A Simple Chat Loop
We can now construct a continuous conversation. By continually appending our prompts and Claude's replies to the messages list, the model retains the context of our chat.
Let's look at a simple execution loop that lets you chat with Claude right from your terminal:
messages = []while True: user_input = input("> ") print("> ", user_input) # 1. Add the user's input to the message history add_user_message(messages, user_input) # 2. Get the model's response answer = chat(messages) # 3. Add the assistant's response back to the history to retain context add_assistant_message(messages, answer) print("---") print(answer) print("---")
And just like that, you have a fully functional contextual chatbot running locally!
Leveling Up Your Claude App: Mastering System Prompts
Now that we have a basic conversational loop running, let's introduce System Prompts. This is one of the most powerful tools for steering the personality, rules, and boundaries of your AI model. System prompts guide how Claude behaves before it even looks at a user's message.
To use system prompts, we simply need to pass an additional parameter to the client.messages.create() call. Let's update our function to accept an optional system parameter:
# Updated chat function with system prompt supportdef chat(messages, system=None): # Set up our base parameters params = { "model": "claude-haiku-4-5-20251001", "max_tokens": 100, "messages": messages, } # If a system prompt is provided, add it to our parameters if system: params["system"] = system # Pass our parameters into the API caller message = client.messages.create(**params) return message.content[0].text
Now we have a flexible chat function capable of handling system instructions. Let's see this in action by creating distinct personas!
Example 1: The Patient Math Tutor
Often, when you ask an AI model a question, it quickly just gives you the answer. But what if you're building an educational app that's supposed to guide students? We can use a system prompt to change this default behavior.
messages = []# Define our system promptmath_tutor_system_prompt = """ You are a patient math tutor. Do not directly answer a student's questions. Guide them through a solution step by step."""# Let's add a student's queryadd_user_message(messages, "how do i solve 5x + 3 = 2?")# Pass the system prompt into our chat functionanswer = chat(messages, system=math_tutor_system_prompt)print(answer)
Claude's Output:
"Great question! Let's work through this together step by step.
Step 1: Look at the equation: 5x + 3 = 2
Your goal is to get x by itself on one side. What do you think should be your first move?
Hint: Think about the constant term (the number without x) on the left side."
By simply passing in three logical sentences as a system prompt, Claude transformed from an answering machine into a helpful, Socratic tutor.
Example 2: The Concise Python Engineer
Next, imagine you are building a coding assistant and you just want raw, concise code without the conversational fluff. Let's change the system prompt to reflect a skilled, no-nonsense software engineer.
messages = []add_user_message( messages, "write a python function that checks a string for duplicates")# Pass our new persona directly in the function callengineer_system_prompt = "you are a python engineer who writes very concise code"answer = chat(messages, system=engineer_system_prompt)print(answer)
Notice how it gets straight to the point? It completely omitted the pleasantries, skipping straight to delivering a highly idiomatic Python solution.
Why System Prompts Matter
System prompts give you architectural control over user interactions. By isolating instructions into the system parameter, you ensure the AI prioritizes its fundamental rules, preventing users from easily overriding its primary purpose.
Stay tuned, and happy building!
If something here sparked a thought, a question, or an argument, I want to hear it. The best conversations start with “I disagree, but here's why.”