Python / FastAPI Basics Interview Questions
How do you receive and validate a JSON request body in FastAPI?
Declare a Pydantic BaseModel as a function parameter. FastAPI automatically reads the JSON body, validates it against the model, and provides it as a typed Python object. If validation fails it returns a 422 with details.
from fastapi import FastAPI from pydantic import BaseModel from typing import Annotated from pydantic import Field app = FastAPI() class Item(BaseModel): name: str description: str | None = None # optional field price: float tax: float | None = None @app.post("/items") def create_item(item: Item): # body parsed + validated automatically total = item.price + (item.tax or 0) return {**item.model_dump(), "total_price": total} # Mixing path param + query param + body in the same endpoint @app.put("/items/{item_id}") def update_item( item_id: int, # path q: str | None = None, # query item: Item | None = None, # body (optional) ): result = {"item_id": item_id} if q: result["q"] = q if item: result.update(item.model_dump()) return result
FastAPI resolves the source of each parameter automatically:
| Parameter type | Source |
|---|---|
| Matches a path segment {name} | Path parameter |
| Simple type (int, str, float…) + not in path | Query parameter |
| Pydantic BaseModel subclass | JSON request body |
| Annotated with Body() | Explicitly JSON body |
More Related questions...