Category: python
input validation with pydantic marshmallow
Published on 30 Sep 2026
Explanation
Input validation checks whether incoming API data follows the expected structure, types, and business rules.
Code:
Request JSON | v Validation | +-- Valid β Continue | +-- Invalid β 400 Response
Explanation
Pydantic models can define the expected structure and data types for incoming data.
Code:
from pydantic import BaseModel
class UserCreate(BaseModel):
name: str
email: str
age: int
Explanation
Validate incoming JSON using a Pydantic model before passing data to the service layer.
Code:
@app.post('/users')
def create_user():
data = UserCreate(**request.get_json())
return data.model_dump(), 201
Explanation
Marshmallow provides schemas for serialization and deserialization of Python objects and request data.
Code:
from marshmallow import Schema, fields
class UserSchema(Schema):
name = fields.Str(required=True)
email = fields.Email(required=True)
age = fields.Int(required=True)
Explanation
Validation errors should be converted into clear API responses rather than allowing invalid data to reach the database.
Code:
{
"error": "VALIDATION_ERROR",
"fields": {
"email": "Invalid email"
}
}