This is a simple guide on how to add SwaggerUI to your plain flask API project without using any additional libraries.
Go to this link to download swagger UI from GitHub and extract it. We are basically interested in the dist directory in this archive.
- In your project directory create 2 directories
templates
andstatic
- Move
index.html
fromdist
totemplates
directory and rename it toswaggerui.html
- Inside
static
directory, create 3 more directories,css
,img
andjs
- Move
.js
files fromdist
tostatic/js
- Move
.css
files fromdist
tostatic/css
- Move
.png
files fromdist
tostatic/img
Your project directory should now look like this
.
├── static
│ ├── css
│ │ └── swagger-ui.css
│ ├── img
│ │ ├── favicon-16x16.png
│ │ └── favicon-32x32.png
│ └── js
│ ├── swagger-ui-bundle.js
│ ├── swagger-ui-standalone-preset.js
│ └── swagger-ui.js
└── templates
├── swaggerui.html
7 <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/swagger-ui.css') }}">
8 <link rel="icon" type="image/png" href="{{ url_for('static', filename='img/favicon-32x32.png') }}" sizes="32x32"/>
9 <link rel="icon" type="image/png" href="{{ url_for('static', filename='img/favicon-16x16.png') }}" sizes="16x16"/>
36 <script src="{{ url_for('static', filename='js/swagger-ui-bundle.js') }}"> </script>
37 <script src="{{ url_for('static', filename='js/swagger-ui-standalone-preset.js') }}"> </script>
- Go to swagger editor and write your API spec in YAML Here is a Sample API spec:
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: hola
- Go to
File
menu in Swagger editor and click onConvert and save as JSON
- Place the downloaded
openapi.json
file in your projects'static
directory - Update the reference for the source json file in
swaggerui.html
file to refer to the spec file in static directory
42 url: "{{ url_for('static', filename='openapi.json') }}",
- Create
hello_api.py
in your project directory with 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_dict[lang])
app.run(use_reloader=True, debug=False)
- Run the app with command:
python3 hello_api.py
from your project directory - Your SwaggerUI documentation shoule be accessible on http://localhost:5000/api/docs