Hackforge Academy

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"
  }
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community