How do I call the Claude API using Python?

Asked 1 hour ago Updated 1 hour ago 12 views

1 Answer


0

Anthropic provides an official Python library, or SDK, that makes calling the Claude API straightforward. Here is how to go from nothing to a working request.

Step 1: Get an API key. Create an account on the Claude developer platform, available through docs.claude.com and the Claude Console. Add billing details, then create an API key. Copy it once and store it safely.

Step 2: Store the key as an environment variable. Instead of putting the key in your code, set an environment variable named ANTHROPIC_API_KEY. On Windows, you can set it in System Properties or with the setx command; on Mac and Linux, add an export line to your shell profile. Many developers use a .env file with a library such as python-dotenv, making sure the .env file is excluded from Git.

Step 3: Install the SDK. Run: pip install anthropic

Step 4: Send your first message. The basic pattern is:

import anthropic
client = anthropic.Anthropic()
message = client.messages.create(model="MODEL_NAME", matokens=1024, messages=[{"role": "user", "content": "Explain what an API is in two sentences."}])
print(message.content[0].text)

Replace MODEL_NAME with a current model identifier from Anthropic's models documentation, for example a current Sonnet or Haiku model. The client automatically reads your API key from the environment variable.

Understanding the parts:

model chooses which Claude model to use.
matokens sets the maximum length of the reply.
messages is the conversation, a list of turns with roles "user" and "assistant." For a multi-turn conversation, include previous turns in order.
system is an optional parameter for instructions that shape Claude's behaviour, such as its role and tone.

The response includes the generated content, plus usage information showing how many input and output tokens were used, which determines cost.

Next steps to explore:

1. Streaming, to show text as it is generated.
2. Tool use, letting Claude call your functions.
3. Vision, sending images for analysis.
4. Prompt caching, to reduce cost for repeated long prompts.
5. The Message Batches API, for processing many requests cheaply.
6. Structured outputs for reliable JSON.

Good practices from the start:

Handle errors such as rate limits and timeouts; the SDK includes automatic retries for some errors.
Set spending limits in the console.
Log token usage to track costs.
Never expose your API key in front-end code.

Anthropic's documentation includes quickstarts, a cookbook of examples and detailed references.

Write Your Answer