1

I have flask project with Marshmallow Schema classes defined in a schemas module. For example:

project 
  - app.py
  - routes.py
  - schemas/
     - schema1.py
     - schema2.py

Where schema1.py is a typical marshmallow Schema.

class FooSchema(Schema):
    name = fields.Str()

The flasgger docs show that schemas can be referenced in the docstring of a route. Here's an abridged snippet

@app.route('/colors/<palette>/')
def colors(palette):
    """Example endpoint returning a list of colors by palette
    This is using docstrings for specifications.
    ---
    parameters:
      - name: palette
        in: path
        type: string
    definitions:
      Palette:
        type: object
        properties:
          palette_name:
            type: array
            items:
              $ref: '#/definitions/Color'     <--------
    responses:
      200:
        description: A list of colors (may be filtered by palette)
        schema:
          $ref: '#/definitions/Palette'
        examples:
          rgb: ['red', 'green', 'blue']
    """

The line of interest being $ref: '#/definitions/Palette'. However, this is just an internal refrence to the definition section in the doc string.

Is there any way to just substitute a reference to the schema/schema1.py module instead? In other words, how can we drop in a schema reference to a module in the same project?

Something like $ref: 'schema/schema1.py#FooSchema'...? The examples regarding marshmallow schemas are otherwise not clear to me.

Adam Hughes
  • 14,601
  • 12
  • 83
  • 122

1 Answers1

2

Definitions should be handled in the template creating Swagger instance. For example in your case, you should define your swagger object in following manner:

from apispec.ext.marshmallow import MarshmallowPlugin
from apispec_webframeworks.flask import FlaskPlugin
from flasgger import APISpec, Swagger


plugins = [FlaskPlugin(), MarshmallowPlugin()]
spec = APISpec("My api docs", '1.0', "2.0", plugins=plugins)
template = spec.to_flasgger(app, definitions=[FooSchema])
swagger =  Swagger(app, template=template, parse=True)

After that you can use: $ref: '#/definitions/Foo' syntax in your definitions.

You may find this snippet helpful.

DevUt
  • 1,280
  • 11
  • 24
  • 1
    It will add definitions, but specs doesn't work any more and we can not have multiple api routes: https://github.com/flasgger/flasgger/issues/483 – Mojtaba May 28 '21 at 21:52