Build an AI API with FastAPI
FastAPI turns Python functions into web endpoints: decorate a function with @app.post("/ask"), describe the request body with a Pydantic model, and FastAPI validates input, converts JSON and writes interactive API docs for you. Because it's async, one server can wait on many LLM calls at once, and it can stream answers token by token.
Setup
uv init ask-api
cd ask-api
uv add "fastapi[standard]" anthropicThe smallest app
from fastapi import FastAPI
app = FastAPI()
@app.get("/greet/{name}")
def greet(name: str, excited: bool = False) -> dict:
message = f"Hello, {name}"
return {"message": message + ("!" if excited else ".")}$ uv run fastapi dev hello.py
$ curl "http://127.0.0.1:8000/greet/Ana?excited=true"
{"message":"Hello, Ana!"}{name}in the path becomes a function parameter; other parameters become query parameters (?excited=true).- Type hints do real work here: FastAPI converts
"true"toTrueand rejects bad values with a clear error. - Open
http://127.0.0.1:8000/docsfor interactive documentation where you can try every endpoint.
Validated request bodies
from pydantic import BaseModel, Field, ValidationError
class Question(BaseModel):
text: str = Field(min_length=3, max_length=500)
language: str = "en"
print(Question(text="What is a decorator?"))
try:
Question(text="?")
except ValidationError as err:
print(err.errors()[0]["msg"])text='What is a decorator?' language='en' String should have at least 3 characters
FastAPI runs exactly this validation on every request. Invalid input never reaches your function; the caller gets a 422 response explaining what's wrong. That also protects you from paying for LLM calls with empty or enormous inputs.
An AI endpoint, with streaming
import os
import anthropic
from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
app = FastAPI(title="Ask the Handbook")
client = anthropic.AsyncAnthropic() # reads ANTHROPIC_API_KEY
MODEL = os.getenv("MODEL", "claude-sonnet-5-5")
class Question(BaseModel):
text: str = Field(min_length=3, max_length=500)
class Answer(BaseModel):
answer: str
model: str
@app.get("/health")
def health() -> dict:
return {"status": "ok"}
@app.post("/ask", response_model=Answer)
async def ask(question: Question) -> Answer:
try:
response = await client.messages.create(
model=MODEL,
max_tokens=400,
system="Answer questions about Python briefly and accurately.",
messages=[{"role": "user", "content": question.text}],
)
except anthropic.APIError as err:
raise HTTPException(status_code=502, detail="The AI service is unavailable") from err
return Answer(answer=response.content[0].text, model=MODEL)
@app.post("/ask/stream")
async def ask_stream(question: Question) -> StreamingResponse:
async def tokens():
async with client.messages.stream(
model=MODEL,
max_tokens=400,
messages=[{"role": "user", "content": question.text}],
) as stream:
async for text in stream.text_stream:
yield text
return StreamingResponse(tokens(), media_type="text/plain")async defendpoints let the server handle other requests while one waits for the LLM.AsyncAnthropicis the async client; one shared client reuses connections.- Errors from the AI provider become a clean
502instead of a crash with a stack trace. StreamingResponsesends text as it arrives, which feels much faster to users.
$ uv run fastapi dev main.py
$ curl -X POST http://127.0.0.1:8000/ask \
-H "Content-Type: application/json" \
-d '{"text": "What does enumerate() do?"}'Testing endpoints
from fastapi.testclient import TestClient
from hello import app
client = TestClient(app)
def test_greet():
response = client.get("/greet/Ana", params={"excited": True})
assert response.status_code == 200
assert response.json() == {"message": "Hello, Ana!"}
def test_bad_query_value():
response = client.get("/greet/Ana", params={"excited": "maybe"})
assert response.status_code == 422TestClient calls your app in memory, without starting a server. For endpoints that call an LLM, replace the client with a fake in tests so they're fast, free and repeatable.
Before you deploy
- Keep secrets in environment variables on the hosting platform.
- Add rate limiting and authentication so strangers can't run up your AI bill.
- Set timeouts on LLM calls and a
max_tokenslimit on every request. - Log requests and errors (never the API key), and set a spending alert with your AI provider.
- Run with
fastapi run main.py(production mode) in a container, or on a platform such as Render, Fly.io, Railway or Cloud Run.
Practice
Write the validation FastAPI would do, by hand. validate_question(data: dict) -> list[str] returns a list of error messages: "text is required" if the key is missing, "text is too short" if it has fewer than 3 characters, "text is too long" above 500. Print the result for {}, {"text": "hi"} and {"text": "What is RAG?"}.
['text is required'] ['text is too short'] []