### Flask-Pydantic: Combined Query and Body Parameter Validation Source: https://context7.com/pallets-eco/flask-pydantic/llms.txt This example shows how to validate both query parameters and the request body simultaneously using Flask-Pydantic. This allows for complex endpoint requirements that consume data from multiple input sources, with all parameters validated and typed. Ensure Flask and Pydantic are installed. ```python from flask import Flask from pydantic import BaseModel from flask_pydantic import validate from typing import Optional app = Flask(__name__) class QueryParams(BaseModel): page: int = 1 limit: int = 10 class UserUpdate(BaseModel): name: Optional[str] = None email: Optional[str] = None age: Optional[int] = None class UpdateResponse(BaseModel): id: int updated_fields: dict page: int limit: int @app.route("/users/", methods=["PATCH"]) @validate() def update_user(user_id: int, body: UserUpdate, query: QueryParams): # All parameters are validated and typed updated = {} if body.name is not None: updated["name"] = body.name if body.email is not None: updated["email"] = body.email if body.age is not None: updated["age"] = body.age return UpdateResponse( id=user_id, updated_fields=updated, page=query.page, limit=query.limit ) # Test with curl: # curl -X PATCH "http://localhost:5000/users/42?page=2&limit=20" \ # -H "Content-Type: application/json" \ # -d '{"name": "Bob", "age": 35}' # Response: {"id": 42, "updated_fields": {"name": "Bob", "age": 35}, "page": 2, "limit": 20} ``` -------------------------------- ### GET /products Source: https://context7.com/pallets-eco/flask-pydantic/llms.txt Demonstrates custom validation error handling by configuring custom error handlers to raise `ValidationError` exceptions. This allows for more control over how validation errors are presented to the client. ```APIDOC ## GET /products ### Description Searches for products based on query parameters. This endpoint showcases custom validation error handling, where validation errors are caught and returned in a standardized format. ### Method GET ### Endpoint /products ### Parameters #### Query Parameters - **category** (str) - Required - The category of the product. - **min_price** (float) - Required - The minimum price of the product. - **max_price** (float) - Required - The maximum price of the product. ### Request Example ```bash curl "http://localhost:5000/products?category=electronics&min_price=invalid&max_price=100" ``` ### Response #### Success Response (200) - **Product** (Product) - A product object matching the search criteria. #### Response Example ```json { "id": 1, "name": "Sample Product", "price": 50.0, "category": "electronics" } ``` #### Error Response (422) - **ValidationError** - Returned when validation fails for query, body, path, or form parameters. The response includes a structured error message detailing the validation failures. #### Error Response Example ```json { "status": "error", "message": "Validation failed", "errors": [ { "location": "query", "error": { "loc": ["min_price"], "msg": "value is not a valid float", "type": "type_error.float" } } ] } ``` ``` -------------------------------- ### Query and Response Models with Flask-Pydantic Validation Source: https://github.com/pallets-eco/flask-pydantic/blob/master/README.md Example of using the `validate` decorator for handling query parameters and defining response models with Flask-Pydantic. It shows how to define Pydantic models for request queries and responses, and how validation errors are returned. ```python from typing import Optional from flask import Flask, request from pydantic import BaseModel from flask_pydantic import validate app = Flask("flask_pydantic_app") class QueryModel(BaseModel): age: int class ResponseModel(BaseModel): id: int age: int name: str nickname: Optional[str] = None @app.route("/", methods=["GET"]) @validate() def get(query: QueryModel): age = query.age return ResponseModel( age=age, id=0, name="abc", nickname="123" ) ``` -------------------------------- ### Handle Both Query Parameters and Request Body with Validation Source: https://github.com/pallets-eco/flask-pydantic/blob/master/README.md This example shows a POST route that validates both query parameters and a request body against their respective Pydantic models. Data from both sources is used to form the response. ```python # Example 3: both query paramters and request body @app.route("/both", methods=["POST"]) @validate() def get_and_post(body: RequestBodyModel, query: QueryModel): name = body.name # From request body nickname = body.nickname # From request body age = query.age # from query parameters return ResponseModel( age=age, name=name, nickname=nickname, id=0 ) ``` -------------------------------- ### Handle Form Data with Validation Source: https://github.com/pallets-eco/flask-pydantic/blob/master/README.md This example illustrates a POST route that expects form data and validates it against a Pydantic model. The extracted form data is then used to generate a response. ```python class RequestFormDataModel(BaseModel): name: str nickname: Optional[str] = None # Example2: request body only @app.route("/", methods=["POST"]) @validate() def post(form: RequestFormDataModel): name = form.name nickname = form.nickname return ResponseModel( name=name, nickname=nickname,id=0, age=1000 ) ``` -------------------------------- ### GET / Source: https://github.com/pallets-eco/flask-pydantic/blob/master/README.md This endpoint demonstrates validating query parameters using the `validate` decorator. It expects an 'age' integer and returns a JSON response based on a `ResponseModel`. ```APIDOC ## GET / ### Description This endpoint validates a required integer query parameter named 'age' and returns a JSON response. ### Method GET ### Endpoint / ### Parameters #### Query Parameters - **age** (int) - Required - The age to be validated. ### Request Example ```bash curl --location --request GET 'http://127.0.0.1:5000/?age=20' ``` ### Response #### Success Response (200) - **id** (int) - The ID of the user. - **age** (int) - The age of the user. - **name** (str) - The name of the user. - **nickname** (Optional[str]) - The nickname of the user. #### Response Example ```json { "id": 0, "age": 20, "name": "abc", "nickname": "123" } ``` #### Error Response (400) - **validation_error** (object) - Contains details about validation failures. - **query_params** (array) - List of validation errors for query parameters. - **loc** (array) - Location of the error (e.g., `["age"]`). - **msg** (str) - Error message (e.g., "field required", "value is not a valid integer"). - **type** (str) - Error type (e.g., "value_error.missing", "type_error.integer"). #### Error Response Example (Missing Parameter) ```json { "validation_error": { "query_params": [ { "loc": ["age"], "msg": "field required", "type": "value_error.missing" } ] } } ``` #### Error Response Example (Invalid Type) ```json { "validation_error": { "query_params": [ { "loc": ["age"], "msg": "value is not a valid integer", "type": "type_error.integer" } ] } } ``` ``` -------------------------------- ### Handle URL Path Parameter with Validation Source: https://github.com/pallets-eco/flask-pydantic/blob/master/README.md This example shows how to define a route that accepts an integer path parameter and validates it using flask-pydantic. It retrieves data from a list based on the validated ID and handles potential 'IndexError'. ```python @app.route("/character//", methods=["GET"]) @validate() def get_character(character_id: int): characters = [ ResponseModel(id=1, age=95, name="Geralt", nickname="White Wolf"), ResponseModel(id=2, age=45, name="Triss Merigold", nickname="sorceress"), ResponseModel(id=3, age=42, name="Julian Alfred Pankratz", nickname="Jaskier"), ResponseModel(id=4, age=101, name="Yennefer", nickname="Yenn"), ] try: return characters[character_id] except IndexError: return {"error": "Not found"}, 400 ``` -------------------------------- ### GET /users/ Source: https://github.com/pallets-eco/flask-pydantic/blob/master/README.md This endpoint demonstrates how to use the `validate` decorator with annotated path parameters. It validates the `user_id` path parameter as a string. ```APIDOC ## GET /users/ ### Description This endpoint demonstrates validating a URL path parameter named `user_id` using type hints. ### Method GET ### Endpoint /users/ ### Parameters #### Path Parameters - **user_id** (str) - Required - The ID of the user. ### Request Example ```bash curl --location --request GET 'http://127.0.0.1:5000/users/123' ``` ### Response #### Success Response (200) *Details of the response depend on the implementation of the `get_user` function.* #### Error Response (400) *If validation fails for `user_id` (though type hints usually catch this at runtime if not provided correctly), a 400 response would be returned.* ``` -------------------------------- ### Form Data Validation with Flask-Pydantic Source: https://context7.com/pallets-eco/flask-pydantic/llms.txt This example shows how to validate multipart form data submissions using Pydantic models with flask-pydantic. It supports standard form fields and file uploads, ensuring that submitted data adheres to the defined Pydantic schema. This prevents invalid data from being processed by the application logic. ```python from flask import Flask from pydantic import BaseModel from flask_pydantic import validate from typing import Optional app = Flask(__name__) class ProfileForm(BaseModel): username: str bio: Optional[str] = None age: int class ProfileResponse(BaseModel): id: int username: str bio: Optional[str] age: int status: str @app.route("/profile", methods=["POST"]) @validate() def create_profile(form: ProfileForm): # Access validated form data return ProfileResponse( id=999, username=form.username, bio=form.bio, age=form.age, status="created" ) # Test with curl: # curl -X POST "http://localhost:5000/profile" \ # -F "username=johndoe" \ # -F "bio=Software developer" \ # -F "age=28" # Response: {"id": 999, "username": "johndoe", "bio": "Software developer", "age": 28, "status": "created"} # # curl -X POST "http://localhost:5000/profile" \ # -F "username=johndoe" \ # -F "age=invalid" # Response 400: {"validation_error": {"form_params": [...]}} ``` -------------------------------- ### GET /character// Source: https://github.com/pallets-eco/flask-pydantic/blob/master/README.md Retrieves a character by their ID. The character_id is a path parameter and must be an integer. ```APIDOC ## GET /character// ### Description Retrieves a specific character using their unique ID from the URL path. ### Method GET ### Endpoint `/character// ### Parameters #### Path Parameters - **character_id** (int) - Required - The unique identifier for the character. ### Response #### Success Response (200) - **id** (int) - The character's ID. - **age** (int) - The character's age. - **name** (str) - The character's name. - **nickname** (str) - The character's nickname. #### Response Example ```json { "id": 1, "age": 95, "name": "Geralt", "nickname": "White Wolf" } ``` ``` -------------------------------- ### Modify Response Status Code (Validate Decorator) Source: https://github.com/pallets-eco/flask-pydantic/blob/master/README.md This example demonstrates setting a custom success status code directly within the `@validate` decorator using the `on_success_status` argument. ```python @app.route("/", methods=["POST"]) @validate(body=BodyModel, query=QueryModel, on_success_status=201) def post(): ... ``` -------------------------------- ### GET /users Source: https://context7.com/pallets-eco/flask-pydantic/llms.txt Serializes lists of Pydantic models as JSON arrays using the `response_many` parameter for endpoints returning collections. This endpoint retrieves a list of users, with options to limit the number of users and filter by active status. ```APIDOC ## GET /users ### Description Retrieves a list of users, supporting pagination and filtering by active status. It demonstrates serializing a collection of Pydantic models as a JSON array. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters - **limit** (int) - Optional - The maximum number of users to return. - **active_only** (bool) - Optional - If true, only active users are returned. ### Request Example ```bash curl "http://localhost:5000/users?limit=2" curl "http://localhost:5000/users?active_only=true" ``` ### Response #### Success Response (200) - **User** (List[User]) - A list of user objects. #### Response Example ```json [ {"id": 1, "name": "Alice", "email": "alice@example.com", "active": true}, {"id": 2, "name": "Bob", "email": "bob@example.com", "active": false} ] ``` ``` -------------------------------- ### Validate Request Bodies with Array of Models using request_body_many Source: https://context7.com/pallets-eco/flask-pydantic/llms.txt This example shows how to validate incoming request bodies that are expected to be arrays of Pydantic models. The `request_body_many=True` parameter enables this functionality, allowing for batch operations. The validated array of models is then accessible via `request.body_params`. ```python from flask import Flask from pydantic import BaseModel from flask_pydantic import validate from typing import List app = Flask(__name__) class Task(BaseModel): title: str priority: int completed: bool = False class BatchResponse(BaseModel): created_count: int task_ids: List[int] @app.route("/tasks/batch", methods=["POST"]) @validate(request_body_many=True) def create_tasks_batch(body: Task): # body is List[Task] when request_body_many=True # Access via request.body_params from flask import request tasks = request.body_params task_ids = [100 + i for i in range(len(tasks))] return BatchResponse( created_count=len(tasks), task_ids=task_ids ) # Test with curl: # curl -X POST "http://localhost:5000/tasks/batch" \ # -H "Content-Type: application/json" \ # -d "[ # {"title": "Task 1", "priority": 1}, # {"title": "Task 2", "priority": 2, "completed": true}, # {"title": "Task 3", "priority": 3} # ]" # Response: {"created_count": 3, "task_ids": [100, 101, 102]} # # curl -X POST "http://localhost:5000/tasks/batch" \ # -H "Content-Type: application/json" \ # -d '{"title": "Single task"}' # Response 400: {"validation_error": {"body_params": [{"loc": ["root"], "msg": "is not an array of objects", "type": "type_error.array"}]}} ``` -------------------------------- ### Custom Validation Error Handling with ValidationError Source: https://context7.com/pallets-eco/flask-pydantic/llms.txt This example shows how to implement custom error handling for validation failures in Flask-Pydantic. By setting `FLASK_PYDANTIC_VALIDATION_ERROR_RAISE` to `True` and defining an error handler for `ValidationError`, you can control the format and content of error responses, returning a consistent JSON structure with detailed error information. ```python from flask import Flask, jsonify from pydantic import BaseModel from flask_pydantic import validate, ValidationError app = Flask(__name__) app.config["FLASK_PYDANTIC_VALIDATION_ERROR_RAISE"] = True class ProductQuery(BaseModel): category: str min_price: float max_price: float class Product(BaseModel): id: int name: str price: float category: str @app.errorhandler(ValidationError) def handle_validation_error(e: ValidationError): errors = [] if e.query_params: errors.extend([{"location": "query", "error": err} for err in e.query_params]) if e.body_params: errors.extend([{"location": "body", "error": err} for err in e.body_params]) if e.path_params: errors.extend([{"location": "path", "error": err} for err in e.path_params]) if e.form_params: errors.extend([{"location": "form", "error": err} for err in e.form_params]) return jsonify({ "status": "error", "message": "Validation failed", "errors": errors }), 422 @app.route("/products", methods=["GET"]) @validate() def search_products(query: ProductQuery): # Mock product search return Product( id=1, name="Sample Product", price=50.0, category=query.category ) # Test with curl: # curl "http://localhost:5000/products?category=electronics&min_price=invalid&max_price=100" # Response 422: {"status": "error", "message": "Validation failed", "errors": [...]} ``` -------------------------------- ### Flask-Pydantic: Validate JSON Request Body with Pydantic Models Source: https://context7.com/pallets-eco/flask-pydantic/llms.txt This snippet demonstrates how Flask-Pydantic validates incoming JSON request bodies against a specified Pydantic model. It includes automatic content-type checking and structured error handling for malformed JSON requests. Ensure Flask and Pydantic are installed. ```python from flask import Flask from pydantic import BaseModel, Field from flask_pydantic import validate from typing import Optional app = Flask(__name__) class UserCreate(BaseModel): name: str = Field(..., min_length=1, max_length=100) email: str age: int = Field(..., ge=0, le=150) nickname: Optional[str] = None class UserResponse(BaseModel): id: int name: str email: str age: int nickname: Optional[str] = None @app.route("/users", methods=["POST"]) @validate() def create_user(body: UserCreate): # Access validated body params user_data = { "id": 123, "name": body.name, "email": body.email, "age": body.age, "nickname": body.nickname } return UserResponse(**user_data) # Test with curl: # curl -X POST "http://localhost:5000/users" \ # -H "Content-Type: application/json" \ # -d '{"name": "Alice", "email": "alice@example.com", "age": 30, "nickname": "Ali"}' # Response: {"id": 123, "name": "Alice", "email": "alice@example.com", "age": 30, "nickname": "Ali"} # # curl -X POST "http://localhost:5000/users" \ # -H "Content-Type: application/json" \ # -d '{"name": "", "email": "alice@example.com", "age": 200}' # Response 400: {"validation_error": {"body_params": [...]}} ``` -------------------------------- ### GET /users - User Query Validation Source: https://context7.com/pallets-eco/flask-pydantic/llms.txt This endpoint demonstrates how to validate query parameters using a Pydantic model. The `@validate()` decorator automatically parses and validates the 'age' and 'name' query parameters against the `QueryModel`. If validation succeeds, the function receives a typed `QueryModel` object. The endpoint also shows automatic response serialization by returning a `ResponseModel`. ```APIDOC ## GET /users ### Description Validates incoming query parameters against a Pydantic model and automatically serializes the response. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters - **age** (int) - Required - The age of the user. - **name** (str) - Optional - The name of the user. ### Request Example (No request body for GET request) ### Response #### Success Response (200) - **id** (int) - The unique identifier of the user. - **age** (int) - The age of the user. - **name** (str) - The name of the user. #### Response Example ```json { "id": 1, "age": 25, "name": "John" } ``` #### Error Response (400) ```json { "validation_error": { "query_params": [ { "loc": ["age"], "msg": "value is not a valid integer", "type": "type_error.integer" } ] } } ``` ``` -------------------------------- ### Flask-Pydantic: Validate Incoming Request Parameters and Serialize Responses Source: https://context7.com/pallets-eco/flask-pydantic/llms.txt The @validate decorator automatically validates incoming request parameters (query, body, form, path) against Pydantic models and serializes response models to JSON. It can infer models from function type hints or accept them as arguments. Ensure Pydantic and Flask are installed. ```python from flask import Flask, request from pydantic import BaseModel from flask_pydantic import validate from typing import Optional app = Flask(__name__) class QueryModel(BaseModel): age: int name: Optional[str] = None class ResponseModel(BaseModel): id: int age: int name: str @app.route("/users", methods=["GET"]) @validate() def get_users(query: QueryModel): # Access validated query params age = query.age name = query.name or "unknown" # Return Pydantic model - automatically serialized to JSON return ResponseModel(id=1, age=age, name=name) # Test with curl: # curl "http://localhost:5000/users?age=25&name=John" # Response: {"id": 1, "age": 25, "name": "John"} # # curl "http://localhost:5000/users?age=invalid" # Response 400: {"validation_error": {"query_params": [{"loc": ["age"], "msg": "value is not a valid integer", "type": "type_error.integer"}]}} ``` -------------------------------- ### POST / Source: https://github.com/pallets-eco/flask-pydantic/blob/master/README.md Creates a new resource using data provided in the request body. Supports optional nickname. ```APIDOC ## POST / ### Description Creates a new resource with the provided name and an optional nickname in the request body. ### Method POST ### Endpoint `/ ### Parameters #### Request Body - **name** (str) - Required - The name of the resource. - **nickname** (str) - Optional - The nickname for the resource. ### Request Example ```json { "name": "New Resource", "nickname": "NR" } ``` ### Response #### Success Response (200) - **id** (int) - The ID of the created resource. - **age** (int) - The age associated with the resource. - **name** (str) - The name of the resource. - **nickname** (str) - The nickname of the resource. #### Response Example ```json { "id": 0, "age": 1000, "name": "New Resource", "nickname": "NR" } ``` ``` -------------------------------- ### POST /resources & POST /resources-alt & POST /resources-headers Source: https://context7.com/pallets-eco/flask-pydantic/llms.txt Demonstrates creating a resource with custom success status codes configured either in the decorator or the return statement. ```APIDOC ## POST /resources ### Description Creates a resource. The success status code (201 Created) is configured directly in the `@validate` decorator. ### Method POST ### Endpoint /resources ### Parameters #### Request Body - **name** (str) - Required - The name of the resource. - **description** (str) - Required - A description for the resource. ### Request Example ```bash curl -X POST "http://localhost:5000/resources" \ -H "Content-Type: application/json" \ -d '{"name": "API", "description": "REST API endpoint"}' ``` ### Response #### Success Response (201) - **id** (int) - The unique identifier for the created resource. - **name** (str) - The name of the resource. - **description** (str) - The description of the resource. #### Response Example ```json { "id": 456, "name": "API", "description": "REST API endpoint" } ``` ## POST /resources-alt ### Description Creates a resource. The success status code (201 Created) is set in the return statement of the route handler. ### Method POST ### Endpoint /resources-alt ### Parameters #### Request Body - **name** (str) - Required - The name of the resource. - **description** (str) - Required - A description for the resource. ### Request Example ```bash curl -X POST "http://localhost:5000/resources-alt" \ -H "Content-Type: application/json" \ -d '{"name": "API", "description": "REST API endpoint"}' ``` ### Response #### Success Response (201) - **id** (int) - The unique identifier for the created resource. - **name** (str) - The name of the resource. - **description** (str) - The description of the resource. #### Response Example ```json { "id": 789, "name": "API", "description": "REST API endpoint" } ``` ## POST /resources-headers ### Description Creates a resource and returns it with custom headers, including a `Location` header pointing to the newly created resource, and a status code of 201. ### Method POST ### Endpoint /resources-headers ### Parameters #### Request Body - **name** (str) - Required - The name of the resource. - **description** (str) - Required - A description for the resource. ### Request Example ```bash curl -X POST "http://localhost:5000/resources-headers" \ -H "Content-Type: application/json" \ -d '{"name": "API", "description": "REST API endpoint"}' ``` ### Response #### Success Response (201) - **id** (int) - The unique identifier for the created resource. - **name** (str) - The name of the resource. - **description** (str) - The description of the resource. - **X-Custom-Header** (str) - A custom header with the value "value". - **Location** (str) - The URL of the newly created resource (e.g., "/resources/101"). #### Response Example ```json { "id": 101, "name": "API", "description": "REST API endpoint" } ``` ``` -------------------------------- ### POST /profile Source: https://context7.com/pallets-eco/flask-pydantic/llms.txt Creates a user profile from form data, validating fields like username, bio, and age using a Pydantic model. ```APIDOC ## POST /profile ### Description Creates a user profile using multipart form data. The request data is validated against the `ProfileForm` Pydantic model. ### Method POST ### Endpoint /profile ### Parameters #### Request Body - **username** (str) - Required - The user's username. - **bio** (str) - Optional - A short biography for the user. - **age** (int) - Required - The user's age. ### Request Example ```bash curl -X POST "http://localhost:5000/profile" \ -F "username=johndoe" \ -F "bio=Software developer" \ -F "age=28" ``` ### Response #### Success Response (200) - **id** (int) - The unique identifier for the created profile. - **username** (str) - The username provided in the request. - **bio** (str) - The bio provided in the request. - **age** (int) - The age provided in the request. - **status** (str) - The status of the profile creation (e.g., "created"). #### Response Example ```json { "id": 999, "username": "johndoe", "bio": "Software developer", "age": 28, "status": "created" } ``` #### Error Response (400) - **validation_error** (object) - Contains details about the validation failure in form parameters. #### Error Response Example ```json { "validation_error": { "form_params": [ { "loc": [ "age" ], "msg": "value is not a valid integer", "type": "type_error.integer" } ] } } ``` ``` -------------------------------- ### Global Configuration Source: https://context7.com/pallets-eco/flask-pydantic/llms.txt Shows how to configure validation behavior globally using Flask application configuration. ```APIDOC ## POST /articles ### Description Creates a new article with provided title, content, and publication status. Global configuration sets validation error status code to 422 and errors are raised as exceptions. ### Method POST ### Endpoint /articles ### Request Body - **title** (str) - Required - The title of the article. - **content** (str) - Required - The main content of the article. - **published** (bool) - Optional - Whether the article is published (defaults to False). ### Request Example ```bash curl -X POST "http://localhost:5000/articles" \ -H "Content-Type: application/json" \ -d '{"title": "Test", "content": "This is the article content."}' ``` ### Response #### Success Response (200) - **id** (int) - The unique identifier of the created article. - **title** (str) - The title of the article. - **content** (str) - The content of the article. - **published** (bool) - The publication status of the article. #### Response Example ```json { "id": 1, "title": "Test", "content": "This is the article content.", "published": false } ``` #### Error Response (422) - **validation_error** (object) - Contains details about the validation failure. - **body_params** (array) - Array of validation errors for the request body. #### Error Response Example (Missing Content) ```json { "validation_error": { "body_params": [ { "loc": ["content"], "msg": "field required", "type": "value_error.missing" } ] } } ``` ``` -------------------------------- ### Response Serialization Options Source: https://context7.com/pallets-eco/flask-pydantic/llms.txt Demonstrates how to control response serialization using options like exclude_none and response_by_alias. ```APIDOC ## GET /users/compact ### Description Retrieves user profile data, excluding fields with `None` values from the JSON response. ### Method GET ### Endpoint /users/compact ### Query Parameters - **user_id** (int) - Required - The ID of the user to retrieve. ### Request Example ```bash curl "http://localhost:5000/users/compact?user_id=1" ``` ### Response #### Success Response (200) - **user_id** (int) - The user's unique identifier. - **full_name** (str) - The user's full name. - **email_address** (str) - The user's email address. #### Response Example ```json { "user_id": 1, "full_name": "John Doe", "email_address": "john@example.com" } ``` ## GET /users/aliased ### Description Retrieves user profile data, using field aliases (uppercase in this case) for the JSON response keys. ### Method GET ### Endpoint /users/aliased ### Query Parameters - **user_id** (int) - Required - The ID of the user to retrieve. ### Request Example ```bash curl "http://localhost:5000/users/aliased?user_id=2" ``` ### Response #### Success Response (200) - **USER_ID** (int) - The user's unique identifier (aliased). - **FULL_NAME** (str) - The user's full name (aliased). - **EMAIL_ADDRESS** (str) - The user's email address (aliased). - **PHONE_NUMBER** (str) - The user's phone number (aliased). #### Response Example ```json { "USER_ID": 2, "FULL_NAME": "Jane Smith", "EMAIL_ADDRESS": "jane@example.com", "PHONE_NUMBER": "+1234567890" } ``` ``` -------------------------------- ### Using Decorated Function kwargs Source: https://github.com/pallets-eco/flask-pydantic/blob/master/README.md Explains how to directly access parsed request data (body, query parameters) as keyword arguments in the decorated route function through type hinting. ```APIDOC ## Using Decorated Function kwargs ### Description This feature allows you to receive validated request data (like request body and query parameters) directly as arguments to your route function, enhancing type safety and IDE support. ### Usage Instead of explicitly passing `body` and `query` to the `validate` decorator, you can define them directly in your function signature using type hints. The decorator will then inject the parsed data into these arguments. ```python # Assuming BodyModel and QueryModel are defined Pydantic models @app.route("/", methods=["POST"]) @validate() def post(body: BodyModel, query: QueryModel): # Access data directly from the arguments name = body.name nickname = body.nickname age = query.age return ResponseModel( id=0, # Example ID age=age, name=name, nickname=nickname, ) ``` ### Benefits - **Type Safety**: Ensures that the arguments `body` and `query` are of the expected Pydantic model types. - **IDE Support**: Enables features like autocompletion and type checking within your IDE. - **Readability**: Makes the code cleaner by reducing the need to access parsed data via `request.body_params` or `request.query_params`. ``` -------------------------------- ### POST / (Form Data) Source: https://github.com/pallets-eco/flask-pydantic/blob/master/README.md Handles requests with form data, extracting 'name' and an optional 'nickname'. ```APIDOC ## POST / (Form Data) ### Description Processes requests containing form data. It expects 'name' and an optional 'nickname' fields. ### Method POST ### Endpoint `/ ### Parameters #### Request Body (Form Data) - **name** (str) - Required - The name field from the form data. - **nickname** (str) - Optional - The nickname field from the form data. ### Request Example ``` name=Jane Doe&nickname=JD ``` ### Response #### Success Response (200) - **id** (int) - The ID of the resource. - **age** (int) - The age associated with the resource. - **name** (str) - The name from the form data. - **nickname** (str) - The nickname from the form data. #### Response Example ```json { "id": 0, "age": 1000, "name": "Jane Doe", "nickname": "JD" } ``` ``` -------------------------------- ### POST /both Source: https://github.com/pallets-eco/flask-pydantic/blob/master/README.md Handles requests containing both query parameters and a request body. It extracts name and nickname from the body and age from query parameters. ```APIDOC ## POST /both ### Description Processes a request that includes both query parameters and a JSON request body. It uses data from both to construct a response. ### Method POST ### Endpoint `/both ### Parameters #### Query Parameters - **age** (int) - Required - The age to be included in the response. #### Request Body - **name** (str) - Required - The name to be included in the response. - **nickname** (str) - Optional - The nickname to be included in the response. ### Request Example #### Query Parameters `?age=30` #### Request Body ```json { "name": "John Doe", "nickname": "JD" } ``` ### Response #### Success Response (200) - **id** (int) - The ID of the resource. - **age** (int) - The age extracted from query parameters. - **name** (str) - The name extracted from the request body. - **nickname** (str) - The nickname extracted from the request body. #### Response Example ```json { "id": 0, "age": 30, "name": "John Doe", "nickname": "JD" } ``` ``` -------------------------------- ### Pydantic Model Aliases with Response Source: https://github.com/pallets-eco/flask-pydantic/blob/master/README.md This demonstrates how to use Pydantic's alias feature for response models by defining an `alias_generator` in `model_config` and setting `response_by_alias=True` in the `@validate` decorator. ```python def modify_key(text: str) -> str: # do whatever you want with model keys return text class MyModel(BaseModel): ... model_config = ConfigDict( alias_generator=modify_key, populate_by_name=True ) @app.route(...) @validate(response_by_alias=True) def my_route(): ... return MyModel(...) ``` -------------------------------- ### Using Decorated Function Arguments for Parsed Data Source: https://github.com/pallets-eco/flask-pydantic/blob/master/README.md This approach allows direct access to validated request data (body, query) as function arguments by leveraging type hinting, simplifying data access and improving IDE support. ```python # necessary imports, app and models definition ... @app.route("/", methods=["POST"]) @validate() def post(body: BodyModel, query: QueryModel): return ResponseModel( id=id_, age=query.age, name=body.name, nickname=body.nickname, ) ``` -------------------------------- ### Validate URL Path Parameters with Flask-Pydantic Source: https://github.com/pallets-eco/flask-pydantic/blob/master/README.md Demonstrates how to use the `validate` decorator to parse and validate URL path parameters in Flask. The path parameter `user_id` is type-hinted as a string and validated by Flask-Pydantic. ```python from flask import Flask from flask_pydantic import validate app = Flask(__name__) @app.route("/users/", methods=["GET"]) @validate() def get_user(user_id: str): # user_id is automatically validated and parsed pass ``` -------------------------------- ### Model Aliases for Responses Source: https://github.com/pallets-eco/flask-pydantic/blob/master/README.md Details how to use Pydantic's alias feature to customize response field names and how to enable this in Flask-Pydantic responses. ```APIDOC ## Model Aliases for Responses ### Description This section explains how to use Pydantic's alias functionality to control the naming of fields in your API responses, allowing for flexibility in how data is presented. ### Defining Aliases Aliases are defined within your Pydantic `BaseModel` using `model_config` and an `alias_generator` function. The `populate_by_name=True` setting ensures that you can still access fields by their original names in your Python code. ```python from pydantic import BaseModel, ConfigDict def modify_key(text: str) -> str: # Example: Convert snake_case to camelCase parts = text.split('_') return parts[0] + ''.join(word.capitalize() for word in parts[1:]) class MyModel(BaseModel): original_name: str original_nickname: str model_config = ConfigDict( alias_generator=modify_key, populate_by_name=True ) ``` ### Enabling Aliases in Responses To make Flask-Pydantic use these aliases in the API response, set `response_by_alias=True` in the `@validate` decorator. ```python @app.route('/my-endpoint') @validate(response_by_alias=True) def my_route(): data = MyModel(original_name="Example", original_nickname="Ex") return data ``` ### Example Response with Aliases If `MyModel` is used with `response_by_alias=True` and the `modify_key` function above, the response would look like: ```json { "originalName": "Example", "originalNickname": "Ex" } ``` Note that within the Python function, you can still access the fields using their original names (`data.original_name`). ``` -------------------------------- ### Global Configuration for Flask-Pydantic Validation Source: https://context7.com/pallets-eco/flask-pydantic/llms.txt Configure validation behavior globally using Flask application config for consistent error handling. This approach centralizes settings like the error status code and exception raising behavior, simplifying management across multiple endpoints. Dependencies include Flask, Pydantic, and Flask-Pydantic. ```python from flask import Flask from pydantic import BaseModel from flask_pydantic import validate app = Flask(__name__) # Configure global validation error status code app.config["FLASK_PYDANTIC_VALIDATION_ERROR_STATUS_CODE"] = 422 # Configure to raise exceptions instead of JSON responses app.config["FLASK_PYDANTIC_VALIDATION_ERROR_RAISE"] = False class ArticleCreate(BaseModel): title: str content: str published: bool = False class Article(BaseModel): id: int title: str content: str published: bool @app.route("/articles", methods=["POST"]) @validate() def create_article(body: ArticleCreate): return Article( id=1, title=body.title, content=body.content, published=body.published ) # Test with curl: # curl -X POST "http://localhost:5000/articles" \ # -H "Content-Type: application/json" \ # -d '{"title": "Test"}' # Response 422: {"validation_error": {"body_params": [{"loc": ["content"], "msg": "field required", ...}]}} ``` -------------------------------- ### URL Path Parameter Validation with Flask and Pydantic Source: https://context7.com/pallets-eco/flask-pydantic/llms.txt This snippet demonstrates how flask-pydantic automatically validates and converts URL path parameters based on function type hints. It supports complex Pydantic types, ensuring that incoming path parameters conform to the expected schema before they reach the route handler. This reduces boilerplate validation code. ```python from flask import Flask from pydantic import BaseModel from flask_pydantic import validate from typing import Optional app = Flask(__name__) class Character(BaseModel): id: int name: str age: int nickname: Optional[str] = None @app.route("/characters/", methods=["GET"]) @validate() def get_character(character_id: int): # character_id is automatically validated as int characters = [ Character(id=0, name="Geralt", age=95, nickname="White Wolf"), Character(id=1, name="Yennefer", age=101, nickname="Yenn"), Character(id=2, name="Ciri", age=22, nickname="Lion Cub") ] try: return characters[character_id] except IndexError: return {"error": "Character not found"}, 404 # Test with curl: # curl "http://localhost:5000/characters/1" # Response: {"id": 1, "name": "Yennefer", "age": 101, "nickname": "Yenn"} # # curl "http://localhost:5000/characters/invalid" # Response 400: {"validation_error": {"path_params": [{"loc": ["character_id"], ...}]}} ``` -------------------------------- ### Handle Request Body with Validation Source: https://github.com/pallets-eco/flask-pydantic/blob/master/README.md This snippet demonstrates how to define a POST route that accepts a request body validated against a Pydantic model. The parsed data from the body is then used to construct a response. ```python class RequestBodyModel(BaseModel): name: str nickname: Optional[str] = None # Example2: request body only @app.route("/", methods=["POST"]) @validate() def post(body: RequestBodyModel): name = body.name nickname = body.nickname return ResponseModel( name=name, nickname=nickname,id=0, age=1000 ) ```