Performance: Body with multiple parameters
This affects the server response time, impacting how fast the client receives and renders data.
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str price: float @app.post("/items/") async def create_item(item: Item): return item
from fastapi import FastAPI, Body app = FastAPI() @app.post("/items/") async def create_item(name: str = Body(...), description: str = Body(...), price: float = Body(...)): return {"name": name, "description": description, "price": price}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Multiple Body Parameters | N/A (server-side) | N/A | N/A | [X] Bad |
| Single Pydantic Model Body | N/A (server-side) | N/A | N/A | [OK] Good |
user and item in a FastAPI endpoint?Body() for multiple body parameters to distinguish them.= Body() for both parameters. async def endpoint(user: User, item: Item): misses Body(), so FastAPI treats only the first as body. Options B and D incorrectly mix Query() and Body().= Body() [OK]= Body() for each body parameter to avoid errors [OK]= Body() for multiple body parametersBody(){"user": {"name": "Alice"}, "item": {"id": 5}}?
from fastapi import FastAPI, Body
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
name: str
class Item(BaseModel):
id: int
@app.post("/create")
async def create(user: User = Body(), item: Item = Body()):
return {"user_name": user.name, "item_id": item.id}user and item respectively, parsing each into the corresponding Pydantic model.user and item:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
name: str
class Item(BaseModel):
id: int
@app.post("/add")
async def add(user: User, item: Item):
return {"user": user, "item": item}= Body() to tell FastAPI to parse them from the body separately.= Body() for multiple body parameters causes validation error. -> Option B= Body() [OK]= Body() for each body parameter to fix errors [OK]= Body() for multiple body parametersuser with fields name and age, and preferences with optional color and food. Which code correctly defines the endpoint and handles missing optional fields gracefully?str | None = None sets optional fields with default None, allowing missing keys without error.= Body()user and preferences from the JSON body separately..dict() on Pydantic models converts them to plain dicts for clean JSON output.field: type | None = None for optional fields [OK]= Body() for multiple parametersPass the test and this pattern moves unknown