question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Is it possible to use flask_restful + marshmallow

See original GitHub issue

I’m looking at this example that uses the docstring to specify the swagger: https://github.com/rochacbruno/flasgger/blob/master/examples/restful.py

In this example it seems like I cannot use use @swag_from like in the marshmallow example, instead I must use the docstring to pass the swagger description: https://github.com/rochacbruno/flasgger/blob/master/examples/marshmallow_apispec.py

However, I would like to define my models using a Marshmallow schema, and then simply refer to those in the $ref. Is that possible?

I mean currently, since I never tell flasgger anywhere about my schemas, it does not know that it should output them to the definitions in the final swagger JSON. Can I make it do this somehow?

There’s a lot of overlapping functionality with all these projects flask, flask_restful and marshmallow, so maybe there is some easier way.

Issue Analytics

  • State:open
  • Created 6 years ago
  • Comments:10 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
ghostcommented, Feb 9, 2021

I made a little workaround, “not beautiful but rare”. At first I tried to register my Schemas via the swagger.definition decorator. As this decorator accepts only classes with the yaml docstring annotation I shortly converted the Marshmallow-Schema to these (Named “Magic” here as it does the very uncommon stuff; Also cut some sqlalchemy stuff from my application, so it has no claim to be complete):

from flask import Flask, request, Response
from flask_marshmallow import Marshmallow
from marshmallow import fields
import yaml
from flasgger.marshmallow_apispec import schema2jsonschema
from flasgger import Swagger, Schema
from flask_restful import Api, Resource

app = Flask(__name__)
ma = Marshmallow(app)
api = Api(app)
swagger = Swagger(app)


def definition(name):
    def magic(schema_class):
        # Build the schema definition as a json
        spec = schema2jsonschema(schema_class)
        # convert the json objects to a yaml
        yaml_spec = yaml.dump(spec)
        # build the docstring. something like: 
        # """Plugin
        # ---
        # properties:
        # description:
        #     type: string
        # id:
        #     type: integer
        # name:
        #     type: string
        # type: object
        # """
        as_docstring = f"{name}\n---\n{yaml_spec}"

        # Define a class and place the docstring
        class Magic(object):
            pass

        Magic.__doc__ = as_docstring
        # invoke the decorator with our class
        swagger.definition(name)(Magic)
        return schema_class

    return magic


@definition("Plugin")
class PluginSchema(Schema):
    class Meta:
        model = Plugin

    id = fields.Integer()
    name = fields.String()
    description = fields.String()


plugin_schema = PluginSchema()
plugins_schema = PluginSchema(many=True)


class PluginListResource(Resource):
    def get(self):
        """
        Get a list of plugins.
        ---
        responses:
            200:
                description: A list of plugins
                schema:
                    type: "array"
                    items:
                        $ref: "#/definitions/Plugin"
        """
        plugins = Plugin.query
        return plugins_schema.dump(plugins)

    def post(self):
        """
        Create a new plugin
        ---
        parameters:
            - in: body
              name: body
              schema:
                  $ref: '#/definitions/Plugin'
        responses:
            200:
                description: The plugin that has been generated.
                schema:
                    $ref: "#/definitions/Plugin"
        """
        new_plugin = Plugin(
            name=request.json['name'],
            description=request.json['description'],
        )
        db.session.add(new_plugin)
        db.session.commit()
        return plugin_schema.dump(new_plugin)


api.add_resource(PluginListResource, '/plugins')

I hope this helps anyone who finds this ticket like me 😃 Also, maybe I missed a way where this is implemented correctly inside flasgger, this was only an internal prototype anyway. It still would be nice to have a common way for this (maybe by just adjusting the swagger.definition decorator, like

@swagger.definition("Plugin")
class PluginSchema(Schema):
    class Meta:
        model = Plugin

    id = fields.Integer()
    name = fields.String()
    description = fields.String()

).

1reaction
netrounds-joakimcommented, Jun 7, 2017

Ah yes that is one use case.

But from articulating my question and now looking at the Marshmallow example again I now saw this that I had missed before: https://github.com/rochacbruno/flasgger/blob/master/examples/marshmallow_apispec.py#L45-L47

definitions = {
     'User': User  # if nto informed will be extracted from usage above
}

Which does what I requested above. Except that it’s inside of the SwaggerView class. And it works now like I want 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Flask-Marshmallow: Flask + marshmallow for beautiful APIs ...
Integrates the marshmallow serialization/deserialization library with your Flask application. ... Wrapper class that integrates Marshmallow with a Flask ...
Read more >
Building REST APIs using Flask-RESTPlus, SQLAlchemy ...
The Flask-Marshmallow extension acts as a thin integration layer for Flask and Marshmallow that adds additional features to Marshmallow, ...
Read more >
flask-based REST api: marshmallow vs flask-restful [closed]
Marshmallow is a serialization/deserialization library and flask-restful is a package to build REST APIs. Yes there are some benefits from ...
Read more >
How To Marshal Data With Flask
Marshmallow. Flask-RESTful has a notice in its documentation that its own request parsing features will eventually be deprecated, and recommends ...
Read more >
Flask with SQLAlchemy & Marshmallow - DEV Community ‍ ‍
Flask Marshmallow Flask with SQLAlchemy & Marshmallow · Step 1: Setup Project Environment · Step 2: Install Flask and Other Dependencies · Step...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found