Creating a Hello World API using Swagger UI and Python

Getting started with your first Swagger UI document

Bhargav S
Bhargav S
Jul 30 · 5 min read

Swagger is a web-based API documentation framework. It is used to create interactive documents for APIs which are built to serve a specific purpose. Swagger UI documents enjoy many advantages when compared to other document types:

  • It’s open-source
  • Enable you to create and share API documentation
  • Allows you to test APIs

In this article, I explain step-by-step process for creating a Swagger UI document to get a “Hello World” response through an API which is built in Flask REST API framework. I will use Python and YAML files to implement Swagger UI and API with explanation.

As a pre-requisite, you are expected to have a basic understanding on Flask APIs and how they work. If you need to gain a basic understanding on Flask APIs, you can refer to the official .

Steps to Create a Swagger UI Document

We will follow the following steps to build a Swagger UI document for an API function:

  • First, we will create the API using Flask web API framework.
  • Next, we will create a JSON or a YAML file to implement API functionality in SwaggerUI.
  • Finally, we will call the created JSON or YAML file inside the Python program where the API definition is present.

You need to install the following Python packages using pip install to run this example.

$ pip install Flask$ pip install flasgger

If you want to update the module while installing it, you can use pip install -U <module_name> or if you are using Python virtual environments and wish to install a specific version of the module for your project, you can execute pip install <module_name>==<version> for example, pip install Flask==2.0.0

But I would recommend that you should install the latest versions. The following is the import block of our Python script.

from flask import Flask, requestfrom flasgger import Swagger, LazyString, LazyJSONEncoderfrom flasgger import swag_from

Define the Flask app using the Flask method:

app = Flask(__name__)

You need the JSON encoder to create JSON from the API objects for which you can use LazyJSONEncoder class.

app.json_encoder = LazyJSONEncoder

The template and the configuration for the Swagger UI document are defined as dictionary objects as follows:

swagger_template = dict(info = {    'title': LazyString(lambda: 'My first Swagger UI document'),    'version': LazyString(lambda: '0.1'),    'description': LazyString(lambda: 'This document depicts a      sample Swagger UI document and implements Hello World functionality after executing GET.'),    },    host = LazyString(lambda: request.host))swagger_config = {    "headers": [],    "specs": [        {            "endpoint": 'hello_world',            "route": '/hello_world.json',            "rule_filter": lambda rule: True,            "model_filter": lambda tag: True,        }    ],    "static_url_path": "/flasgger_static",    "swagger_ui": True,    "specs_route": "/apidocs/"}

The LazyString functionality of flasgger module is used to set default values for certain parameters during runtime. The parameters of the Swagger UI document such as document title, version, description etc. are defined within the info field. The base URL for the API is specified within the host field. The configuration details of Swagger UI are defined within the swagger_config JSON object.

Finally, the swagger object is defined using the Swagger method imported from flasgger module as follows:

swagger = Swagger(app, template=swagger_template,                               config=swagger_config)

The API function is defined and the route/address of the Flask app is specified using the @app.route decorator. The YAML file for Swagger UI document is also called using the @swag_from decorator by specifying path of YAML file and GET method as arguments (arguments such as POST, PUT, DELETE can also be used as per requirement).

@swag_from("hello_world.yml", methods=['GET'])@app.route("/")def hello_world():    return "Hello World!!!"

NOTE: In this case, the YAML file and the Python file should be in the same directory. If not, the correct file path of the YAML file should be specified within the @swag_from decorator argument.

The following lines should be added inside the hello_world.yml file for implementing the GET response in Swagger UI:-

openapi: 3.0.0tags:  - name: Hello Worldget:

description: None
responses: '200': description: Successful response '400': description: Bad Request '500': description: Internal Server Error

NOTE: If the GET response does not have any parameters to be filled, it is a good practice to specify description as None and define responses in the end.

Finally, the Flask app is run and executed inside the main using the following lines of code:-

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

The code when executed will run on localhost in development mode and the following document is displayed when running

Document obtained after running in browser

As you can see, this document contains the title, version and description of the API as defined in the YAML file. Once the GET response is selected in the Swagger UI document, the document expand as:

Result obtained after selecting GET response from the document

When you click the “Try it out” button, the document displays the “Execute” button as follows:

Result obtained after selecting “Try it out” button

Once the “Execute” option is selected, the Hello World output is displayed as shown below:-

Result after executing GET response by selecting “Execute” option

As seen, the API response is returned within the “Response body” of the GET method. The “Response headers” contain basic information of the response such as length of the response, type of the response, date and time at which the response was received (time will be displayed as per GMT time zone) etc.

Hope you have understood the significance of creating Swagger UI documents for APIs and how to use them as testing tools for the API. I would be happy to acknowledge any questions and doubts which can be posted through the comments.


Experiences in the tech kitchen at Quantrium