CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-flask-openapi3

Generate REST API and OpenAPI documentation for your Flask project with automatic request/response validation using Pydantic models.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

core-classes.mddocs/

Core Application Classes

The main classes for building OpenAPI-enabled Flask applications. These classes provide the foundation for creating REST APIs with automatic documentation generation and request validation.

Capabilities

OpenAPI Application Class

The primary Flask application class that extends Flask with OpenAPI functionality, automatic request validation, and documentation generation.

class OpenAPI(APIScaffold, Flask):
    def __init__(
        self,
        import_name: str,
        *,
        info: Optional[Info] = None,
        security_schemes: Optional[SecuritySchemesDict] = None,
        responses: Optional[ResponseDict] = None,
        servers: Optional[list[Server]] = None,
        external_docs: Optional[ExternalDocumentation] = None,
        operation_id_callback: Callable = get_operation_id_for_path,
        openapi_extensions: Optional[dict[str, Any]] = None,
        validation_error_status: Union[str, int] = 422,
        validation_error_model: Type[BaseModel] = ValidationErrorModel,
        validation_error_callback: Callable = make_validation_error_response,
        doc_ui: bool = True,
        doc_prefix: str = "/openapi",
        doc_url: str = "/openapi.json",
        **kwargs: Any
    ):
        """
        OpenAPI class that provides REST API functionality along with Swagger UI and Redoc.

        Args:
            import_name: The import name for the Flask application.
            info: Information about the API (title, version, etc.).
            security_schemes: Security schemes for the API.
            responses: API responses should be either a subclass of BaseModel, a dictionary, or None.
            servers: An array of Server objects providing connectivity information to a target server.
            external_docs: External documentation for the API.
            operation_id_callback: Callback function for custom operation ID generation.
            openapi_extensions: Extensions to the OpenAPI Schema.
            validation_error_status: HTTP Status of the response given when a validation error is detected.
            validation_error_model: Validation error response model for OpenAPI Specification.
            validation_error_callback: Validation error response callback.
            doc_ui: Enable OpenAPI document UI (Swagger UI and Redoc).
            doc_prefix: URL prefix used for OpenAPI document and UI.
            doc_url: URL for accessing the OpenAPI specification document in JSON format.
            **kwargs: Additional kwargs to be passed to Flask.
        """

Usage Example:

from flask_openapi3 import OpenAPI, Info, Tag
from pydantic import BaseModel

# Create API info
info = Info(title="My API", version="1.0.0", description="API documentation")
tags = [Tag(name="users", description="User management")]

# Create OpenAPI app
app = OpenAPI(__name__, info=info)

# Define models
class User(BaseModel):
    name: str
    email: str

# Add routes with automatic validation
@app.post("/users", tags=tags, responses={201: User})
def create_user(body: User):
    return body.model_dump()

# Access OpenAPI spec at /openapi.json
# Access Swagger UI at /openapi

OpenAPI Methods

Additional methods available on the OpenAPI class:

@property
def api_doc(self) -> dict:
    """
    Generate the OpenAPI specification JSON.
    
    Returns:
        The OpenAPI specification JSON as a dictionary.
    """

def register_api_view(
    self,
    api_view: APIView,
    url_prefix: Optional[str] = None,
    view_kwargs: Optional[dict[Any, Any]] = None
) -> None:
    """
    Register APIView instance with the application.
    
    Args:
        api_view: The APIView instance to register.
        url_prefix: A path to prepend to all the APIView's urls
        view_kwargs: Additional keyword arguments to pass to the API views.
    """

APIBlueprint Class

Flask Blueprint with OpenAPI support for organizing related API endpoints into modules.

class APIBlueprint(APIScaffold, Blueprint):
    def __init__(
        self,
        name: str,
        import_name: str,
        *,
        abp_tags: Optional[list[Tag]] = None,
        abp_security: Optional[list[dict[str, list[str]]]] = None,
        abp_responses: Optional[ResponseDict] = None,
        doc_ui: bool = True,
        operation_id_callback: Callable = get_operation_id_for_path,
        **kwargs: Any
    ):
        """
        Based on Flask Blueprint with OpenAPI functionality.

        Args:
            name: The name of the blueprint.
            import_name: The name of the blueprint package, usually __name__.
            abp_tags: APIBlueprint tags for every API.
            abp_security: APIBlueprint security for every API.
            abp_responses: API responses should be either a subclass of BaseModel, a dictionary, or None.
            doc_ui: Enable OpenAPI document UI.
            operation_id_callback: Callback function for custom operation_id generation.
            **kwargs: Additional kwargs passed to Blueprint.
        """

Usage Example:

from flask_openapi3 import OpenAPI, APIBlueprint, Info, Tag
from pydantic import BaseModel

# Create main app
app = OpenAPI(__name__, info=Info(title="API", version="1.0.0"))

# Create blueprint with tags
user_tag = Tag(name="users", description="User operations")
users_bp = APIBlueprint("users", __name__, abp_tags=[user_tag])

class User(BaseModel):
    id: int
    name: str

# Add routes to blueprint
@users_bp.get("/users", responses={200: list[User]})
def get_users():
    return [{"id": 1, "name": "John"}]

# Register blueprint
app.register_api(users_bp)

APIView Class

Class-based views for organizing related API endpoints using method-based routing.

class APIView:
    def __init__(
        self,
        url_prefix: Optional[str] = None,
        view_tags: Optional[list[Tag]] = None,
        view_security: Optional[list[dict[str, list[str]]]] = None,
        view_responses: Optional[ResponseDict] = None,
        doc_ui: bool = True,
        operation_id_callback: Callable = get_operation_id_for_path,
    ):
        """
        Create a class-based view

        Args:
            url_prefix: A path to prepend to all the APIView's urls
            view_tags: APIView tags for every API.
            view_security: APIView security for every API.
            view_responses: API responses should be either a subclass of BaseModel, a dictionary, or None.
            doc_ui: Enable OpenAPI document UI.
            operation_id_callback: Callback function for custom operation_id generation.
        """

    def route(self, rule: str):
        """Decorator for view class registration"""
    
    def doc(
        self,
        *,
        tags: Optional[list[Tag]] = None,
        summary: Optional[str] = None,
        description: Optional[str] = None,
        external_docs: Optional[ExternalDocumentation] = None,
        operation_id: Optional[str] = None,
        responses: Optional[ResponseDict] = None,
        deprecated: Optional[bool] = None,
        security: Optional[list[dict[str, list[Any]]]] = None,
        servers: Optional[list[Server]] = None,
        openapi_extensions: Optional[dict[str, Any]] = None,
        doc_ui: bool = True
    ) -> Callable:
        """
        Decorator for view method documentation.
        
        Args:
            tags: Adds metadata to a single tag.
            summary: A short summary of what the operation does.
            description: A verbose explanation of the operation behavior.
            external_docs: Additional external documentation for this operation.
            operation_id: Unique string used to identify the operation.
            responses: API responses should be either a subclass of BaseModel, a dictionary, or None.
            deprecated: Declares this operation to be deprecated.
            security: A declaration of which security mechanisms can be used for this operation.
            servers: An alternative server array to service this operation.
            openapi_extensions: Extensions to the OpenAPI Schema.
            doc_ui: Enable OpenAPI document UI for this operation.
        """
    
    def register(
        self,
        app: "OpenAPI",
        url_prefix: Optional[str] = None,
        view_kwargs: Optional[dict[Any, Any]] = None
    ) -> None:
        """
        Register the API views with the given OpenAPI app.
        
        Args:
            app: An instance of the OpenAPI app.
            url_prefix: A path to prepend to all the APIView's urls
            view_kwargs: Additional keyword arguments to pass to the API views.
        """

Usage Example:

from flask_openapi3 import OpenAPI, APIView, Info, Tag
from pydantic import BaseModel

app = OpenAPI(__name__, info=Info(title="API", version="1.0.0"))

class User(BaseModel):
    id: int
    name: str
    email: str

class UserQuery(BaseModel):
    name: str

# Create class-based view
user_tag = Tag(name="users", description="User management")

class UserView(APIView):
    def __init__(self):
        super().__init__(view_tags=[user_tag])

    def get(self, query: UserQuery):
        """Get users by name"""
        return [{"id": 1, "name": query.name, "email": "user@example.com"}]
    
    def post(self, body: User):
        """Create a new user"""
        return {"id": 2, **body.model_dump()}

# Register view
user_view = UserView()
user_view.register(app, "/users")

APIScaffold Base Class

Base class providing common API functionality shared between OpenAPI and APIBlueprint classes.

class APIScaffold:
    def _collect_openapi_info(
        self,
        rule: str,
        func: Callable,
        *,
        tags: Optional[list[Tag]] = None,
        summary: Optional[str] = None,
        description: Optional[str] = None,
        external_docs: Optional[ExternalDocumentation] = None,
        operation_id: Optional[str] = None,
        responses: Optional[ResponseDict] = None,
        deprecated: Optional[bool] = None,
        security: Optional[list[dict[str, list[Any]]]] = None,
        servers: Optional[list[Server]] = None,
        openapi_extensions: Optional[dict[str, Any]] = None,
        doc_ui: bool = True,
        method: str = HTTPMethod.GET
    ) -> ParametersTuple:
        """Collect OpenAPI information for endpoint registration"""

    def register_api(self, api) -> None:
        """Register an API component (blueprint or view)"""

    def _add_url_rule(
        self,
        rule,
        endpoint=None,
        view_func=None,
        provide_automatic_options=None,
        **options,
    ) -> None:
        """Add URL rule with OpenAPI information collection"""

Common Decorator Methods

All main classes (OpenAPI, APIBlueprint) provide HTTP method decorators for route registration:

def get(
    self,
    rule: str,
    *,
    tags: Optional[list[Tag]] = None,
    summary: Optional[str] = None,
    description: Optional[str] = None,
    external_docs: Optional[ExternalDocumentation] = None,
    operation_id: Optional[str] = None,
    responses: Optional[ResponseDict] = None,
    deprecated: Optional[bool] = None,
    security: Optional[list[dict[str, list[Any]]]] = None,
    servers: Optional[list[Server]] = None,
    openapi_extensions: Optional[dict[str, Any]] = None,
    doc_ui: bool = True,
    **options: Any
) -> Callable: ...

def post(self, rule: str, **kwargs) -> Callable: ...
def put(self, rule: str, **kwargs) -> Callable: ...
def delete(self, rule: str, **kwargs) -> Callable: ...
def patch(self, rule: str, **kwargs) -> Callable: ...
def head(self, rule: str, **kwargs) -> Callable: ...
def options(self, rule: str, **kwargs) -> Callable: ...
def trace(self, rule: str, **kwargs) -> Callable: ...

These decorators automatically handle:

  • Request validation based on function parameter types
  • Response serialization and validation
  • OpenAPI specification generation
  • Documentation UI integration

Install with Tessl CLI

npx tessl i tessl/pypi-flask-openapi3

docs

cli-commands.md

core-classes.md

index.md

openapi-models.md

utilities.md

validation.md

tile.json