Registry / web-framework / flask-pydantic

flask-pydantic

JSON →
library0.14.0pypypi✓ verified 86d ago

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.

pip install Flask-Pydantic
INSTALL
IMPORT
SIG · FLASK-PYDANTIC
F
flask-pydantic
web-frameworkpythonv0.14.0
Install
3.9s avg
Import
886ms
Disk
31MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.14.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 0.926s · 32.5MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 3.9s · import 0.847s · 32MB
31MB installed
● package 31MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

validate
from flask_pydantic import validate
BaseModel
from pydantic import BaseModel
Flask
from flask import Flask

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)
Debug
Known issues
breakingWhen migrating to Pydantic V2, direct usage of Pydantic V1 methods (e.g., `.dict()`, `.json()`, `.parse_obj()`) on your Pydantic models will break. Flask-Pydantic (from v0.13.0) supports both Pydantic V1 and V2, but your application code must be updated.
fix
Review the official Pydantic V1 to V2 migration guide. Use Pydantic V2 methods like `.model_dump()`, `.model_dump_json()`, and `.model_validate()`. Alternatively, for existing V1 models, you can explicitly import `from pydantic.v1 import BaseModel` (note: `pydantic.v1` is not supported on Python 3.14+).
affects: All versions where user code interacts directly with Pydantic models installed as Pydantic V2.
gotchaThe order of decorators matters. The `@app.route` decorator must always precede the `@validate()` decorator (i.e., `@validate()` should be closer to the function definition). Incorrect order will lead to validation not being applied.
fix
Ensure `@app.route` is defined *before* `@validate()` for all your Flask routes.
affects: All
gotchaPrior to version 0.13.2, `flask-pydantic` did not fully support asynchronous Flask views. Using `@validate` on `async def` routes might have led to unexpected behavior or errors.
fix
Upgrade `flask-pydantic` to version `0.13.2` or newer to ensure proper support for asynchronous view functions.
affects: <0.13.2
gotchaPath parameter validation with dependency injection was fixed in version 0.14.0. Users on older versions might encounter issues where path parameters are not correctly validated or injected when used alongside other dependencies.
fix
Upgrade `flask-pydantic` to version `0.14.0` or newer to resolve issues with path parameter validation in views using dependency injection.
affects: <0.14.0
gotchaBy default, `flask-pydantic` returns a 400 HTTP status code with a JSON error message upon validation failure. If you need custom error responses (e.g., a different status code, error format, or to raise a specific exception), the default behavior needs to be overridden.
fix
You can configure `FLASK_PYDANTIC_VALIDATION_ERROR_STATUS_CODE` in your Flask app config to change the status code. For full customization, set `FLASK_PYDANTIC_VALIDATION_ERROR_RAISE = True` in your Flask config and then use `app.register_error_handler(flask_pydantic.ValidationError, custom_error_handler)` to catch and handle the validation error globally.
affects: All
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'flask_pydantic'
The 'flask-pydantic' library, or one of its core dependencies like 'Flask' or 'Pydantic', is not installed in the Python environment where the application is running.
fix
Install the library using pip: `pip install Flask-Pydantic`.
ValidationError: 1 validation error for QueryModel\nquery_params -> age\n field required (type=value_error.missing)
The incoming request is missing a required field (e.g., 'age' in query parameters, or a field in the JSON body) that is defined as mandatory in the Pydantic model used by the `@validate` decorator.
fix
Ensure the client sends all required fields in the request, or modify the Pydantic model to make the field optional by using `Optional[Type]` and providing a default value, e.g., `age: Optional[int] = None`.
TypeError: Object of type Formats is not JSON serializable
A Pydantic model, or the `ValidationError` object being returned by `flask-pydantic`, contains a Python object (like an Enum or a custom class instance) that Flask's default JSON serializer cannot convert into a JSON string.
fix
For Enum fields, ensure they inherit from `str, Enum` (e.g., `class Formats(str, Enum): ...`). For custom objects, ensure they have a `json()` or `model_dump()` method or register a custom JSON encoder with Flask to handle these types, or manually call `.model_dump()` on your Pydantic model before returning it.
The application behaves unexpectedly, or the `validate` decorator does not seem to apply.
The `@app.route` decorator is placed after the `@validate` decorator, which prevents `flask-pydantic` from correctly intercepting and processing the request before the route function is called.
fix
Reverse the order of the decorators, ensuring that `@app.route` comes first (outermost) and `@validate` is closer to the function definition (innermost), e.g., `@app.route(...) @validate(...) def my_route(): ...`.
Upgrade
Version history
0.14.0latest on PyPI · released Dec 22, 2025
Audit
Dependencies
FlaskrequiredCore web framework integration.
PydanticrequiredData validation and serialization engine.
Agent activity
9 hits · last 30 days
node
6
Resources
flask-pydantic — pip install flask-pydantic · libregistry