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.

Simplest app with Swagger UI

See original GitHub issue

I can’t make my app have the Swagger route. This is the simplest app with PeeWee I came up with:

import marshmallow as ma
from flask import Flask
from flask.views import MethodView
from flask_rest_api import Api, Blueprint
from peewee import TextField
from playhouse.flask_utils import FlaskDB


class Config:
    DATABASE = {
        'name': 'database.db',
        'engine': 'SqliteDatabase',
    }
    OPENAPI_URL_PREFIX = '/doc'
    OPENAPI_REDOC_PATH = '/redoc'
    OPENAPI_SWAGGER_UI_PATH = '/swagger'
    OPENAPI_SWAGGER_URL = '/swagger'
    API_SPEC_OPTIONS = {'x-internal-id': '2'}


class MyDB(FlaskDB):
    def connect_db(self):
        if self.database.is_closed():
            super(MyDB, self).connect_db()


app = Flask('My API')
app.config.from_object(Config)
api = Api(app)
db = MyDB(app)


class Pet(db.Model):
    name = TextField(unique=True)


db.database.create_tables([Pet])

pet = Pet(name='cici')
try:
    pet.save()
except:
    pass


#  @api.definition('Pet')
class PetSchema(ma.Schema):
    class Meta:
        strict = True
        ordered = True

    id = ma.fields.Int(dump_only=True)
    name = ma.fields.String()


blp = Blueprint(
    'pets',
    'pets',
    url_prefix='/pets',
    description='Operations on pets'
)


@blp.route('/')
class Pets(MethodView):
    @blp.response(PetSchema(many=True))
    def get(self):
        """List pets"""
        return Pet.select()


api.register_blueprint(blp)

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

These are the routes:

flask routes
Endpoint                Methods  Rule
----------------------  -------  -----------------------
api-docs.openapi_json   GET      /doc/openapi.json
api-docs.openapi_redoc  GET      /doc/redoc
pets.Pets               GET      /pets/
static                  GET      /static/<path:filename>

How can I enable Swagger UI?

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:23 (12 by maintainers)

github_iconTop GitHub Comments

4reactions
lafrechcommented, Nov 27, 2018

In the example above:

/doc/openapi.json  # Raw json spec
/doc/redoc  # Redoc page
/doc/swagger  # Swagger page

Thinking of it, the naming mixes PATH and URL in a not so consistent way.

The @doc decorator is unrelated. It is meant to pass additional doc, everything that can’t be inferred from the doc, either because flask-rest-api can’t guess it, or because it is lacking the feature to do so.

2reactions
lafrechcommented, Nov 19, 2018

There was an issue in the code when using OPENAPI_SWAGGER_UI_URL. It is fixed in master.

Note that this parameter is meant to pass an URL to a directory where the Swagger UI scripts can be found. The value you’re passing is wrong because it does not end with a / and I suspect you don’t really mean to use a relative URL. If you do, then that’s fine. But you still need the trailing slash. You can check what is produced in the generated html when accessing the doc page at the path you provided.

I don’t have time right now to add complete examples to the docs, but here’s a sample with the docs working:

import marshmallow as ma
from flask import Flask
from flask.views import MethodView
from flask_rest_api import Api, Blueprint


class Config:
    OPENAPI_URL_PREFIX = '/doc'
    OPENAPI_REDOC_PATH = '/redoc'
    OPENAPI_SWAGGER_UI_PATH = '/swagger'
    # The following is equivalent to OPENAPI_SWAGGER_UI_VERSION = '3.19.5'
    OPENAPI_SWAGGER_UI_URL = 'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.19.5/'


app = Flask('My API')
app.config.from_object(Config)
api = Api(app)


@api.definition('Pet')
class PetSchema(ma.Schema):
    class Meta:
        strict = True
        ordered = True

    id = ma.fields.Int(dump_only=True)
    name = ma.fields.String()


blp = Blueprint(
    'pets',
    'pets',
    url_prefix='/pets',
    description='Operations on pets'
)


@blp.route('/')
class Pets(MethodView):
    @blp.response(PetSchema(many=True))
    def get(self):
        """List pets"""
        # TODO
        # return Pet.select()


api.register_blueprint(blp)

if __name__ == '__main__':
    app.run()
Read more comments on GitHub >

github_iconTop Results From Across the Web

Swagger UI tutorial | Documenting APIs - Idratherbewriting.com
Swagger UI provides a display framework that reads an OpenAPI specification document and generates an interactive documentation website.
Read more >
Getting Started with OpenAPI Tools | Swagger Open Source
Swagger is the most widely used tooling ecosystem for developing APIs with the OpenAPI ... Use the Swagger UI to visualize and document...
Read more >
Spring Boot - with Swagger UI | Simple Programming - YouTube
Hi Guys, Welcome to Simple ProgrammingThis is going to be a two part video series where we will see how to configure swagger...
Read more >
The Simplest Way to Add Swagger to a Node.js Project
This section will guide you through installing Swagger in a Node.js project by using Swagger UI Express. We have some steps as below:....
Read more >
Simple Steps to Integrate Swagger UI in a .NET Core Application
Swagger tooling allows you to generate beautiful API documentation, including a UI to explore and test operations, directly from your routes, ...
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