Skip to content

Lesson 4 of 6

Call the API with a Python script

Send your refined prompt to the Claude API from a Python script and print the model's text response.

7 minClaude, Gemini and ChatGPT

After this lesson, you will be able to call the Claude API from a Python script, send a prompt, and print the model's text response.

Set up your API key

To use the Claude API, you need an API key. Get one from the Anthropic Console. The Console is the web page where you manage your Claude account and keys. Keep the key secret: treat it like a password.

Store the key in an environment variable called ANTHROPIC_API_KEY. On Linux or macOS, open a terminal and run:

export ANTHROPIC_API_KEY='your-api-key-here'

On Windows, use the Command Prompt:

set ANTHROPIC_API_KEY=your-api-key-here

Replace your-api-key-here with your actual key. The key stays in the environment for that terminal session only. You will need to set it again in a new terminal.

Install the Anthropic Python library

The Anthropic Python library gives you a convenient way to call the API. Install it with pip. The lesson is written for version 0.40.0, so install that version:

pip install "anthropic>=0.40,<0.41"

This command installs the library and its dependencies. If you use a virtual environment, activate it first.

Write a script that calls the API

Create a new file called api_call.py in your working directory. Copy this code into it:

import os
from anthropic import Anthropic

# Replace with a current model from the Anthropic model list
MODEL_NAME = "claude-3-5-sonnet-20241022"

client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))

prompt = "Explain what an API is in one sentence."

message = client.messages.create(
    model=MODEL_NAME,
    max_tokens=100,
    messages=[
        {"role": "user", "content": prompt}
    ]
)

print(message.content[0].text)

Let's go through the script line by line. import os lets us read the environment variable. from anthropic import Anthropic imports the client class. MODEL_NAME is a constant at the top of the file. The comment tells you to replace it with a current model from the Anthropic model list, because model names change over time.

client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY")) creates a client object. It reads the API key from the environment variable you set earlier. If the variable is missing, the client will raise an error when you make a request.

prompt is the text you send to Claude. In this example, it asks for a one-sentence explanation of an API.

client.messages.create(...) sends the request. The arguments are: model tells Claude which model to use. max_tokens limits the length of the response, here to 100 tokens. A token is roughly a piece of a word. messages is a list of message objects. Each message has a role (here "user") and content (the prompt text).

The response is stored in message. The model's text is in message.content, which is a list of content blocks. The first block is usually text, and you get its text with message.content[0].text. Finally, print outputs that text to the terminal.

Before you run the script, look up a current model name in Anthropic's list of models and put it in the MODEL_NAME constant. The name in the example may have been withdrawn since this lesson was written, and a withdrawn name makes the request fail. Then run the script from your terminal:

python api_call.py

You should see a one-sentence explanation of an API printed. The exact wording will vary because the model generates text each time.

Use your refined prompt from Lesson 2

In Lesson 2, you wrote a prompt that gives Claude a role, task, and output format. You can use that prompt in the API call. Replace the prompt variable in api_call.py with your refined prompt. For example, if your prompt is:

You are a patient teacher who explains technical ideas to beginners.

Explain the text below in simple words.

Write three bullet points. Each bullet point must be one sentence.

Text:
Pandas is a Python library for working with data. It provides two main data structures: Series for one-dimensional data and DataFrame for two-dimensional data. You can use Pandas to read data from CSV files, clean it, and analyse it.

Then set prompt to that string in Python. You can use triple quotes for a multi-line string:

prompt = """You are a patient teacher who explains technical ideas to beginners.

Explain the text below in simple words.

Write three bullet points. Each bullet point must be one sentence.

Text:
Pandas is a Python library for working with data. It provides two main data structures: Series for one-dimensional data and DataFrame for two-dimensional data. You can use Pandas to read data from CSV files, clean it, and analyse it."""

Run the script again. The output should follow your format: three bullet points, each one sentence, explaining the Pandas text in simple words.

Handle errors

If the API key is wrong, the script will raise an AuthenticationError. If the key is missing altogether, the library stops with a TypeError saying it could not resolve an authentication method; set the environment variable and run the script again. If you exceed your rate limit, you may get a RateLimitError. To see these errors clearly, wrap the API call in a try-except block. Here is an updated version of api_call.py:

import os
from anthropic import Anthropic
from anthropic import AuthenticationError, RateLimitError

# Replace with a current model from the Anthropic model list
MODEL_NAME = "claude-3-5-sonnet-20241022"

client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))

prompt = "Explain what an API is in one sentence."

try:
    message = client.messages.create(
        model=MODEL_NAME,
        max_tokens=100,
        messages=[
            {"role": "user", "content": prompt}
        ]
    )
    print(message.content[0].text)
except AuthenticationError:
    print("Authentication failed. Check your ANTHROPIC_API_KEY.")
except RateLimitError:
    print("Rate limit exceeded. Wait a moment and try again.")

This version catches the two most common errors and prints a friendly message. You can add more except blocks for other errors if needed.

Key takeaways

  • Store your Anthropic API key in an environment variable called ANTHROPIC_API_KEY.
  • Use the anthropic Python library to create a client and call client.messages.create() with your model, max_tokens, and messages.
  • The model's text response is in message.content[0].text.
  • Wrap the API call in a try-except block to handle authentication and rate limit errors gracefully.

Try it

Modify api_call.py to ask Claude to summarise the Pandas text from Lesson 2 in exactly two sentences. Use the refined prompt structure: role, task, output format, and the text. Set max_tokens to 200. Run the script. Check that the output has exactly two sentences and that it summarises the text. If it does not, adjust the prompt and run again. A good result is a two-sentence summary that captures the main points of the Pandas text.

Official documentation

Ready to use this in a job?

Rolebound applies to matching roles for you.

Start now

Written with AI and checked automatically. Tools change, so a command may behave differently in the version you install. Spotted a mistake? Tell us.

    Cookies on Rolebound

    We use necessary cookies to sign you in and keep the site working — those cannot be turned off. We would also like to set analytics and advertising cookies so we can see which pages help people get interviews and which adverts brought them here. Nothing optional is set unless you say yes, and you can change your mind at any time from “Cookie settings” in the footer. Read our Privacy Policy.

    Call the API with a Python script | Working with Claude: Prompting, Projects and API | Rolebound