Flask-Pydantic

0.14.0 · active · verified Wed Apr 15

Flask-Pydantic is a Flask extension that integrates the Pydantic library for robust data validation and serialization. It streamlines the process of validating incoming request data (query parameters, JSON bodies, form data, and path parameters) and serializing outgoing responses using Pydantic models, enhancing type safety and developer experience in Flask applications. The current version is 0.14.0, and it is actively maintained as part of the Pallets Community Ecosystem, with regular releases addressing new features and bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `flask-pydantic` to validate query parameters for a GET request and a JSON request body for a POST request. It defines Pydantic `BaseModel` classes for both input validation and response serialization, applying the `@validate` decorator to Flask routes to automatically handle data parsing and validation. Errors result in a 400 Bad Request response by default.

from typing import Optional
from flask import Flask, request, jsonify
from pydantic import BaseModel, Field
from flask_pydantic import validate

app = Flask(__name__)

class QueryModel(BaseModel):
    age: int = Field(..., ge=0, description="User's age")
    city: Optional[str] = None

class RequestBodyModel(BaseModel):
    name: str = Field(..., min_length=2, max_length=50)
    email: str = Field(..., pattern="^.+@.+\..+$") # Simple email regex

class ResponseModel(BaseModel):
    message: str
    user_info: dict

@app.route("/users", methods=["GET"])
@validate(query=QueryModel)
def get_user_info(query: QueryModel):
    """Get user info based on query parameters."""
    return jsonify(ResponseModel(
        message="User info retrieved successfully",
        user_info={"age": query.age, "city": query.city}
    ).model_dump())

@app.route("/users", methods=["POST"])
@validate(body=RequestBodyModel)
def create_user(body: RequestBodyModel):
    """Create a new user with validated request body."""
    # In a real app, you would save `body` to a database
    return jsonify(ResponseModel(
        message=f"User {body.name} created with email {body.email}",
        user_info=body.model_dump()
    ).model_dump()), 201

if __name__ == "__main__":
    # Example usage: start server and make requests like:
    # GET /users?age=30&city=NewYork
    # POST /users with JSON body: {"name": "Alice", "email": "alice@example.com"}
    app.run(debug=True, port=5000)

view raw JSON →