Validate a request body

Take your time, follow the code and check your understanding.

The codeHTTP and validation
class Product(BaseModel):
    title: str
    price: float = Field(gt=0)

@app.post("/products", status_code=201)
def create(product: Product):
    return product

# {"title":"Lamp", "price": -1}
Your answer4 min · no timer
What needs fixing?

Show solution and explanation

The Pydantic model validates the JSON request body. Field(gt=0) requires a positive price.

Body validation fails before creation.