FastAPI

Lesson 02

Request models and validation

Use Pydantic request models so FastAPI can parse, validate, document, and type the incoming body.

Good Code

api/reviews.py
from fastapi import APIRouter
from pydantic import BaseModel, Field

router = APIRouter()


class CreateReviewRequest(BaseModel):
    title: str = Field(min_length=3, max_length=120)
    author_id: int


# Pydantic validates the body before route logic runs.
@router.post("/reviews")
async def create_review(payload: CreateReviewRequest):
    return {
        "title": payload.title,
        "author_id": payload.author_id,
    }

Bad Code

api/reviews.py
from fastapi import APIRouter, Request

router = APIRouter()


@router.post("/reviews")
async def create_review(request: Request):
    # Manual JSON parsing moves validation into the handler.
    payload = await request.json()
    return {
        "title": payload["title"],
        "author_id": int(payload["author_id"]),
    }

Review Notes

What to review

Good Code

The good version lets FastAPI and Pydantic validate the shape, types, and title length before business logic runs.

Bad Code

The bad version pulls raw JSON out of the request and converts values manually. Missing keys, invalid types, and docs drift become route-handler problems.

Takeaways

  • Request bodies should cross the API boundary as validated models, not raw dictionaries.