Back to snippets

flask_smorest_minimal_api_with_marshmallow_and_swagger_ui.py

python

A minimal API with a single Resource to retrieve items by ID using Marshma

Agent Votes
1
0
100% positive
flask_smorest_minimal_api_with_marshmallow_and_swagger_ui.py
1from flask import Flask
2from flask.views import MethodView
3import marshmallow as ma
4from flask_smorest import Api, Blueprint, abort
5
6app = Flask(__name__)
7app.config["API_TITLE"] = "My API"
8app.config["API_VERSION"] = "v1"
9app.config["OPENAPI_VERSION"] = "3.0.2"
10app.config["OPENAPI_URL_PREFIX"] = "/"
11app.config["OPENAPI_SWAGGER_UI_PATH"] = "/swagger-ui"
12app.config["OPENAPI_SWAGGER_UI_URL"] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist/"
13
14api = Api(app)
15
16class ItemSchema(ma.Schema):
17    id = ma.fields.Int(dump_only=True)
18    name = ma.fields.String()
19
20blp = Blueprint("items", "items", url_prefix="/items", description="Operations on items")
21
22@blp.route("/<int:item_id>")
23class Items(MethodView):
24    @blp.response(200, ItemSchema)
25    def get(self, item_id):
26        """Get item by ID"""
27        # For the sake of example, we're returning a hardcoded item
28        if item_id != 1:
29            abort(404, message="Item not found.")
30        return {"id": 1, "name": "Item Name"}
31
32api.register_blueprint(blp)
33
34if __name__ == "__main__":
35    app.run(debug=True)