Generate REST API and OpenAPI documentation for your Flask project with automatic request/response validation using Pydantic models.
—
Helper functions for OpenAPI specification generation, parameter parsing, schema extraction, and operation management. These utilities support the automatic documentation generation and request validation features of Flask-OpenAPI3.
Functions for creating and managing OpenAPI operation specifications.
def get_operation(
func: Callable,
*,
summary: Optional[str] = None,
description: Optional[str] = None,
openapi_extensions: Optional[dict[str, Any]] = None,
) -> Operation:
"""
Return an Operation object with the specified summary and description.
Args:
func: The function or method for which the operation is being defined.
summary: A short summary of what the operation does.
description: A verbose explanation of the operation behavior.
openapi_extensions: Additional extensions to the OpenAPI Schema.
Returns:
An Operation object representing the operation.
"""Usage Example:
from flask_openapi3.utils import get_operation
def my_endpoint():
"""Get all users from the database"""
return []
# Create operation from function
operation = get_operation(
my_endpoint,
summary="List Users",
description="Retrieve a paginated list of all users",
openapi_extensions={"x-custom": "value"}
)Functions for generating unique operation IDs for API endpoints.
def get_operation_id_for_path(
*,
bp_name: str = "",
name: str = "",
path: str = "",
method: str = ""
) -> str:
"""
Generate operation ID for API endpoints.
Args:
bp_name: Blueprint name (if applicable)
name: Function name
path: URL path
method: HTTP method
Returns:
Generated operation ID string
"""Usage Example:
from flask_openapi3.utils import get_operation_id_for_path
# Generate operation ID
op_id = get_operation_id_for_path(
bp_name="users",
name="create_user",
path="/users",
method="POST"
)
# Result: "users_create_user_post"Functions for extracting JSON schemas from Pydantic models.
def get_model_schema(
model: Type[BaseModel],
mode: JsonSchemaMode = "validation"
) -> dict:
"""
Extract JSON schema from Pydantic model.
Args:
model: Pydantic model class
mode: Schema generation mode ("validation" or "serialization")
Returns:
JSON schema dictionary
"""Usage Example:
from flask_openapi3.utils import get_model_schema
from pydantic import BaseModel
class User(BaseModel):
name: str
email: str
age: int = None
# Extract schema
schema = get_model_schema(User)
# Returns JSON schema with properties, required fields, etc.Functions for parsing different types of parameters from Pydantic models.
def parse_parameters(
path: Optional[Type[BaseModel]] = None,
query: Optional[Type[BaseModel]] = None,
header: Optional[Type[BaseModel]] = None,
cookie: Optional[Type[BaseModel]] = None,
form: Optional[Type[BaseModel]] = None,
body: Optional[Type[BaseModel]] = None,
raw: Optional[Type[RawModel]] = None
) -> ParametersTuple:
"""
Parse all parameter types for endpoint.
Args:
path: Path parameter model
query: Query parameter model
header: Header parameter model
cookie: Cookie parameter model
form: Form data model
body: Request body model
raw: Raw request model
Returns:
Tuple of processed parameter models
"""Specialized functions for parsing specific parameter types.
def parse_header(header: Type[BaseModel]) -> tuple[list[Parameter], dict]:
"""
Parse header parameters from model.
Args:
header: Pydantic model defining header parameters
Returns:
Tuple of (parameter list, schema dict)
"""
def parse_cookie(cookie: Type[BaseModel]) -> tuple[list[Parameter], dict]:
"""
Parse cookie parameters from model.
Args:
cookie: Pydantic model defining cookie parameters
Returns:
Tuple of (parameter list, schema dict)
"""
def parse_path(path: Type[BaseModel]) -> tuple[list[Parameter], dict]:
"""
Parse path parameters from model.
Args:
path: Pydantic model defining path parameters
Returns:
Tuple of (parameter list, schema dict)
"""
def parse_query(query: Type[BaseModel]) -> tuple[list[Parameter], dict]:
"""
Parse query parameters from model.
Args:
query: Pydantic model defining query parameters
Returns:
Tuple of (parameter list, schema dict)
"""
def parse_form(
form: Type[BaseModel],
*,
multipart: bool = False
) -> tuple[Optional[RequestBody], dict]:
"""
Parse form data parameters from model.
Args:
form: Pydantic model defining form fields
multipart: Whether to use multipart/form-data encoding
Returns:
Tuple of (request body, schema dict)
"""
def parse_body(
body: Type[BaseModel],
*,
content_type: str = "application/json"
) -> tuple[Optional[RequestBody], dict]:
"""
Parse request body from model.
Args:
body: Pydantic model defining request body
content_type: Media type for request body
Returns:
Tuple of (request body, schema dict)
"""Usage Example:
from flask_openapi3.utils import parse_query, parse_body
from pydantic import BaseModel
class UserQuery(BaseModel):
name: str
age: int = None
class UserBody(BaseModel):
email: str
password: str
# Parse query parameters
query_params, query_schema = parse_query(UserQuery)
# Parse request body
request_body, body_schema = parse_body(UserBody)Functions for processing response definitions.
def get_responses(
responses: Optional[ResponseDict] = None,
validation_error_status: Union[str, int] = 422,
validation_error_model: Type[BaseModel] = ValidationErrorModel
) -> Responses:
"""
Process response definitions for OpenAPI.
Args:
responses: Response definitions by status code
validation_error_status: Status code for validation errors
validation_error_model: Model for validation error responses
Returns:
Processed Responses object
"""
def convert_responses_key_to_string(responses: ResponseDict) -> ResponseStrKeyDict:
"""
Convert response status codes to strings.
Args:
responses: Response dict with int/HTTPStatus keys
Returns:
Response dict with string keys
"""Utility functions for processing HTTP methods and URL rules.
def parse_method(method: str) -> HTTPMethod:
"""
Parse HTTP method from string.
Args:
method: HTTP method string
Returns:
HTTPMethod enum value
"""
def parse_rule(rule: str) -> str:
"""
Parse URL rule patterns.
Args:
rule: Flask URL rule string
Returns:
Processed rule string
"""Functions for processing and storing endpoint tags.
def parse_and_store_tags(
tags: Optional[list[Tag]] = None,
tag_names: Optional[list[str]] = None
) -> list[str]:
"""
Process and store endpoint tags.
Args:
tags: List of Tag objects
tag_names: List of tag name strings
Returns:
List of tag names
"""Functions for creating validation error responses.
def make_validation_error_response(e: ValidationError) -> dict:
"""
Create validation error response.
Args:
e: Pydantic ValidationError
Returns:
Error response dictionary
"""Usage Example:
from flask_openapi3.utils import make_validation_error_response
from pydantic import ValidationError, BaseModel
class User(BaseModel):
name: str
age: int
try:
User(name="John", age="invalid")
except ValidationError as e:
error_response = make_validation_error_response(e)
# Returns structured error responseHTTP_STATUS: dict[str, str]
"""HTTP status code to phrase mapping"""Usage Example:
from flask_openapi3.utils import HTTP_STATUS
# Get status phrase
status_phrase = HTTP_STATUS["200"] # "OK"
status_phrase = HTTP_STATUS["404"] # "Not Found"class HTTPMethod(str, Enum):
"""HTTP methods enumeration"""
GET = "GET"
POST = "POST"
PUT = "PUT"
DELETE = "DELETE"
PATCH = "PATCH"
HEAD = "HEAD"
OPTIONS = "OPTIONS"
TRACE = "TRACE"
CONNECT = "CONNECT"Create custom operation ID generation logic:
from flask_openapi3 import OpenAPI, Info
def custom_operation_id(*, bp_name="", name="", path="", method=""):
"""Custom operation ID generator"""
parts = []
if bp_name:
parts.append(bp_name)
if name:
parts.append(name)
parts.append(method.lower())
return "_".join(parts)
app = OpenAPI(
__name__,
info=Info(title="API", version="1.0.0"),
operation_id_callback=custom_operation_id
)Process schemas with custom logic:
from flask_openapi3.utils import get_model_schema
from pydantic import BaseModel
class User(BaseModel):
name: str
email: str
# Get schema with custom processing
schema = get_model_schema(User, mode="serialization")
# Add custom properties
schema["x-custom-property"] = "custom-value"Handle complex parameter scenarios:
from flask_openapi3.utils import parse_parameters, parse_query, parse_body
from pydantic import BaseModel
class ComplexQuery(BaseModel):
filters: dict[str, str] = {}
sort: list[str] = []
class ComplexBody(BaseModel):
data: dict[str, Any]
metadata: dict[str, str] = {}
# Parse all parameters
params = parse_parameters(
query=ComplexQuery,
body=ComplexBody
)
# Handle individual parsing
query_params, query_schema = parse_query(ComplexQuery)
body_params, body_schema = parse_body(ComplexBody)Install with Tessl CLI
npx tessl i tessl/pypi-flask-openapi3