Flask-APISpec

0.11.4 · active · verified Thu Apr 16

Flask-APISpec provides a convenient layer for integrating APISpec and webargs/marshmallow with Flask applications to automatically generate OpenAPI/Swagger documentation for REST APIs. It simplifies schema definition and request/response marshaling. The current version is 0.11.4, and releases are infrequent, often following `apispec` updates or Flask compatibility requirements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a Marshmallow schema, apply `doc`, `use_kwargs`, and `marshal_with` decorators to Flask routes, and initialize `FlaskApiSpec` to generate OpenAPI documentation accessible via `/swagger-ui/`.

from flask import Flask, jsonify
from flask_apispec import doc, use_kwargs, marshal_with
from flask_apispec.extension import FlaskApiSpec
from marshmallow import Schema, fields

app = Flask(__name__)
app.config.update({
    'APISPEC_SPEC': {
        'title': 'My Awesome API',
        'version': 'v1',
        'openapi_version': '3.0.0' # Recommended for modern APIs
    },
    'APISPEC_SWAGGER_URL': '/swagger/',
    'APISPEC_SWAGGER_UI_URL': '/swagger-ui/'
})
docs = FlaskApiSpec(app)

class ItemSchema(Schema):
    id = fields.Int(dump_only=True)
    name = fields.Str(required=True, description='Name of the item')
    description = fields.Str(required=False, description='Description of the item')

items_db = {}
next_id = 1

@app.route('/items', methods=['POST'])
@doc(description='Create a new item', tags=['Items'])
@use_kwargs(ItemSchema, location='json')
@marshal_with(ItemSchema, code=201)
def create_item(**kwargs):
    global next_id
    item = kwargs
    item['id'] = next_id
    items_db[next_id] = item
    next_id += 1
    return jsonify(item), 201

@app.route('/items/<int:item_id>', methods=['GET'])
@doc(description='Get an item by ID', tags=['Items'], params={'item_id': {'description': 'Item ID', 'type': 'integer'}})
@marshal_with(ItemSchema, code=200)
def get_item(item_id):
    item = items_db.get(item_id)
    if item: 
        return jsonify(item), 200
    return jsonify({'message': 'Item not found'}), 404

docs.register(create_item)
docs.register(get_item)

if __name__ == '__main__':
    app.run(debug=True)

view raw JSON →