FastAPI is the fastest way to build production-ready APIs in Python. In this lesson you'll install it, understand how it works, and build your first working endpoint.
A running FastAPI server with three endpoints: a health check, a text analysis endpoint that calls Claude, and a JSON response with proper status codes and error handling.
Install FastAPI and uvicorn (the server that runs it):
$ pip install fastapi uvicorn anthropic python-dotenv
Create main.py:
from fastapi import FastAPI app = FastAPI() @app.get("/") def health_check(): return {"status": "ok", "service": "AI API"}
Run it:
$ uvicorn main:app --reload
Open http://localhost:8000 — you get your first response. Open http://localhost:8000/docs — you get auto-generated documentation you can run right in the browser.
Now build a real endpoint that accepts text and returns an AI-generated summary:
from fastapi import FastAPI, HTTPException from pydantic import BaseModel import anthropic app = FastAPI(title="AI Text API") client = anthropic.Anthropic() class SummarizeRequest(BaseModel): text: str max_words: int = 100 @app.get("/") def health_check(): return {"status": "ok"} @app.post("/summarize") def summarize(req: SummarizeRequest): if not req.text.strip(): raise HTTPException(status_code=400, detail="text cannot be empty") msg = client.messages.create( model="claude-sonnet-4-20250514", max_tokens=512, system=f"Summarize the text in {req.max_words} words or fewer. Return only the summary.", messages=[{"role": "user", "content": req.text}] ) return { "summary": msg.content[0].text, "input_tokens": msg.usage.input_tokens, "output_tokens": msg.usage.output_tokens }
Test it at /docs — click the /summarize endpoint, click "Try it out," paste any text, hit Execute. You'll see the raw request and response.
Want live instruction and hands-on projects? Join the AI bootcamp — 3 days, 5 cities.
Before moving on, confirm understanding of these key concepts: