N
NexusDigitalLabs
← Back to Academy

Phase 1 — Foundations · Lesson 13 · 20 XP

FastAPI basics

FastAPI routes are plain Python functions decorated with the HTTP method and path: @app.get("/items"), @app.post("/items"). Request bodies are Pydantic models straight from Lesson 8 — FastAPI validates the incoming JSON against the model automatically and returns a 422 with a clear error if it doesn't match, before your function body even runs.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.post("/items")
def create_item(item: Item):
    return {"id": 1, **item.model_dump()}

Every FastAPI app gets a free interactive docs page at /docs, generated from your route signatures and Pydantic models — genuinely useful for another engineer (or you, in a week) calling the API without reading the source. This is the framework you'll reach for constantly once you're wrapping an LLM call or an agent behind an endpoint.

Exercise

Build a small FastAPI app with two routes — GET a list of items, POST a new item — using Pydantic models for validation. Run it and explore the auto-generated /docs page, including trying a request with a deliberately invalid body.

Check yourself

1. What does FastAPI do automatically when a request body doesn't match your Pydantic model?

2. Why is an auto-generated interactive docs page useful for an API another engineer will call?

← Previous lesson

SQL and Postgres

Answer the check-yourself questions to unlock this