Debian Codegraph @

docs/writing_plugins.rst

raw
1 Writing Plugins
2 ===============
3
4 A plugins is a subclass of `apispec.plugin.BasePlugin`.
5
6
7 Helper Methods
8 --------------
9
10 Plugins provide "helper" methods that augment the behavior of `apispec.APISpec` methods.
11
12 There are five types of helper methods:
13
14 * Schema helpers
15 * Parameter helpers
16 * Response helpers
17 * Path helpers
18 * Operation helpers
19
20 Helper functions modify `apispec.APISpec` methods. For example, path helpers modify `apispec.APISpec.path`.
21
22
23 A plugin with a path helper function may look something like this:
24
25 .. code-block:: python
26
27 from apispec import BasePlugin
28 from apispec.yaml_utils import load_operations_from_docstring
29
30
31 class MyPlugin(BasePlugin):
32 def path_helper(self, path, operations, func, **kwargs):
33 """Path helper that parses docstrings for operations. Adds a
34 ``func`` parameter to `apispec.APISpec.path`.
35 """
36 operations.update(load_operations_from_docstring(func.__doc__))
37
38
39 All plugin helpers must accept extra `**kwargs`, allowing custom plugins to define new arguments if required.
40
41 A plugin with an operation helper that adds `deprecated` flag may look like this
42
43 .. code-block:: python
44
45 # deprecated_plugin.py
46
47 from apispec import BasePlugin
48 from apispec.yaml_utils import load_operations_from_docstring
49
50
51 class DeprecatedPlugin(BasePlugin):
52 def operation_helper(self, path, operations, **kwargs):
53 """Operation helper that add `deprecated` flag if in `kwargs`"""
54 if kwargs.pop("deprecated", False) is True:
55 for key, value in operations.items():
56 value["deprecated"] = True
57
58
59 Using this plugin
60
61 .. code-block:: python
62
63 import json
64 from apispec import APISpec
65 from deprecated_plugin import DeprecatedPlugin
66
67 spec = APISpec(
68 title="Gisty",
69 version="1.0.0",
70 openapi_version="3.0.2",
71 plugins=[DeprecatedPlugin()],
72 )
73
74 # path will call operation_helper on operations
75 spec.path(
76 path="/gists/{gist_id}",
77 operations={"get": {"responses": {"200": {"description": "standard response"}}}},
78 deprecated=True,
79 )
80 print(json.dumps(spec.to_dict()["paths"]))
81 # {"/gists/{gist_id}": {"get": {"responses": {"200": {"description": "standard response"}}, "deprecated": true}}}
82
83
84
85 The ``init_spec`` Method
86 ------------------------
87
88 `BasePlugin` has an `init_spec` method that `APISpec` calls on each plugin at initialization with the spec object itself as parameter. It is no-op by default, but a plugin may override it to access and store useful information on the spec object.
89
90 A typical use case is conditional code depending on the OpenAPI version, which is stored as ``openapi_version`` on the `spec` object. See source code for `apispec.ext.marshmallow.MarshmallowPlugin </_modules/apispec/ext/marshmallow.html>`_ for an example.
91
92 Example: Docstring-parsing Plugin
93 ---------------------------------
94
95 Here's a plugin example involving conditional processing depending on the OpenAPI version:
96
97 .. code-block:: python
98
99 # docplugin.py
100
101 from apispec import BasePlugin
102 from apispec.yaml_utils import load_operations_from_docstring
103
104
105 class DocPlugin(BasePlugin):
106 def init_spec(self, spec):
107 super(DocPlugin, self).init_spec(spec)
108 self.openapi_major_version = spec.openapi_version.major
109
110 def operation_helper(self, operations, func, **kwargs):
111 """Operation helper that parses docstrings for operations. Adds a
112 ``func`` parameter to `apispec.APISpec.path`.
113 """
114 doc_operations = load_operations_from_docstring(func.__doc__)
115 # Apply conditional processing
116 if self.openapi_major_version < 3:
117 "...Mutating doc_operations for OpenAPI v2..."
118 else:
119 "...Mutating doc_operations for OpenAPI v3+..."
120 operations.update(doc_operations)
121
122
123 To use the plugin:
124
125 .. code-block:: python
126
127 from apispec import APISpec
128 from docplugin import DocPlugin
129
130 spec = APISpec(
131 title="Gisty", version="1.0.0", openapi_version="3.0.2", plugins=[DocPlugin()]
132 )
133
134
135 def gist_detail(gist_id):
136 """Gist detail view.
137 ---
138 get:
139 responses:
140 200:
141 content:
142 application/json:
143 schema: '#/definitions/Gist'
144 """
145 pass
146
147
148 spec.path(path="/gists/{gist_id}", func=gist_detail)
149 print(dict(spec.to_dict()["paths"]))
150 # {'/gists/{gist_id}': {'get': {'responses': {200: {'content': {'application/json': {'schema': '#/definitions/Gist'}}}}}}}
151
152
153 Next Steps
154 ----------
155
156 To learn more about how to write plugins:
157
158 * Consult the :doc:`Core API docs <api_core>` for `BasePlugin <apispec.BasePlugin>`
159 * View the source for an existing apispec plugin, e.g. `FlaskPlugin <https://github.com/marshmallow-code/apispec-webframeworks/blob/master/src/apispec_webframeworks/flask.py>`_.
160 * Check out some projects using apispec: https://github.com/marshmallow-code/apispec/wiki/Ecosystem