Flask-Pydantic Documentation

repository·master·Indexed 19 days ago

https://github.com/pallets-eco/flask-pydantic

A Flask extension for integration with the Pydantic library, providing request validation for query parameters, request bodies, form data, and URL path parameters. It features a @validate decorator to handle automatic validation and error responses, support for Pydantic aliases in responses, and configurable error status codes via Flask app config.

Tokens
1.2K
Snippets
4
Records
7
Agent score
16%

What's inside Flask-Pydantic

  1. How the `@validate` decorator works

    master

    The @validate decorator integrates Pydantic models with Flask routes to validate incoming request data. It supports three main types of parameters:

    1. Query Parameters: Accessed via request.query_params or as a function argument.
    2. Body Parameters (JSON): Accessed via request.body_params or as a function argument.
    3. Form Data: Accessed via request.form_params or as a function argument.

    Important: The @validate decorator must be placed after the @app.route decorator (closer to the function definition).

    If validation fails, the extension returns a 400 response (by default) containing a JSON object describing the validation errors.

    @app.route("/path", methods=["POST"])
    @validate()
    def my_route(body: MyModel):
        # body is already validated and parsed
        return {"status": "ok"}
  2. Access validated parameters via `request` or function arguments

    master

    You can access validated data in two ways:

    1. Via Flask's request object

    Validated parameters are attached to the request object under specific attributes:

    • request.query_params for query parameters
    • request.body_params for JSON body parameters
    • request.form_params for form-data

    By using type hints in your decorated function, the parsed data is passed directly as keyword arguments. This provides better IDE support and type safety.

    @app.route("/", methods=["POST"])
    @validate()
    def post(body: RequestBodyModel, query: QueryModel):
        # Accessing directly from arguments
        name = body.name
        age = query.age
        return ResponseModel(name=name, age=age, ...)
  3. Configure Flask-Pydantic via App Config

    master

    You can control the extension's behavior using Flask application configuration keys:

    • FLASK_PYDANTIC_VALIDATION_ERROR_STATUS_CODE: Sets the HTTP status code returned when validation fails (defaults to 400).
    • FLASK_PYDANTIC_VALIDATION_ERROR_RAISE: If set to True, the extension will raise a flask_pydantic.ValidationError instead of returning a response. This allows you to use app.register_error_handler to customize the error response manually. The exception object will contain body_params, form_params, path_params, or query_params as lists of error dictionaries.
  4. Use Pydantic aliases in responses

    master

    To use Pydantic's alias feature in your API responses, configure your Pydantic model with an alias_generator and set response_by_alias=True in the @validate decorator.

    from pydantic import BaseModel, ConfigDict
    
    def modify_key(text: str) -> str:
        return text
    
    class MyModel(BaseModel):
        name: str
        model_config = ConfigDict(
            alias_generator=modify_key,
            populate_by_name=True
        )
    
    @app.route("/", methods=["GET"])
    @validate(response_by_alias=True)
    def my_route():
        return MyModel(name="test")
  5. Validate URL path parameters

    master

    Flask-Pydantic can also validate variables defined in the URL path. To do this, use type hints in the decorated function signature. The extension will parse and validate the path variable using the specified type.

    @app.route("/users/<user_id>", methods=["GET"])
    @validate()
    def get_user(user_id: int):
        # user_id is automatically validated as an integer
        pass
  6. Configure `@validate` decorator arguments

    master

    The @validate decorator accepts several arguments to customize validation and response behavior:

    ArgumentDescription
    on_success_statusSets the HTTP status code for a successful validation (default is 200).
    response_manyIf True, enables serialization of multiple models (the route function should return an iterable of models).
    request_body_manyIf False, enables serialization of multiple models inside the root level of the request body. If the body doesn't contain an array of objects, a 400 is returned.
    get_json_paramsDictionary of parameters to be passed to the flask.Request.get_json function.
    response_by_aliasIf True, uses Pydantic aliases when serializing the response.