APISpec

6.10.0 · active · verified Sun Apr 05

APISpec is a pluggable Python library designed for generating API specifications. It primarily supports the OpenAPI Specification (formerly known as the Swagger specification), enabling developers to programmatically define their API's structure, endpoints, and data models. It is framework-agnostic and offers built-in integration capabilities, notably with Marshmallow. The library maintains an active development status, with frequent patch and minor releases, and new major versions typically released on an annual or bi-annual cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize an `APISpec` object, define a Marshmallow schema, register it as an OpenAPI component, and then add a path with an operation that references the defined schema. Finally, it prints the generated OpenAPI specification in JSON format. This illustrates the basic programmatic API definition workflow using `apispec` and its Marshmallow plugin.

from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from marshmallow import Schema, fields
import json

# 1. Create an APISpec object
spec = APISpec(
    title="My Awesome API",
    version="1.0.0",
    openapi_version="3.0.2",
    info=dict(description="A minimal example of APISpec"),
    plugins=[
        MarshmallowPlugin(),
    ],
)

# 2. Define a Marshmallow Schema and register it as an OpenAPI component
class UserSchema(Schema):
    id = fields.Int(dump_only=True)
    name = fields.Str(required=True, description="The user's name")
    email = fields.Email(required=True, description="The user's email address")

spec.components.schema("User", schema=UserSchema)

# 3. Add a path with operations referencing the schema
spec.path(
    path="/users/{user_id}",
    operations=dict(
        get=dict(
            summary="Get user by ID",
            parameters=[
                {
                    "in": "path",
                    "name": "user_id",
                    "schema": {"type": "integer"},
                    "required": True,
                    "description": "Numeric ID of the user to get",
                }
            ],
            responses={
                200: {
                    "description": "User data",
                    "content": {"application/json": {"schema": {"$ref": "#/components/schemas/User"}}},
                }
            },
        )
    ),
)

# 4. Output the spec as JSON
print(json.dumps(spec.to_dict(), indent=2))

view raw JSON →