How to Enable Swagger? #5995
|
How can I add Swagger (OpenAPI) to a Flask API for testing purposes to ensure my endpoints are working correctly and keep the documentation in sync with the routes? |
Replies: 2 comments
|
You'd need to use some extension for it. Flask does not have anything related to it built-in. |
|
Flask does not have built-in Swagger like FastAPI does, but there are a couple of solid options: option 1: flask-smorest (my recommendation) this is the cleanest approach — it auto-generates OpenAPI docs from your marshmallow schemas: pip install flask-smorestfrom flask import Flask
from flask_smorest import Api, Blueprint, abort
from marshmallow import Schema, fields
app = Flask(__name__)
app.config["API_TITLE"] = "My API"
app.config["API_VERSION"] = "v1"
app.config["OPENAPI_VERSION"] = "3.0.2"
app.config["OPENAPI_URL_PREFIX"] = "/"
app.config["OPENAPI_SWAGGER_UI_PATH"] = "/swagger"
app.config["OPENAPI_SWAGGER_UI_URL"] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist/"
api = Api(app)
class ItemSchema(Schema):
id = fields.Int(dump_only=True)
name = fields.Str(required=True)
blp = Blueprint("items", __name__, url_prefix="/items")
@blp.route("/")
@blp.response(200, ItemSchema(many=True))
def get_items():
return [{"id": 1, "name": "thing"}]
api.register_blueprint(blp)now visit option 2: flask-restx if you want something closer to the Django REST framework experience: it gives you swagger at option 3: if you just want quick testing without changing your code just serve your Flask app and use a standalone Swagger UI pointed at a manually written honestly if you are starting fresh and want built-in Swagger, FastAPI is the way to go — it is literally free with zero config. but flask-smorest gets you 90% there with Flask. |
Flask does not have built-in Swagger like FastAPI does, but there are a couple of solid options:
option 1: flask-smorest (my recommendation)
this is the cleanest approach — it auto-generates OpenAPI docs from your marshmallow schemas: