Programming
Building Python APIs with Flask, Flask-RESTPlus / Flask-RESTX, and Swagger UI
How to build an interactive API dashboard in Python?
What is Swagger UI?
Swagger UI is a tool to visualize and interact with APIs which is automatically generated using the OpenAPI specification. It generates a webpage that helps us to document and interact with various APIs.
What is Flask-RESTPlus?
Flask-RESTPlus is an extension for Flask which encourages best practices with minimal setup. It provides a collection of decorators and tools to describe API and expose its documentation using Swagger.
Note: Flask-RESTPlus is no longer maintained. Consider using Flask-RESTX, a fork of Flask-RESTPlus
Installation
You can install Flask-RESTPlus with pip
pip install flask-restplus
Or install Flask-RESTX using pip (recommended):
pip install flask-restx
Minimal API
from flask import Flask
from flask_restplus import Api, Resource
app = Flask(__name__)
api = Api(app)
@api.route('/hello/')
class HelloWorld(Resource):
def get(self):
return "Hello World"
if __name__ == '__main__':
app.run()
Note: If you are using Flask-RESTX then change the import
from flask_restplus import Api, Resource
tofrom flask_restx import Api, Resource
. The rest of the code remains the same.
Save this file as app.py
(or any other filename you want), go to the terminal, and type python app.py
(i.e. python <filename>.py
) to start the program.
If you get the following error while deploying:
from werkzeug import cached_property
ImportError: cannot import name 'cached_property'
Add this line before importing flask_restplus:
import werkzeug
werkzeug.cached_property = werkzeug.utils.cached_property
Now, launch a browser and go to http://localhost:5000
and you should see this screen:
This is the Swagger UI screen. It allows you to view all the endpoints and test the APIs using the Try it out button.
You can also view the contents of the Swagger file by visiting http://localhost:5000/swagger.json
. The Swagger file generated for the above code is as follows:
{
"swagger": "2.0",
"basePath": "/",
"paths": {
"/hello/": {
"get": {
"responses": {
"200": {
"description": "Success"
}
},
"operationId": "get_hello_world",
"tags": [
"default"
]
}
}
},
"info": {
"title": "API",
"version": "1.0"
},
"produces": [
"application/json"
],
"consumes": [
"application/json"
],
"tags": [
{
"name": "default",
"description": "Default namespace"
}
],
"responses": {
"ParseError": {
"description": "When a mask can't be parsed"
},
"MaskError": {
"description": "When any error occurs on mask"
}
}
}
Fetching Request Parameters
You can fetch the parameters passed during the API call using reqparse
from flask import Flask
from flask_restplus import Api, Resource, reqparse
app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('name', help='Specify your name')
@api.route('/hello/')
class HelloWorld(Resource):
@api.doc(parser=parser)
def get(self):
args = parser.parse_args()
name = args['name']
return "Hello " + name
if __name__ == '__main__':
app.run()
In the above code, parser.parse_args()
returns a dictionary with the key as the argument's name and value as the value passed in the query.
This generates the Swagger UI as below:
Click on the Try it out button to check the API. It will result in the following output:
File Upload
To use File Upload, set the location to files
and type to FileStorage
from flask import Flask
from flask_restplus import Api, Resource
from werkzeug.datastructures import FileStorage
app = Flask(__name__)
api = Api(app)
upload_parser = api.parser()
upload_parser.add_argument('file',
location='files',
type=FileStorage)
@api.route('/upload/')
@api.expect(upload_parser)
class UploadDemo(Resource):
def post(self):
args = upload_parser.parse_args()
file = args.get('file')
print(file.filename)
return "Uploaded file is " + file.filename
if __name__ == '__main__':
app.run()
The Swagger UI generated for the above code will be as follows:
API parameters
api = Api(app,
version='10.5',
title='Flask Restplus Demo',
description='Demo to show various API parameters',
license='MIT',
contact='Jimit Dholakia',
contact_url='https://in.linkedin.com/in/jimit105',
doc = '/docs/',
prefix='/test'
)
version
→ API Version (for Swagger Documentation)
title
→ API title (for Swagger Documentation)
description
→ API Description (for Swagger Documentation)
license
→ Specify License for the API (for Swagger Documentation)
license_url
→ Specify the License page URL (for Swagger Documentation)
contact
→ Specify contact person (for Swagger Documentation)
contact_email
→ Specify the email address of contact person (for Swagger Documentation)
contact_url
→ Specify URL to contact person (for Swagger Documentation)
doc
→ Specify the path for Swagger UI Documentation. Defaults to '/'
prefix
→ Specify a prefix for all endpoints of the URL
The Swagger UI generated for the above code is as follows:
References
- https://flask-restplus.readthedocs.io/en/stable/
- https://flask-restplus.readthedocs.io/en/stable/index.html
- https://flask-restx.readthedocs.io/en/latest/index.html
Resources
All the code snippets of this article are available on my GitHub Page.
Suggested Reading
Creating RESTful Web APIs using Flask and Python
Let’s Connect
LinkedIn: https://www.linkedin.com/in/jimit105/
GitHub: https://github.com/jimit105
Twitter: https://twitter.com/jimit105