Can we automatically add Marshmallow shemas to swagger `api.doc()`?

Viewed 5267

I have an API which I would like to display via Swagger UI. I do so by:

bp = Blueprint("api", __name__)
api = Api(bp)

@api.doc(
    description="Description, I want to add schema here",
    responses={200: "Success"},
)
def post(self):
    """ Appears in Title of Swagger
        Authorization: Bearer <auth-key>
    """
    return jsonify(200)

Lets say I have the followinig Schema:

class SomeSchema(Schema):
    id = fields.String(required=True)

Is there a way to display this schema automatically for swagger? For example I would like to fill in:

enter image description here

to have contain the fields automatically.

2 Answers

This is exactly what apispec is made for. It is developed by the marshmallow team.

(You may also be interested in webargs to parse inputs with marshmallow. And flask-smorest for an integration of apispec and webargs into a complete API framework.)

Disclaimer: marshmallow/apispec/webargs/flask-smorest maintainer.

If you want to avoid using apispec as I did, you can manually convert the marshmallow schema to a flask model and use it on the api.expect decorator.

from flask_restx import fields as flask_fields
from marshmallow import fields as marshmallow_fields

# Map your types conversion here
TYPE_MAPPING = {
    marshmallow_fields.String: flask_fields.String,
    marshmallow_fields.Number: flask_fields.Integer,
    marshmallow_fields.DateTime: flask_fields.DateTime,
}

def convert_schema_to_flask_model(schema):
    schema_fields = getattr(schema, "_declared_fields")
    converted_schema = {}

    for field in schema_fields:
        converted_schema[field] = TYPE_MAPPING[type(schema_fields[field])]

    return converted_schema
Related