Debian Codegraph @

examples/apispec_example.py

raw symbols SCIP
1 """
2 Example using marshmallow APISpec as base template for Flasgger specs
3 """
4 # coding: utf-8
5 from flask import Flask, jsonify
6
7 from flasgger import APISpec, Schema, Swagger, fields
8 from apispec.ext.marshmallow import MarshmallowPlugin
9 from apispec_webframeworks.flask import FlaskPlugin
10
11 # Create an APISpec
12 spec = APISpec(
13 title='Flasger Petstore',
14 version='1.0.10',
15 openapi_version='2.0',
16 plugins=[
17 FlaskPlugin(),
18 MarshmallowPlugin(),
19 ],
20 )
21
22 app = Flask(__name__)
23
24
25 # Optional marshmallow support
26 class CategorySchema(Schema):
27 id = fields.Int()
28 name = fields.Str(required=True)
29
30
31 class PetSchema(Schema):
32 category = fields.Nested(CategorySchema, many=True)
33 name = fields.Str()
34
35
36 @app.route('/random')
37 def random_pet():
38 """
39 A cute furry animal endpoint.
40 Get a random pet
41 ---
42 description: Get a random pet
43 responses:
44 200:
45 description: A pet to be returned
46 schema:
47 $ref: '#/definitions/Pet'
48 """
49 pet = {'category': [{'id': 1, 'name': 'rodent'}], 'name': 'Mickey'}
50 return jsonify(PetSchema().dump(pet).data)
51
52 @app.route("/add", methods=["POST"])
53 def create_pet(body: PetSchema) :
54 """Create a cute furry animal endpoint.
55 ---
56 post:
57 description: Create a random pet
58 parameters:
59 - in: body
60 name: body
61 required: True
62 schema:
63 $ref: '#/definitions/Pet'
64 security:
65 - ApiKeyAuth: []
66 responses:
67 201:
68 description: If pet is created
69 content:
70 application/json:
71 status: string
72 """
73 return jsonify(
74 {"status": "New user created"}
75 ), 201
76
77
78 template = spec.to_flasgger(
79 app,
80 definitions=[CategorySchema, PetSchema],
81 paths=[random_pet, create_pet]
82 )
83
84 """
85 optionally if using apispec.APISpec from original module
86 you can do:
87
88 from flasgger.utils import apispec_to_template
89 template = apispec_to_template(
90 app=app,
91 spec=spec,
92 definitions=[CategorySchema, PetSchema],
93 paths=[random_pet, create_pet]
94 )
95
96 """
97
98 # start Flasgger using a template from apispec
99 swag = Swagger(app, template=template)
100
101
102 if __name__ == '__main__':
103 app.run(debug=True)