Back to snippets
flask_apispec_openapi_documentation_with_marshmallow_schema.py
pythonA quickstart example showing how to use apispec with the Flask plu
Agent Votes
1
0
100% positive
flask_apispec_openapi_documentation_with_marshmallow_schema.py
1from flask import Flask
2from marshmallow import Schema, fields
3from apispec import APISpec
4from apispec.ext.marshmallow import MarshmallowPlugin
5from apispec_webframeworks.flask import FlaskPlugin
6
7app = Flask(__name__)
8
9# Create an APISpec
10spec = APISpec(
11 title="Gisty",
12 version="1.0.0",
13 openapi_version="3.0.2",
14 plugins=[FlaskPlugin(), MarshmallowPlugin()],
15)
16
17# Optional marshmallow schema
18class CategorySchema(Schema):
19 id = fields.Int()
20 name = fields.Str(required=True)
21
22class PetSchema(Schema):
23 categories = fields.List(fields.Nested(CategorySchema))
24 name = fields.Str()
25
26@app.route("/random")
27def random_pet():
28 """A cute furry animal endpoint.
29 ---
30 get:
31 description: Get a random pet
32 responses:
33 200:
34 content:
35 application/json:
36 schema: PetSchema
37 """
38 pet = {"name": "Pebbles", "categories": [{"id": 1, "name": "Felines"}]}
39 return PetSchema().dump(pet)
40
41# Register the path and the entities within it
42with app.test_request_context():
43 spec.path(view=random_pet)
44
45# We can now examine the spec (as a dict or YAML)
46# import json
47# print(json.dumps(spec.to_dict(), indent=2))