| 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 PackagesFirst, install flask-restx: pip install flask-restx
Alternatively, if you want to use Flasgger: pip install flasgger
2. Setup Flask-RESTx with Swagger UICreate 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 Flasggerpip install flasgger
Modify the Flask Appfrom 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 APIFairypip install apifairy
Modify Your Flask Appfrom 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 FeaturesUsing 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 UsersTo 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! 🚀 |