PythiloLesson 3 of 14 · progress kept in this browser

Validate a JSON request body

A JSON body needs an explicit contract just as a path or query does. Annotating an endpoint parameter with a Pydantic model tells FastAPI to parse the request body and validate its fields before invoking the endpoint.

Return only values derived from the validated model. Reading a second copy of the raw dictionary would bypass those rules. Use the response status to distinguish successful creation from a normal read, and test malformed data as well as a successful request. These tests run entirely through an in-memory ASGI transport.

from fastapi import FastAPI
from pydantic import BaseModel, Field
class Item(BaseModel):
    units: int = Field(gt=0)
app = FastAPI()
@app.post("/items", status_code=201)
async def create(item: Item):
    return item.model_dump()
print(app.openapi()["paths"].keys())
Your task

Define Item(name:str minimum length1, quantity:int>0). build_app() provides POST /items, returning the validated dictionary with HTTP 201; invalid or missing fields return 422.

The first run loads fastapi, httpx, pydantic into this browser.