A pluggable API specification generator for OpenAPI/Swagger specifications
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Central API specification creation and management with support for OpenAPI 2.x and 3.x formats. The APISpec class serves as the main orchestrator for building OpenAPI specifications programmatically.
Main class for creating and managing OpenAPI specifications. Handles specification metadata, component management, path definitions, and output generation.
class APISpec:
def __init__(
self,
title: str,
version: str,
openapi_version: str,
plugins: Sequence[BasePlugin] = (),
**options: Any
):
"""
Create a new APISpec instance.
Parameters:
- title: API title
- version: API version
- openapi_version: OpenAPI Specification version ('2.x' or '3.x.x')
- plugins: Plugin instances for framework integration
- **options: Additional top-level OpenAPI fields
"""Generate the final OpenAPI specification in dictionary or YAML format for consumption by OpenAPI tools and documentation generators.
def to_dict(self) -> dict[str, Any]:
"""
Return the specification as a dictionary.
Returns:
Dictionary containing the complete OpenAPI specification
"""
def to_yaml(self, yaml_dump_kwargs: Any | None = None) -> str:
"""
Render the specification to YAML string.
Parameters:
- yaml_dump_kwargs: Additional arguments to pass to yaml.dump
Returns:
YAML string representation of the specification
"""Add tag information to organize and categorize API operations in the generated specification.
def tag(self, tag: dict) -> APISpec:
"""
Store information about a tag.
Parameters:
- tag: Dictionary containing tag information (name, description, etc.)
Returns:
Self for method chaining
"""Add path objects (endpoints) to the specification with HTTP operations, parameters, and responses.
def path(
self,
path: str | None = None,
*,
operations: dict[str, Any] | None = None,
summary: str | None = None,
description: str | None = None,
parameters: list[dict] | None = None,
**kwargs: Any
) -> APISpec:
"""
Add a new path object to the specification.
Parameters:
- path: URL path component (e.g., '/users/{id}')
- operations: Dictionary mapping HTTP methods to operation objects
- summary: Short summary relevant to all operations in this path
- description: Long description relevant to all operations in this path
- parameters: List of parameters relevant to all operations in this path
- **kwargs: Parameters used by path helpers from plugins
Returns:
Self for method chaining
"""Access to specification metadata and configuration.
title: str # API title
version: str # API version
openapi_version: Version # OpenAPI version object
plugins: Sequence[BasePlugin] # Registered plugins
options: dict # Additional top-level options
components: Components # Component management instanceOpenAPI version and method validation constants.
VALID_METHODS_OPENAPI_V2: list[str] # ['get', 'post', 'put', 'patch', 'delete', 'head', 'options']
VALID_METHODS_OPENAPI_V3: list[str] # VALID_METHODS_OPENAPI_V2 + ['trace']
VALID_METHODS: dict[int, list[str]] # {2: VALID_METHODS_OPENAPI_V2, 3: VALID_METHODS_OPENAPI_V3}
MIN_INCLUSIVE_OPENAPI_VERSION: Version # Version("2.0")
MAX_EXCLUSIVE_OPENAPI_VERSION: Version # Version("4.0")from apispec import APISpec
# Create OpenAPI 3.0 specification
spec = APISpec(
title="Pet Store API",
version="1.0.0",
openapi_version="3.0.2",
info={
"description": "A simple pet store API",
"contact": {"name": "API Support", "email": "support@petstore.com"}
}
)
# Add tags for organization
spec.tag({
"name": "pets",
"description": "Operations on pets"
})# Add a path with multiple operations
spec.path(
"/pets",
operations={
"get": {
"tags": ["pets"],
"summary": "List all pets",
"parameters": [
{
"name": "limit",
"in": "query",
"schema": {"type": "integer", "maximum": 100}
}
],
"responses": {
"200": {
"description": "List of pets",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {"$ref": "#/components/schemas/Pet"}
}
}
}
}
}
},
"post": {
"tags": ["pets"],
"summary": "Create a pet",
"requestBody": {
"required": True,
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Pet"}
}
}
},
"responses": {
"201": {"description": "Pet created"},
"400": {"description": "Invalid input"}
}
}
}
)# Get specification as dictionary
spec_dict = spec.to_dict()
# Get specification as YAML
spec_yaml = spec.to_yaml()
# Custom YAML options
spec_yaml_custom = spec.to_yaml({
"sort_keys": True,
"indent": 4
})Install with Tessl CLI
npx tessl i tessl/pypi-apispec