One of the biggest time-sinks in web development is writing if/else statements to check if a request body is valid.
In the Node.js post I shared earlier, we talked about structure. Today, let’s talk about Safety. In Python, we use Pydantic models to handle the "boring stuff" automatically.
The Manual Way (Avoid this)
@app.post("/login")
def login(data: dict):
if "email" not in data:
return {"error": "Email is required"}
# ... more messy checks
The FastAPI Way (Do this)
By defining a class, FastAPI will automatically return a 422 Unprocessable Entity error if the user sends bad data. You don't have to write a single if statement.
from pydantic import BaseModel, EmailStr
class LoginSchema(BaseModel):
email: EmailStr
password: str
remember_me: bool = False # Default value
@app.post("/login")
def login(data: LoginSchema):
# data is already validated and typed here!
return {"message": f"Welcome {data.email}"}
Why this wins:
Type Safety: Your IDE knows exactly what
data.emailis.Auto Docs: Your Swagger UI updates instantly to show the required fields.
Cleaner Code: Your business logic stays separate from your validation logic.
If you’re moving from Express to FastAPI, Pydantic is the "killer feature" you’ll wish you had sooner.
Top comments (1)
Are you still using manual dictionaries for your API data, or have you made the switch to Pydantic?