Learn / Python for AI / Lesson 7

Build an AI API with FastAPI

16 min Tested on Python 3.15Updated By
In short

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

terminal
uv init ask-api
cd ask-api
uv add "fastapi[standard]" anthropic

The smallest app

hello.py
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 ".")}
terminal
$ 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" to True and rejects bad values with a clear error.
  • Open http://127.0.0.1:8000/docs for interactive documentation where you can try every endpoint.

Validated request bodies

Python
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"])
Output
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

main.py
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 def endpoints let the server handle other requests while one waits for the LLM.
  • AsyncAnthropic is the async client; one shared client reuses connections.
  • Errors from the AI provider become a clean 502 instead of a crash with a stack trace.
  • StreamingResponse sends text as it arrives, which feels much faster to users.
terminal
$ 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

test_hello.py
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 == 422

TestClient 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_tokens limit 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?"}.

Expected output:
['text is required']
['text is too short']
[]
Your code

Quick check

1. What does FastAPI return when a request body fails validation?

2. Why make LLM endpoints async def?

3. Where do you see FastAPI's automatic interactive docs?

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →