CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-apispec

A pluggable API specification generator for OpenAPI/Swagger specifications

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

components.mddocs/

Component Management

Management of reusable OpenAPI components including schemas, responses, parameters, headers, examples, and security schemes. Components enable reusability and maintainability in OpenAPI specifications through reference-based definitions.

Capabilities

Schema Management

Register and manage schema components that define data structures used throughout the API specification.

def schema(
    self,
    component_id: str,
    component: dict | None = None,
    *,
    lazy: bool = False,
    **kwargs: Any
) -> Components:
    """
    Add a new schema to the specification.
    
    Parameters:
    - component_id: Identifier by which schema may be referenced
    - component: Schema definition dictionary
    - lazy: Register component only when referenced in the spec
    - **kwargs: Plugin-specific arguments (e.g., marshmallow metadata)
    
    Returns:
    Self for method chaining
    
    Raises:
    - DuplicateComponentNameError: If component_id already exists
    """

Response Management

Register reusable response components that can be referenced across multiple operations.

def response(
    self,
    component_id: str,
    component: dict | None = None,
    *,
    lazy: bool = False,
    **kwargs: Any
) -> Components:
    """
    Add a response which can be referenced.
    
    Parameters:
    - component_id: Identifier by which response may be referenced
    - component: Response definition dictionary
    - lazy: Register component only when referenced in the spec
    - **kwargs: Plugin-specific arguments
    
    Returns:
    Self for method chaining
    
    Raises:
    - DuplicateComponentNameError: If component_id already exists
    """

Parameter Management

Register reusable parameter components for path, query, header, and cookie parameters.

def parameter(
    self,
    component_id: str,
    location: str,
    component: dict | None = None,
    *,
    lazy: bool = False,
    **kwargs: Any
) -> Components:
    """
    Add a parameter which can be referenced.
    
    Parameters:
    - component_id: Identifier by which parameter may be referenced
    - location: Parameter location ('path', 'query', 'header', 'cookie')
    - component: Parameter definition dictionary
    - lazy: Register component only when referenced in the spec
    - **kwargs: Plugin-specific arguments
    
    Returns:
    Self for method chaining
    
    Raises:
    - DuplicateComponentNameError: If component_id already exists
    
    Note:
    Path parameters automatically have required=True set
    """

Header Management

Register reusable header components for response headers.

def header(
    self,
    component_id: str,
    component: dict,
    *,
    lazy: bool = False,
    **kwargs: Any
) -> Components:
    """
    Add a header which can be referenced.
    
    Parameters:
    - component_id: Identifier by which header may be referenced
    - component: Header definition dictionary
    - lazy: Register component only when referenced in the spec
    - **kwargs: Plugin-specific arguments
    
    Returns:
    Self for method chaining
    
    Raises:
    - DuplicateComponentNameError: If component_id already exists
    """

Example Management

Register reusable example components for request and response examples.

def example(
    self,
    component_id: str,
    component: dict,
    *,
    lazy: bool = False
) -> Components:
    """
    Add an example which can be referenced.
    
    Parameters:
    - component_id: Identifier by which example may be referenced
    - component: Example definition dictionary
    - lazy: Register component only when referenced in the spec
    
    Returns:
    Self for method chaining
    
    Raises:
    - DuplicateComponentNameError: If component_id already exists
    """

Security Scheme Management

Register security scheme components for API authentication and authorization.

def security_scheme(self, component_id: str, component: dict) -> Components:
    """
    Add a security scheme which can be referenced.
    
    Parameters:
    - component_id: Identifier by which security scheme may be referenced
    - component: Security scheme definition dictionary
    
    Returns:
    Self for method chaining
    
    Raises:
    - DuplicateComponentNameError: If component_id already exists
    """

Reference Resolution

Convert component references to proper OpenAPI reference objects or return inline definitions.

def get_ref(
    self,
    obj_type: str,
    obj_or_component_id: dict | str
) -> dict:
    """
    Return object or reference for a component.
    
    Parameters:
    - obj_type: Component type ('schema', 'parameter', 'response', 'header', 'example', 'security_scheme')
    - obj_or_component_id: Either a complete definition dict or a reference ID string
    
    Returns:
    Either the complete definition dict or a $ref object
    """

Component Serialization

Convert all registered components to their OpenAPI specification format.

def to_dict(self) -> dict[str, dict]:
    """
    Convert components to dictionary format for OpenAPI specification.
    
    Returns:
    Dictionary mapping component sections to their definitions
    """

Properties

Component storage properties providing access to registered components.

schemas: dict[str, dict]  # Schema components
responses: dict[str, dict]  # Response components  
parameters: dict[str, dict]  # Parameter components
headers: dict[str, dict]  # Header components
examples: dict[str, dict]  # Example components
security_schemes: dict[str, dict]  # Security scheme components
schemas_lazy: dict[str, dict]  # Lazy schema components storage
responses_lazy: dict[str, dict]  # Lazy response components storage
parameters_lazy: dict[str, dict]  # Lazy parameter components storage
headers_lazy: dict[str, dict]  # Lazy header components storage
examples_lazy: dict[str, dict]  # Lazy example components storage
openapi_version: Version  # OpenAPI version for reference formatting

Usage Examples

Schema Components

from apispec import APISpec

spec = APISpec(title="API", version="1.0.0", openapi_version="3.0.2")

# Register schema components
spec.components.schema("User", {
    "type": "object",
    "properties": {
        "id": {"type": "integer", "readOnly": True},
        "name": {"type": "string"},
        "email": {"type": "string", "format": "email"}
    },
    "required": ["name", "email"]
})

spec.components.schema("Error", {
    "type": "object", 
    "properties": {
        "code": {"type": "integer"},
        "message": {"type": "string"}
    },
    "required": ["code", "message"]
})

Response Components

# Register response components
spec.components.response("NotFound", {
    "description": "Resource not found",
    "content": {
        "application/json": {
            "schema": {"$ref": "#/components/schemas/Error"}
        }
    }
})

spec.components.response("UserResponse", {
    "description": "User information",
    "content": {
        "application/json": {
            "schema": {"$ref": "#/components/schemas/User"}
        }
    }
})

Parameter Components

# Register parameter components
spec.components.parameter("UserId", "path", {
    "description": "Unique identifier for a user",
    "schema": {"type": "integer", "minimum": 1}
})

spec.components.parameter("Limit", "query", {
    "description": "Maximum number of results to return",
    "schema": {"type": "integer", "minimum": 1, "maximum": 100, "default": 20}
})

Security Schemes

# Register security schemes
spec.components.security_scheme("ApiKeyAuth", {
    "type": "apiKey",
    "in": "header", 
    "name": "X-API-Key"
})

spec.components.security_scheme("BearerAuth", {
    "type": "http",
    "scheme": "bearer",
    "bearerFormat": "JWT"
})

Using Components in Paths

# Use registered components in path definitions
spec.path("/users/{id}", operations={
    "get": {
        "summary": "Get user by ID",
        "parameters": [
            {"$ref": "#/components/parameters/UserId"}
        ],
        "responses": {
            "200": {"$ref": "#/components/responses/UserResponse"},
            "404": {"$ref": "#/components/responses/NotFound"}
        },
        "security": [{"ApiKeyAuth": []}]
    }
})

Lazy Registration

# Register components lazily - only included in spec when referenced
spec.components.schema("LazyUser", user_schema_dict, lazy=True)

# Component will be registered when first referenced
user_ref = spec.components.get_ref("schema", "LazyUser")

Install with Tessl CLI

npx tessl i tessl/pypi-apispec

docs

components.md

core-spec.md

index.md

marshmallow.md

plugin-system.md

utils.md

tile.json