Request and Response Models
Never trust what comes in. You'll check a request body by hand first, then let Pydantic models and field rules do it, read the 422 errors FastAPI sends back, and use response models to choose exactly what goes back out. Then you'll build a pet adoption center's application API.
Updated
Checking What Comes In
- Checking Input by Hand (Apprentice): An API can't trust what a request sends, so before it saves anything it checks each field for being there, having the right type, staying in its range and being an allowed value, and it collects every problem to send back at once.
- Request Models with Pydantic (Apprentice): A Pydantic model replaces checks written by hand with a class that names each field of a request body and its type, with defaults for fields that may be left out, None for optional ones, and models inside models, and FastAPI checks every request against it before the route runs.
- Field Rules: Lengths, Ranges and Choices (Journeyman): Field() puts rules on a model's fields, such as a name of 1 to 80 characters and an age of 18 or over, Literal allows only a fixed set of values, EmailStr checks the shape of an email address, and Query puts the same kind of rules on a query parameter.
What Goes Back Out
- Reading FastAPI's 422 Validation Errors (Apprentice): When a request breaks a model's rules, FastAPI answers 422 with a detail list that has one entry per problem, whose loc says where the problem is, msg what's wrong, type what kind of problem it is and input what was sent, so an app can show each message beside its own box.
- Response Models: Choosing What Goes Out (Journeyman): A response model says exactly which fields a route sends back, set by the route's return type or by response_model=, so separate models for what comes in and what goes out keep fields such as staff notes and password hashes inside the API.
Exercise: Pet Adoption Applications
- Exercise: Pet Adoption Applications (Journeyman): Finish an adoption center's FastAPI applications router with a request model whose field rules refuse bad applications with a 422 and a response model that keeps the staff's private notes out of every answer, and let TestClient's tests check each one.