How to use Claude API with FastAPI
Quick answer
Use the
anthropic Python SDK to call Claude models inside a FastAPI app by creating an Anthropic client with your API key and defining an endpoint that sends user messages to client.messages.create. Return the AI's response as JSON from your FastAPI route.PREREQUISITES
Python 3.8+Anthropic API keypip install anthropic fastapi uvicorn
Setup
Install the required packages and set your Anthropic API key as an environment variable.
- Install packages:
pip install anthropic fastapi uvicorn - Set environment variable:
export ANTHROPIC_API_KEY='your_api_key_here'(Linux/macOS) orset ANTHROPIC_API_KEY=your_api_key_here(Windows)
pip install anthropic fastapi uvicorn Step by step
This example shows a minimal FastAPI app that exposes a POST endpoint /chat. It accepts a JSON payload with a user message, sends it to Claude using the anthropic SDK, and returns the AI's reply.
import os
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import anthropic
app = FastAPI()
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
class ChatRequest(BaseModel):
message: str
@app.post("/chat")
async def chat(request: ChatRequest):
try:
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=500,
system="You are a helpful assistant.",
messages=[{"role": "user", "content": request.message}]
)
return {"response": response.choices[0].message.content}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# To run: uvicorn filename:app --reload Common variations
You can customize the integration by:
- Using different Claude models like
claude-3-5-haiku-20241022for shorter responses. - Making the endpoint async if you use an async Anthropic client variant.
- Adding streaming support by handling partial responses (requires more advanced setup).
- Adding authentication or request validation in FastAPI.
Troubleshooting
If you get authentication errors, verify your ANTHROPIC_API_KEY environment variable is set correctly. For timeout or network errors, check your internet connection and API endpoint availability. If the model name is invalid, confirm you are using a current Claude model name from Anthropic's docs.
Key Takeaways
- Use the official
anthropicSDK with environment-based API keys for secure integration. - Define a FastAPI POST endpoint that sends user input to Claude and returns the AI response.
- Customize model choice and parameters to fit your app’s needs.
- Handle exceptions gracefully to provide meaningful error messages.
- Keep your API key secure and never hardcode it in source code.