Automated OpenAPI documentation for a Python Flask API

CK CK 3788 
Created at  
1,126 0 0

Flask is a lightweight and flexible Python web framework that provides essential tools and features for building web applications. It allows developers to define routes, handle HTTP requests, render templates, and manage user sessions, all while offering a microframework approach that promotes simplicity and extensibility through various extensions and libraries. Flask's minimal core makes it easy to learn and integrate with other technologies, making it a popular choice for both small projects and complex web applications.

 

For automated API documentation in Flask, Flasgger offers a good balance of features and ease of use, automatically generating Swagger UI from docstrings and providing some validation. APIFairy is a more lightweight option focused on generating API documentation primarily from Pydantic schemas, offering built-in validation and serialization. While Flask-Swagger-UI provides the Swagger UI interface itself, it requires more manual configuration to generate the underlying OpenAPI specification. Therefore, if you prioritize automatic documentation generation from docstrings and minimal configuration, choose Flasgger. If you're heavily invested in Pydantic for schema definition and want validation and documentation tied together, APIFairy might be a better fit, but you'll write schemas. Flask-Swagger-UI is best used if you want very fine-grained control and prefer generating your OpenAPI spec directly.

 

1. Install Required Packages

First, install flask-restx:

pip install flask-restx

Alternatively, if you want to use Flasgger:

pip install flasgger

2. Setup Flask-RESTx with Swagger UI

Create a Flask API and integrate OpenAPI documentation.

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

app = Flask(__name__)
api = Api(
    app, 
    version="1.0", 
    title="My Flask API",
    description="A simple Flask API with Swagger documentation"
)

# Define API namespace
ns = api.namespace('hello', description="Simple Hello API")

# Define API model for input/output data
hello_model = api.model('Hello', {
    'message': fields.String(description="A simple greeting message"),
})

@ns.route('/')
class HelloWorld(Resource):
    @api.doc(description="Returns a greeting message")
    @api.marshal_with(hello_model)
    def get(self):
        """Returns a simple greeting message"""
        return {"message": "Hello, World!"}

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

API Documentation

  • Swagger UI: Available at http://127.0.0.1:5000/ (by default).
  • OpenAPI JSON Schema: Available at http://127.0.0.1:5000/swagger.json.

3. Using Flasgger (Alternative)

If you prefer Flasgger, you can generate Swagger documentation using decorators.

Install Flasgger

pip install flasgger

Modify the Flask App

from flask import Flask, jsonify
from flasgger import Swagger

app = Flask(__name__)
swagger = Swagger(app)

@app.route('/hello', methods=['GET'])
def hello():
    """
    A simple greeting API
    ---
    responses:
      200:
        description: Returns a greeting message
        schema:
          type: object
          properties:
            message:
              type: string
    """
    return jsonify(message="Hello, World!")

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

API Documentation

  • Swagger UI: Available at http://127.0.0.1:5000/apidocs/.

4. Using APIFairy (For Flask 2.x)

Another modern alternative is APIFairy, which supports OpenAPI and Redoc.

Install APIFairy

pip install apifairy

Modify Your Flask App

from flask import Flask, jsonify
from apifairy import APIFairy

app = Flask(__name__)
apifairy = APIFairy(app)

@app.route('/hello', methods=['GET'])
def hello():
    """
    A simple greeting API
    ---
    responses:
      200:
        content:
          application/json:
            schema:
              type: object
              properties:
                message:
                  type: string
    """
    return jsonify(message="Hello, World!")

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

API Documentation

  • Swagger UI: Available at http://127.0.0.1:5000/docs/swagger/.
  • Redoc: Available at http://127.0.0.1:5000/docs/redoc/.

5. Additional Features

Using Query Parameters in Flask-RESTx

@ns.route('/greet')
class GreetUser(Resource):
    @api.doc(params={'name': 'The name of the user'})
    def get(self):
        """Returns a personalized greeting"""
        from flask import request
        name = request.args.get('name', 'Guest')
        return {"message": f"Hello, {name}!"}

Restrict Swagger Access to Authenticated Users

To protect your Swagger UI, modify the Api instance:

from flask_restx import Api
from flask import Flask
from flask_basicauth import BasicAuth

app = Flask(__name__)
app.config['BASIC_AUTH_USERNAME'] = 'admin'
app.config['BASIC_AUTH_PASSWORD'] = 'secret'

basic_auth = BasicAuth(app)

api = Api(app, security="basicAuth")

@api.route('/protected')
class ProtectedResource(Resource):
    @basic_auth.required
    def get(self):
        return {"message": "You are authenticated!"}

Conclusion

  • Use flask-restx if you want built-in OpenAPI support with Swagger.
  • Use Flasgger for decorator-based Swagger UI integration.
  • Use APIFairy for Flask 2.x with Redoc support.

Each of these methods provides automated OpenAPI documentation with minimal effort! 🚀

Tags APIFairy Automated Open API Documentation Flasgger Flash API Open API Open API Documentation OpenAPI flask-restx Facebook X
Comments 0
Similar posts
  1. Automated API documentation for a Django REST Framework (DRF) project using drf-yasg (Yet Another Swagger Generator)
    1,033
  1. What “GPU Clustering” Really Means (And How to Code for It)
    214
  2. How to Build a Python Chatbot That Writes and Runs Code Using Microsoft AutoGen (With Sample Code)
    244
  3. Beyond Prompt Engineering: Why Loop Engineering is the Future of Autonomous AI
    310
  4. A Python Code to get the Server Instance ID for Remote Management
    366
  5. From Local Python Web to Standalone
    2,056
  6. Demystifying FAISS: Your Guide to ANN(Approximate Nearest Neighbor) Search
    326
  7. TensorRT for LLMs: Speed, Scale, and Why Startups Choose It Over TensorFlow
    466
  8. Python ML Technologies used for the target Segmentation
    381
  9. Managing WHITE_LIST in FastAPI to Improve the Server Security
    354
  10. A common async example
    989
  11. Milvus and LLM Integration - Very Smart Approach!
    304
  12. Automated API Documentation with PyCharm
    896
  13. How to install python 3.9 alongside python 3.8 on CentOS 7?
    719
  14. How to run Python 3.9 on Mac?
    656
  15. Python Quizs
    502
  16. Uploading a file to a Google Drive Folder programmatically with Python
    3,309
  17. Garbage Collection when your system does not have enough memory in your Python App
    1,021
  18. Method to maximize full CPU performance with Python
    325
  19. How do I get the maximum available of thread in python?
    994
  20. Using Queue Algorithm with Redis - RPUSH and LPOP
    774
  21. Use cache concept with Redis : Let's do Redis programming with Python
    539
  22. Installing Python 3.8 in a venv environment on CentOS 7
    465
  23. CUDA versus OpenCL
    584
  24. Simple gRPC server based on Python
    398
  25. Python code to convert PDF file to Excel Spreadsheet
    705
  26. Python script to list files on your Google Drive and download one of them
    941
  27. Coinbase Python API - Basic Example
    464
  28. AWS Lambda Code Example based on Python
    334
  29. Python code using GPU on CentOS with AWS
    1,258
  30. Video Scence Detection with PySceneDetect
    2,339
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    29
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    55
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    49
  4. How do I create animated background for Google Meet?
    22,910
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    271
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    103
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    168
  8. Array of arguments passed to script in PHP
    97
  9. Invalid Auction Storms in Ad Tech
    106
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    207
  11. The Two Clocks of Ad Server Architecture
    77
  12. Frequency Cap Architecture Overview
    526
  13. Collecting Proof-of-Play from 100,000 Screens
    152
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    302
  15. What is RedisVL?
    114
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    246
  17. TPU & GPU Cluster Management Tools
    257
  18. The Concept of Scaffolding in AI Agents
    244
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    596
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    267
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    353
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    206
  23. Machine Learning: Training vs. Ranking
    229
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    202
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    672
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    200
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    232