Flask-Swagger
Flask-Swagger is a Python library designed to extract Swagger 2.0 specifications from Flask projects. Its latest version is 0.2.14, released in February 2021. The project appears to be in maintenance mode with infrequent updates, and lacks support for newer Python versions (3.9+) and OpenAPI 3.0.
Common errors
-
ModuleNotFoundError: No module named 'flask_swagger'
cause The flask-swagger package is not installed or not available in the current Python environment.fixRun `pip install flask-swagger` to install the package. -
TypeError: object of type 'Response' is not JSON serializable
cause The Flask `swagger` function returns a dictionary, which must be converted to a JSON response using Flask's `jsonify` utility before returning from a view function.fixImport `jsonify` from `flask` and wrap the `swagger` output: `return jsonify(swagger(app))`. -
RuntimeError: No application found. Either work inside a request context or set the 'FLASK_APP' environment variable.
cause The `swagger(app)` function might be called outside of an application context or before the Flask app instance is properly initialized, especially if trying to access application config or routes dynamically.fixEnsure `swagger(app)` is called within the context of a running Flask application, typically inside a view function or after `app` has been fully configured.
Warnings
- deprecated Flask-Swagger is no longer actively maintained and has known compatibility issues with Python versions 3.9 and newer. For modern OpenAPI (3.x) support and active development, consider using `flasgger` or `flask-restx`.
- gotcha This library exclusively supports Swagger 2.0 specifications. It does not provide support for the newer OpenAPI 3.x standards. If your project requires OpenAPI 3.x, an alternative library is necessary.
- breaking In version 0.2.0, a change was introduced where Swagger specifications should reference 'id' instead of 'name' in certain contexts (e.g., for operation IDs). Code written for pre-0.2.0 versions may break.
Install
-
pip install flask-swagger
Imports
- swagger
from flask_swagger import swagger
Quickstart
from flask import Flask, jsonify
from flask_swagger import swagger
app = Flask(__name__)
@app.route('/spec')
def spec():
swag = swagger(app)
swag['info']['title'] = "My Flask API"
swag['info']['version'] = "1.0"
return jsonify(swag)
@app.route('/hello/<name>')
def hello(name):
"""
Hello World Endpoint
This is a test endpoint returning a greeting.
---
parameters:
- name: name
in: path
type: string
required: true
default: World
responses:
200:
description: A greeting message
schema:
type: string
example: Hello, John!
"""
return f"Hello, {name}!"
# To run the app:
# if __name__ == '__main__':
# app.run(debug=True)