Chapter 5: JSON APIs with FastAPI
FastAPI's core strength is JSON APIs with typed contracts. This is the closest match to ASP.NET Core minimal APIs and Web API controllers.
from fastapi import status
from pydantic import BaseModel, Field
class RecipeCreate(BaseModel):
title: str = Field(min_length=1, max_length=120)
instructions: str = Field(min_length=1)
servings: int = Field(ge=1, le=50)
class RecipeRead(RecipeCreate):
id: int
@app.post(
"/api/recipes",
response_model=RecipeRead,
status_code=status.HTTP_201_CREATED,
)
def create_recipe(command: RecipeCreate) -> RecipeRead:
recipe_id = max(RECIPES) + 1
recipe = RecipeRead(id=recipe_id, **command.model_dump())
RECIPES[recipe_id] = recipe
return recipe
Use separate models for:
- Create input.
- Update input.
- Public read output.
- Internal persistence entities.
Do not return ORM models directly from every endpoint just because it works. Shape your API contract deliberately. This is the same discipline as keeping EF Core entities from leaking into every public API response.