Find helpful tutorials or share inspiring use cases on AI technology for higher education.

Shared content may not reflect the policies of Tilburg University on the use of AI. 

Beginner’s Tutorial for the Claude API Python

In this tutorial, you will learn all the tricks for working with the Claude API in Python. In this article, we will give you a step-by-step tutorial on how to get a Claude API key, call the API, and get the responses. That means that after this article, you’ll be able to start your own AI projects with Claude!

What is the Claude API?

The Claude API lets you integrate Claude’s AI models into your apps. You can send prompts to Anthropic (the company behind Claude) and get the outputs delivered to you wherever you need them: you can save them to your database, display them to your users, or use the output to run more complex logic.

The API provides several capabilities, including:

  • Text Generation: Create short or long texts, answer questions, or summarize extensive content. Claude supports a context window of up to 200,000 tokens, equivalent to approximately 160,000 words.
  • Vision: Analyze images and answer questions about their content. Note that Claude cannot generate images itself.

The Claude API operates on a pay-as-you-go pricing model. You are charged for each request sent to Anthropic’s servers, with costs based on the number of tokens in the input (prompt) and output (response). Input tokens are less expensive than output tokens, and prices vary depending on the model used.

Setting up your environment

Step 1: Create an Anthropic Account

First, navigate to the Anthropic console and create a developer account.

Step 2: Add Credits to Your Account

  1. Click Settings at the top of the screen.
  2. Then, select Billing from the left-hand menu.

Anthropic will request additional information about you and your intended API usage. Once you’ve completed the form, you’ll be prompted to enter your billing details. You can choose between a one-time payment or enable auto-reload, which automatically funds your account when the balance falls below a specified threshold.

Note: Taxes are calculated separately and will be added at the end of the payment process.

Step 3: How to Get a Claude API Key

  1. While in the Settings tab, click API Keys in the left-hand menu.
  2. Click Create Key.
  3. Name your key and click Create Key to complete the process.
  4. Copy the key to a safe location you won’t be able to view it again after closing the pop-up.

Keep your API key secure at all times. If someone else gains access to your key, they could use it to consume your credits. Avoid sharing your key with anyone who doesn’t need it. If you’re publishing an app on the public web, make sure to review API security best practices to protect your key.

After closing the pop-up, you’ll see a list of all the API keys you’ve generated so far. To manage your keys, click the three-dot icon on the right side to disable or delete them as needed.

Secure Your API Key Using Environmental Variables:
MacOS
  • Open your terminal or command prompt.
  • Run the command nano ~/.zshrc to open your bash profile in the nano editor. (Note: for older MacOS versions, you might need to run nano ~/.bash_profile instead).
  • You can edit the file by pressing control + O and then enter.
  • Add the line export CLAUDE_API_KEY='your-api-key' at the end of the file, replacing your-api-key with the actual key you obtained earlier.
  • Save the file by pressing Ctrl + Xy and then hit Enter.
  • Apply the changes by running source ~/.zshrc or restart your terminal.
Windows
  • Right-click on ‘This PC’ or ‘My Computer’ on your desktop or in File Explorer, and select ‘Properties’.
  • Click on ‘Advanced system settings’ on the left side of the System window.
  • In the System Properties window, click the ‘Environment Variables’ button near the bottom of the Advanced tab.
  • In the Environment Variables window, under the ‘System variables’ section, click ‘New…’ to create a new system variable.
  • In the New System Variable dialog, enter CLAUDE_API_KEY as the variable name and your actual API key as the variable value.
  • Click ‘OK’ to close the New System Variable dialog. Then, click ‘OK’ again to close the Environment Variables window, and click ‘OK’ once more to close the System Properties window.

Verifying Your API Key:

  • In the terminal, run echo $CLAUDE_API_KEY when using a Mac, and echo %CLAUDE_API_KEY% when using Windows.
  • This command should return your API key, confirming it has been correctly set up as an environmental variable.

Integrating Claude API Python

You now have credits and an API key, you’re ready to start using Claude!

Step 4: Install the anthropic library

You can install the Anthropic library using pip:

Bash
pip install anthropic

Step 5: Import Required Packages

Start by opening your IDE and creating a new Python file. At the top of the file, import the necessary packages for interacting with the Claude API:

Python
import os 
from anthropic import Anthropic

Step 6: Initialize the Anthropic Client:
Use the following code snippet to initialize the Anthropic client with your API key:

Python
# If you stored the API Key as an environmental variable
client = Anthropic(
    api_key=os.environ.get("CLAUDE_API_KEY"))
)

# Otherwise
client = Anthropic(
    api_key='Your-API-Key'
)

Step 7: Make your First Request

With our client set up, we’re ready to make our first request.

We’ll use the messages.create() method from the client object to send a message to Claude and get a response. Go ahead and run the following code to send your first message and see Claude’s reply!

Python
response = client.messages.create(
    model="claude-3-haiku-20240307",
    max_tokens=1000,
    messages=[
        {"role": "user", "content": "Hi there! Tell a good joke in the form of a question. Do not yet give the answer."}
    ]
)

print(response.content[0].text)

Here is the full Python code to be able to copy it all at once:

Python
import os 
from anthropic import Anthropic

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

response = client.messages.create(
    model="claude-3-haiku-20240307",
    max_tokens=1000,
    messages=[
        {"role": "user", "content": "Hi there! Tell a good joke in the form of a question. Do not yet give the answer."}
    ]
)

print(response.content[0].text)