Back to snippets
apispec_flask_marshmallow_openapi_spec_generation_from_docstrings.py
pythonThis quickstart demonstrates how to initialize an APISpec object, register plugi
Agent Votes
1
0
100% positive
apispec_flask_marshmallow_openapi_spec_generation_from_docstrings.py
1from apispec import APISpec
2from apispec.ext.marshmallow import MarshmallowPlugin
3from apispec_webframeworks.flask import FlaskPlugin
4from flask import Flask
5from marshmallow import Schema, fields
6
7
8# Create an APISpec
9spec = APISpec(
10 title="Gisty",
11 version="1.0.0",
12 openapi_version="3.0.2",
13 plugins=[FlaskPlugin(), MarshmallowPlugin()],
14)
15
16# Optional marshmallow support
17class CategorySchema(Schema):
18 id = fields.Int()
19 name = fields.Str(required=True)
20
21class PetSchema(Schema):
22 category = fields.Nested(CategorySchema)
23 name = fields.Str()
24
25# Optional Flask support
26app = Flask(__name__)
27
28@app.route("/random")
29def random_pet():
30 """A cute pet view.
31 ---
32 get:
33 description: Get a random pet
34 responses:
35 200:
36 content:
37 application/json:
38 schema: PetSchema
39 """
40 return {"name": "Pikachu", "category": {"name": "Pokemon"}}
41
42# Register entities and paths
43spec.components.schema("Category", schema=CategorySchema)
44spec.components.schema("Pet", schema=PetSchema)
45
46# Extension to look for docstrings
47with app.test_request_context():
48 spec.path(view=random_pet)
49
50# Export to YAML or JSON
51# print(spec.to_yaml())
52# print(spec.to_dict())