APISpec Web Framework Plugins

1.2.0 · active · verified Tue Apr 14

apispec-webframeworks is a Python library providing plugins to integrate `apispec` with various web frameworks like Flask, Aiohttp, Bottle, and Tornado. These plugins were originally part of `apispec.ext` but were moved to this separate package to streamline `apispec`'s core. It is currently at version 1.2.0 and receives updates to maintain compatibility with `apispec` and relevant frameworks.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate `apispec-webframeworks` with Flask and `marshmallow` to automatically generate OpenAPI specifications from view function docstrings and Marshmallow schemas. It sets up a basic Flask application, defines an API endpoint, and exposes the generated OpenAPI JSON.

from flask import Flask
from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from apispec_webframeworks.flask import FlaskPlugin
from marshmallow import Schema, fields

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

# 2. Define a Marshmallow Schema
class ItemSchema(Schema):
    id = fields.Int(dump_only=True)
    name = fields.Str(required=True, description="The item's name")

# 3. Register the schema with APISpec
spec.components.schema("Item", schema=ItemSchema)

# 4. Initialize Flask app
app = Flask(__name__)

# 5. Define a Flask route with OpenAPI docstrings
@app.route("/items/<int:item_id>")
def get_item(item_id):
    """Get item by ID
    ---
    parameters:
      - in: path
        name: item_id
        schema:
          type: integer
        required: true
        description: Numeric ID of the item to retrieve
    responses:
      200:
        description: Item details
        content:
          application/json:
            schema: ItemSchema
      404:
        description: Item not found
    """
    # In a real app, you'd fetch from a DB
    if item_id == 1:
        return ItemSchema().dump({'id': 1, 'name': 'Sample Item'})
    return {"message": "Item not found"}, 404

# 6. Register the Flask path with APISpec (must be in request context)
with app.test_request_context():
    spec.path(view=get_item)

# 7. Add an endpoint to serve the OpenAPI spec
@app.route("/swagger.json")
def swagger_spec():
    return spec.to_dict()

# To run this example:
# 1. Save as app.py
# 2. Run: flask run
# 3. Access: http://127.0.0.1:5000/swagger.json

view raw JSON →