Swagger with Flask
Posted on
by Kevin FoongSwagger is a great tool which enables us to document our API structure and allow others to test it out. Here I will provide an overview on how we can set up Swagger on a Flask API project.
We will use the Flask-Swagger-UI library. Note that this library provides Swagger via a blueprint so we will also need to be using blueprints in Flask (which this post will not go through).
- First we install Flask-Swagger-UI
pip install flask-swagger-ui
- Next we configure Flask-Swagger-UI. See below an example init.py file.
SWAGGER_URL is the url where we access Swagger
API_URL is where the physical swagger.json file is located
from flask import Flask from config import Config from flask_swagger_ui import get_swaggerui_blueprint SWAGGER_URL = '/swagger' API_URL = '/static/swagger.json' SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={ 'app_name': "MyApp" } ) def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) with app.app_context(): db.init_app(app) app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL) return app
- Now we just need to create the swagger.json file we specified in API_URL
A nice way to do this is to use the online Swagger editor at https://editor.swagger.io/. The editor by default already provides a skeleton specification so you can use this as the starting point for your own specification. You can first create your specification in YAML (Yet Another Markup Language) format then output the final version in JSON format for Flask. For reference we can refer to the OpenAPI specification in which Swagger is based on, at http://spec.openapis.org/oas/v3.0.3. - Run Flask. We can now access Swagger via the URL we previously specified.
We can now use Swagger to view our API structure as well as to test it out live.
We have integrated Swagger with our Flask API but at the moment the creation of the swagger json file is still done manually. This means that changing our API in Flask will also mean that we will need to change our Swagger file to reflect that. There are some existing packages like Flask-Restplus which is quite useful to help create API's as well as automatically generating Swagger documentation. However if you prefer to create an API without any third-party libraries and just use plain Flask then integrating Swagger in the way described here is a good option.