What is flask swagger?

Swagger is a web-based API documentation framework. Users use the Swagger documentation framework to create interactive documents for inbuilt APIs to only work on specific purposes. Swagger documentation has many advantages compared to other document types because it is an open source that helps you create and share API documentation.

Flask-rest plus default provides Swagger documentation, which is done from the root URL of the API. If we run a code and visit the API's root URL, you can view the automatically generated Swagger UI documentation.

This article will look at how to add swagger UI to flask API without using additional libraries.

Installation

Download swagger UI from GitHub and extract that file.

You can get it by clicking on the download, and then extract the file.

Download

 Now you can copy the files from dist to your project directory by the following steps:

  • Create two directories of name templates and static in your project file.
  • Move index.html from dist to templates directory and rename it as swaggerui.html
  • Create more three directories of name CSS, img, and js inside the static directory.
  • Move .js files to static/js from dist
  • Move .css files to static/css from dist
  • Move .png files to static/img from dist

API project

Now we edit swaggerui.html and replace all static URLs with jinja2 template tags.

To write your API in open API format, we go to the swagger editor and type the sample code given below

openapi: 3.0.0
info:
  version: 1.0.0
  title: hello API
  description: An API to return hello in requested language


paths:
  /api:
    get:
      tags:
        - Hello
      description: Returns hello in specified language
      parameters:
        - in: query
          name: lang
          required: true
          description: language
          schema:
            type: string
            example: es


      responses:
        '200':
          description: hello in the requested language
          content:
            text/plain:
              schema:
                type: string
                example: hello 

Now go to the file menu in the swagger editor and click on the option convert and save as JSON. Once you place the file to JSON, you have to place the downloaded      swagger-initializer.js file in your project's static directory and update the source JSON file in the swaggerui.html file to a specific static directory.  

Now, as we have completed the setup of the swagger and the flask connection, we return swaggerui.html with the flask render template in the preferred route.

Then, create a hello-world_api.py in your project using the following code

from flask import Flask, request, jsonify, render_template

app = Flask(__name__)


@app.route('/')
def get_root():
    print('sending root')
    return render_template('index.html')


@app.route('/api/docs')
def get_docs():
    print('sending docs')
    return render_template('swaggerui.html')


@app.route('/api')
def get_api():
    hello_dict = {'en': 'Hello', 'es': 'Hola'}
    lang = request.args.get('lang')
    return jsonify(hello-world_dict[lang])


app.run(use_reloader=True, debug=False)

now we run this application by using the following command

python3 hello-world_api.py

by this, we added swagger UI to a flask API project with an open API file.

Some advantages of swagger are

  • You can synchronize the API documentation with the server and client in same time
  • It allows us to generate REST API documentations and interact with the REST API
  • This provides proper responses in the format of JSON and Xml files,
  • It also implementations are available for various technologies like scala, java, and HTML5.
  • It can be used to directly automate API-dependent processes.
  • We can find it integrated to popular and powerful tools such as WSO2.

Conclusion

Adding swagger to flask helps users build, document, test, and consume RESTful web services, which can be used in both a top-down and bottom-up API development approach. Swagger can be used to design an API before any code is written.  

Swagger provides a method to automate the documentation using GET, PUT, POST, and DELETE attributes and prepares itself. Swagger automatically updates itself if there are any changes in it. So, swagger in flask provides a method called swagger that inspects the flask application for endpoints that contain YAML docstrings.