Flask API Documentation using Flask-Restx (Swagger for Flask)

Creating Swagger Documentation and UI for flask APIs with minimal code changes

Abhishek Tripathi
5 min readJan 1, 2021

What is Flask?

According to Wikipedia:

Flask is a micro web framework written in Python. It is classified as a micro-framework because it does not require particular tools or libraries.

flask is used to create Rest APIs and Render templates (html pages) in python. It supports lot of functionality, please refer the official site

Once we have created an API we would like to share the APIs and its details with others. There are different ways of sharing it like creating a collection in POSTMAN and share it with the team or somehow automate the documentation process of the API so that changes in API get documented with minimal changes in the existing code.

API Documentation:

API documentation is a technical content deliverable, containing instructions about how to effectively use and integrate with an API. API description formats like the OpenAPI/Swagger Specification have automated the documentation process, making it easier for teams to generate and maintain them.

Swagger API Sample
Swagger Documentation with Request and Response

Swagger in Java

In Java, Spring framework the process for swagger documentation is very easy, just download the dependency in maven or gradle and add swagger the configuration code( less than 10 lines) and all the APIs get documented with basic parameters and responses without any change in application code. Please check the link below for spring boot swagger config:

Swagger for Flask

There are multiple packages available for adding swagger like documentation in flask like : flask-swagger, Flask-RESTPLUSetc.

Flask-RESTX is a community fork of Flask-RESTPLUS package which is very simple to use and lets us create Swagger documentation with minimal coding or changes in existing fask application.

Getting Started : Simple Get method using flask-Restx:

Requirements

Download Flask and Flask-Restx package from pypi.org or simply run the following command

pip install flask 
pip install flask-restx

Simple Flask API

from flask import Flaskapp = Flask(__name__)@app.route('/hello',methods=['GET'])
def hello_get():
return 'hello'
if __name__ == '__main__':
app.run()

The above function will return ‘hello’ in the browser. http://localhost:5000/hello

Adding Flask-Restx

For adding swagger documentation to the above api, we have to do the following

  • Import API and Resource from flask-restx
from flask_restx import Api, Resource
  • Create api by passing app created above to the API.
api = Api(app)
  • Create a new class annotated with @api.route(<<route-address>>) with Resource as parameter for the api with get as a function of the class
@api.route('/hello')
class HelloWorld(Resource):
def get(self):
return 'hello'

Notice the changes from a flask app, the @app.route is now @api.route as we are now using flask-restx the class HelloWorld has a parameter Resource (imported from flask-restx) and the function name is get (it will be post or put for a post, put request respectively). the body is not touched. Put it all together:

from flask import Flask, request
from flask_restx import Api, Resource, reqparse

app = Flask(__name__)
api = Api(app)
@api.route('/hello')
class HelloWorld(Resource):
def get(self):
return 'hello'
if __name__ == '__main__':
app.run()
  • Run the Application:

The Swagger documentation:

Swagger For GET Request

Try the API from Swagger:

The Response is “hello” with HTTP 200

Passing Parameters

Passing Parameters both path as well as query parameters is very simple:

Path Parameter:

  • Include the parameter name with type within the api.route
@api.route('/hello/<string:id>')
  • Include the parameter in the get method defined
def get(self,id)

Query Parameter:

  • Define the parameters in the parser module of the flask-restx package.
parser = reqparse.RequestParser()
parser.add_argument('var1', type=str, help='variable 1')
parser.add_argument('var2', type=str, help='variable 2')
  • Add @api.doc annotation with parser as a parameter
@api.doc(parser=parser)
def get(self):

Complete code:

from flask import Flask, request
from flask_restx import Api, Resource, reqparse

app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('var1', type=str, help='variable 1')
parser.add_argument('var2', type=str, help='variable 2')
@api.route('/hello/<string:id>')
class HelloWorldParameter(Resource):
@api.doc(parser=parser)
def get(self,id):
args = parser.parse_args()
post_var1 = args['var1']
post_var2 = args['var2']
return 'Hello : ' + post_var1 + post_var2 + id
if __name__ == '__main__':
app.run()

Run the Application and open the swagger UI at http://localhost:5000/

Swagger API Documentation with parameters
Trying the API by passing the parameters

Post and Put Request

For Post and Put request only need to add a post or put method like get method and restart the application.

@api.route('/hello/<string:id>')
class HelloWorldParameter(Resource):
@api.doc(parser=parser)
def post(self, id):
args = parser.parse_args()
post_var1 = args['var1']
post_var2 = args['var2']
return 'Hello : ' + post_var1 + ' ' + post_var2 + ' ' + id

Restart the Application and open the swagger UI at http://localhost:5000/

POST API Swagger
Trying it out with values.

For more information and examples please refer the official documentation page

Hope this helps you to get started with flask swagger documentation.

Thanks.

--

--

Abhishek Tripathi
Abhishek Tripathi

Responses (1)