0
0
FlaskHow-ToBeginner · 4 min read

How to Document API Using Swagger in Flask

To document an API in Flask using Swagger, use the Flask-RESTX extension which integrates Swagger UI automatically. Define your API endpoints with namespaces and models, then Flask-RESTX generates interactive Swagger documentation at a URL like /.
📐

Syntax

Use Flask-RESTX to add Swagger documentation to your Flask API. Key parts include:

  • Api: Wraps your Flask app to enable Swagger UI.
  • Namespace: Groups related endpoints.
  • Model: Defines data structures for requests and responses.
  • @api.route: Decorates endpoint routes.
  • @api.doc and @api.expect: Add descriptions and input validation.
python
from flask import Flask
from flask_restx import Api, Resource, fields

app = Flask(__name__)
api = Api(app, version='1.0', title='Sample API', description='A simple API')

ns = api.namespace('items', description='Item operations')

item_model = api.model('Item', {
    'id': fields.Integer(readonly=True, description='The item unique identifier'),
    'name': fields.String(required=True, description='Item name')
})

@ns.route('/')
class ItemList(Resource):
    @ns.doc('list_items')
    def get(self):
        '''List all items'''
        return []

    @ns.doc('create_item')
    @ns.expect(item_model)
    def post(self):
        '''Create a new item'''
        return {'id': 1, 'name': 'Sample'}, 201

if __name__ == '__main__':
    app.run(debug=True)
💻

Example

This example shows a Flask app with Swagger UI documentation using Flask-RESTX. It defines an items namespace with GET and POST endpoints. The POST endpoint expects a JSON body matching the item_model. Running this app provides interactive API docs at http://localhost:5000/.

python
from flask import Flask
from flask_restx import Api, Resource, fields

app = Flask(__name__)
api = Api(app, version='1.0', title='Item API', description='API to manage items')

ns = api.namespace('items', description='Operations related to items')

item_model = api.model('Item', {
    'id': fields.Integer(readonly=True, description='Unique identifier'),
    'name': fields.String(required=True, description='Name of the item')
})

items = []

@ns.route('/')
class ItemList(Resource):
    @ns.doc('list_items')
    def get(self):
        '''Returns list of items'''
        return items

    @ns.doc('create_item')
    @ns.expect(item_model)
    def post(self):
        '''Creates a new item'''
        new_item = api.payload
        new_item['id'] = len(items) + 1
        items.append(new_item)
        return new_item, 201

if __name__ == '__main__':
    app.run(debug=True)
Output
Running the app and visiting http://localhost:5000/ shows Swagger UI with documented endpoints for GET and POST /items.
⚠️

Common Pitfalls

Common mistakes when documenting Flask APIs with Swagger include:

  • Not installing or importing flask-restx properly.
  • Forgetting to wrap the Flask app with Api(app).
  • Not defining models with api.model, causing missing schema in docs.
  • Using @api.expect without a model, which disables input validation.
  • Not running the app in debug mode during development to see errors clearly.
python
from flask import Flask
from flask_restx import Api, Resource

app = Flask(__name__)
# Missing Api wrapper causes no Swagger UI
# api = Api(app)  # This line is required

# @api.route('/')
# class HelloWorld(Resource):
#     def get(self):
#         return {'hello': 'world'}

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

# Correct way:
# api = Api(app)
# @api.route('/')
# class HelloWorld(Resource):
#     def get(self):
#         return {'hello': 'world'}
📊

Quick Reference

Summary tips for documenting Flask APIs with Swagger:

  • Install flask-restx via pip install flask-restx.
  • Wrap your Flask app with Api(app) to enable Swagger UI.
  • Use Namespace to organize endpoints.
  • Define data models with api.model for clear request/response schemas.
  • Decorate routes with @api.route and use @api.expect for input validation.
  • Run your app and visit http://localhost:5000/ to see interactive Swagger docs.

Key Takeaways

Use Flask-RESTX to easily add Swagger UI documentation to your Flask API.
Define models with api.model to describe your data structures clearly.
Wrap your Flask app with Api(app) to enable Swagger integration.
Use namespaces and decorators to organize and document endpoints.
Run your app and open the root URL to access interactive Swagger docs.