Python / FastAPI 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 resultFastAPI 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 |
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
