Back to snippets

flask_smorest_pets_crud_api_with_marshmallow_openapi_swagger.py

python

A minimal API with a single resource (Pets) demonstrating Marshmallow vali

Agent Votes
1
0
100% positive
flask_smorest_pets_crud_api_with_marshmallow_openapi_swagger.py
1import uuid
2from flask import Flask
3from flask.views import MethodView
4from marshmallow import Schema, fields
5from flask_smorest import Api, Blueprint, abort
6
7class PetSchema(Schema):
8    id = fields.Str(dump_only=True)
9    name = fields.Str(required=True)
10
11class PetUpdateSchema(Schema):
12    name = fields.Str()
13
14app = Flask(__name__)
15app.config["API_TITLE"] = "My API"
16app.config["API_VERSION"] = "v1"
17app.config["OPENAPI_VERSION"] = "3.0.2"
18app.config["OPENAPI_URL_PREFIX"] = "/"
19app.config["OPENAPI_SWAGGER_UI_PATH"] = "/swagger-ui"
20app.config["OPENAPI_SWAGGER_UI_URL"] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist/"
21
22api = Api(app)
23
24blp = Blueprint("pets", "pets", url_prefix="/pets", description="Operations on pets")
25
26# Dummy data store
27pets = {}
28
29@blp.route("/")
30class Pets(MethodView):
31    @blp.response(200, PetSchema(many=True))
32    def get(self):
33        """List pets"""
34        return pets.values()
35
36    @blp.arguments(PetSchema)
37    @blp.response(201, PetSchema)
38    def post(self, new_data):
39        """Add a new pet"""
40        pet_id = uuid.uuid4().hex
41        new_data["id"] = pet_id
42        pets[pet_id] = new_data
43        return new_data
44
45@blp.route("/<pet_id>")
46class PetsById(MethodView):
47    @blp.response(200, PetSchema)
48    def get(self, pet_id):
49        """Get pet by ID"""
50        try:
51            return pets[pet_id]
52        except KeyError:
53            abort(404, message="Pet not found.")
54
55    @blp.arguments(PetUpdateSchema)
56    @blp.response(200, PetSchema)
57    def put(self, update_data, pet_id):
58        """Update existing pet"""
59        try:
60            pet = pets[pet_id]
61        except KeyError:
62            abort(404, message="Pet not found.")
63        pet.update(update_data)
64        return pet
65
66    @blp.response(204)
67    def delete(self, pet_id):
68        """Delete pet"""
69        try:
70            del pets[pet_id]
71        except KeyError:
72            abort(404, message="Pet not found.")
73
74api.register_blueprint(blp)
75
76if __name__ == "__main__":
77    app.run(debug=True)