Performance: Request body declaration
This affects the server's request processing speed and the initial response time perceived by the user.
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float @app.post('/items/') async def create_item(item: Item): return item
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() @app.post('/items/') async def create_item(item: dict): # process item as a plain dict return item
| Pattern | CPU Usage | Validation Efficiency | Response Time Impact | Verdict |
|---|---|---|---|---|
| Plain dict as request body | High (manual checks) | None (manual or missing) | Slower by several ms | [X] Bad |
| Pydantic model declaration | Low (optimized parsing) | Automatic and fast | Faster response, better LCP | [OK] Good |
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
async def create_item(item: Item):
return {"item_name": item.name, "item_price": item.price}from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
username: str
age: int
@app.post("/users/")
def create_user(user: User = None):
return {"username": user.username, "age": user.age}description which can be missing or null. How should you declare the Pydantic model to handle this correctly?Pass the test and this pattern moves unknown