| 1 |
Using Plugins |
| 2 |
============= |
| 3 |
|
| 4 |
What is an apispec "plugin"? |
| 5 |
---------------------------- |
| 6 |
|
| 7 |
An apispec *plugin* is an object that provides helper methods for generating OpenAPI entities from objects in your application. |
| 8 |
|
| 9 |
A plugin may modify the behavior of `APISpec <apispec.APISpec>` methods so that they can take your application's objects as input. |
| 10 |
|
| 11 |
Enabling Plugins |
| 12 |
---------------- |
| 13 |
|
| 14 |
To enable a plugin, pass an instance to the constructor of `APISpec <apispec.APISpec>`. |
| 15 |
|
| 16 |
.. code-block:: python |
| 17 |
:emphasize-lines: 9 |
| 18 |
|
| 19 |
from apispec import APISpec |
| 20 |
from apispec.ext.marshmallow import MarshmallowPlugin |
| 21 |
|
| 22 |
spec = APISpec( |
| 23 |
title="Gisty", |
| 24 |
version="1.0.0", |
| 25 |
openapi_version="3.0.2", |
| 26 |
info=dict(description="A minimal gist API"), |
| 27 |
plugins=[MarshmallowPlugin()], |
| 28 |
) |
| 29 |
|
| 30 |
|
| 31 |
Example: Flask and Marshmallow Plugins |
| 32 |
-------------------------------------- |
| 33 |
|
| 34 |
The bundled marshmallow plugin (`apispec.ext.marshmallow.MarshmallowPlugin`) |
| 35 |
provides helpers for generating OpenAPI schema and parameter objects from `marshmallow <https://marshmallow.readthedocs.io/en/latest/>`_ schemas and fields. |
| 36 |
|
| 37 |
The `apispec-webframeworks <https://github.com/marshmallow-code/apispec-webframeworks>`_ |
| 38 |
package includes a Flask plugin with helpers for generating path objects from view functions. |
| 39 |
|
| 40 |
Let's recreate the spec from the :doc:`Quickstart guide <quickstart>` using these two plugins. |
| 41 |
|
| 42 |
First, ensure that ``apispec-webframeworks`` is installed: :: |
| 43 |
|
| 44 |
$ pip install apispec-webframeworks |
| 45 |
|
| 46 |
Also, ensure that a compatible ``marshmallow`` version is used: :: |
| 47 |
|
| 48 |
$ pip install -U apispec[marshmallow] |
| 49 |
|
| 50 |
We can now use the marshmallow and Flask plugins. |
| 51 |
|
| 52 |
.. code-block:: python |
| 53 |
|
| 54 |
from apispec import APISpec |
| 55 |
from apispec.ext.marshmallow import MarshmallowPlugin |
| 56 |
from apispec_webframeworks.flask import FlaskPlugin |
| 57 |
|
| 58 |
spec = APISpec( |
| 59 |
title="Gisty", |
| 60 |
version="1.0.0", |
| 61 |
openapi_version="3.0.2", |
| 62 |
info=dict(description="A minimal gist API"), |
| 63 |
plugins=[FlaskPlugin(), MarshmallowPlugin()], |
| 64 |
) |
| 65 |
|
| 66 |
|
| 67 |
Our application will have a marshmallow `Schema <marshmallow.Schema>` for gists. |
| 68 |
|
| 69 |
.. code-block:: python |
| 70 |
|
| 71 |
from marshmallow import Schema, fields |
| 72 |
|
| 73 |
|
| 74 |
class GistParameter(Schema): |
| 75 |
gist_id = fields.Int() |
| 76 |
|
| 77 |
|
| 78 |
class GistSchema(Schema): |
| 79 |
id = fields.Int() |
| 80 |
content = fields.Str() |
| 81 |
|
| 82 |
|
| 83 |
The marshmallow plugin allows us to pass this `Schema` to |
| 84 |
`spec.components.schema <apispec.core.Components.schema>`. |
| 85 |
|
| 86 |
|
| 87 |
.. code-block:: python |
| 88 |
|
| 89 |
spec.components.schema("Gist", schema=GistSchema) |
| 90 |
|
| 91 |
The schema is now added to the spec. |
| 92 |
|
| 93 |
.. code-block:: python |
| 94 |
|
| 95 |
from pprint import pprint |
| 96 |
|
| 97 |
pprint(spec.to_dict()) |
| 98 |
# {'components': {'parameters': {}, 'responses': {}, 'schemas': {}}, |
| 99 |
# 'info': {'description': 'A minimal gist API', |
| 100 |
# 'title': 'Gisty', |
| 101 |
# 'version': '1.0.0'}, |
| 102 |
# 'openapi': '3.0.2', |
| 103 |
# 'paths': {}, |
| 104 |
# 'tags': []} |
| 105 |
|
| 106 |
Our application will have a Flask route for the gist detail endpoint. |
| 107 |
|
| 108 |
We'll add some YAML in the docstring to add response information. |
| 109 |
|
| 110 |
.. code-block:: python |
| 111 |
|
| 112 |
from flask import Flask |
| 113 |
|
| 114 |
app = Flask(__name__) |
| 115 |
|
| 116 |
|
| 117 |
# NOTE: Plugins may inspect docstrings to gather more information for the spec |
| 118 |
@app.route("/gists/<gist_id>") |
| 119 |
def gist_detail(gist_id): |
| 120 |
"""Gist detail view. |
| 121 |
--- |
| 122 |
get: |
| 123 |
parameters: |
| 124 |
- in: path |
| 125 |
schema: GistParameter |
| 126 |
responses: |
| 127 |
200: |
| 128 |
content: |
| 129 |
application/json: |
| 130 |
schema: GistSchema |
| 131 |
""" |
| 132 |
return "details about gist {}".format(gist_id) |
| 133 |
|
| 134 |
The Flask plugin allows us to pass this view to `spec.path <apispec.APISpec.path>`. |
| 135 |
|
| 136 |
|
| 137 |
.. code-block:: python |
| 138 |
|
| 139 |
# Since path inspects the view and its route, |
| 140 |
# we need to be in a Flask request context |
| 141 |
with app.test_request_context(): |
| 142 |
spec.path(view=gist_detail) |
| 143 |
|
| 144 |
|
| 145 |
Our OpenAPI spec now looks like this: |
| 146 |
|
| 147 |
.. code-block:: python |
| 148 |
|
| 149 |
pprint(spec.to_dict()) |
| 150 |
# {'components': {'parameters': {}, |
| 151 |
# 'responses': {}, |
| 152 |
# 'schemas': {'Gist': {'properties': {'content': {'type': 'string'}, |
| 153 |
# 'id': {'format': 'int32', |
| 154 |
# 'type': 'integer'}}, |
| 155 |
# 'type': 'object'}}}, |
| 156 |
# 'info': {'description': 'A minimal gist API', |
| 157 |
# 'title': 'Gisty', |
| 158 |
# 'version': '1.0.0'}, |
| 159 |
# 'openapi': '3.0.2', |
| 160 |
# 'paths': {'/gists/{gist_id}': {'get': {'parameters': [{'in': 'path', |
| 161 |
# 'name': 'gist_id', |
| 162 |
# 'required': True, |
| 163 |
# 'schema': {'format': 'int32', |
| 164 |
# 'type': 'integer'}}], |
| 165 |
# 'responses': {200: {'content': {'application/json': {'schema': {'$ref': '#/components/schemas/Gist'}}}}}}}}, |
| 166 |
# 'tags': []} |
| 167 |
|
| 168 |
If your API uses `method-based dispatching <http://flask.pocoo.org/docs/0.12/views/#method-based-dispatching>`_, the process is similar. Note that the method no longer needs to be included in the docstring. |
| 169 |
|
| 170 |
.. code-block:: python |
| 171 |
|
| 172 |
from flask.views import MethodView |
| 173 |
|
| 174 |
|
| 175 |
class GistApi(MethodView): |
| 176 |
def get(self): |
| 177 |
"""Gist view |
| 178 |
--- |
| 179 |
description: Get a gist |
| 180 |
responses: |
| 181 |
200: |
| 182 |
content: |
| 183 |
application/json: |
| 184 |
schema: GistSchema |
| 185 |
""" |
| 186 |
pass |
| 187 |
|
| 188 |
def post(self): |
| 189 |
pass |
| 190 |
|
| 191 |
|
| 192 |
method_view = GistApi.as_view("gist") |
| 193 |
app.add_url_rule("/gist", view_func=method_view) |
| 194 |
with app.test_request_context(): |
| 195 |
spec.path(view=method_view) |
| 196 |
pprint(dict(spec.to_dict()["paths"]["/gist"])) |
| 197 |
# {'get': {'description': 'get a gist', |
| 198 |
# 'responses': {200: {'content': {'application/json': {'schema': {'$ref': '#/components/schemas/Gist'}}}}}}, |
| 199 |
# 'post': {}} |
| 200 |
|
| 201 |
|
| 202 |
Marshmallow Plugin |
| 203 |
------------------ |
| 204 |
|
| 205 |
.. _marshmallow_nested_schemas: |
| 206 |
|
| 207 |
Nested Schemas |
| 208 |
************** |
| 209 |
|
| 210 |
By default, Marshmallow `Nested` fields are represented by a `JSON Reference object |
| 211 |
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#referenceObject>`_. |
| 212 |
If the schema has been added to the spec via `spec.components.schema <apispec.core.Components.schema>`, |
| 213 |
the user-supplied name will be used in the reference. Otherwise apispec will |
| 214 |
add the nested schema to the spec using an automatically resolved name for the |
| 215 |
nested schema. The default `resolver <apispec.ext.marshmallow.resolver>` |
| 216 |
function will resolve a name based on the schema's class `__name__`, dropping a |
| 217 |
trailing "Schema" so that `class PetSchema(Schema)` resolves to "Pet". |
| 218 |
|
| 219 |
To change the behavior of the name resolution simply pass a |
| 220 |
function accepting a `Schema` class, `Schema` instance or a string that resolves |
| 221 |
to a `Schema` class and returning a string to the plugin's |
| 222 |
constructor. To easily work with these argument types the marshmallow plugin provides |
| 223 |
`resolve_schema_cls <apispec.ext.marshmallow.common.resolve_schema_cls>` |
| 224 |
and `resolve_schema_instance <apispec.ext.marshmallow.common.resolve_schema_instance>` |
| 225 |
functions. If the `schema_name_resolver` function returns a value that |
| 226 |
evaluates to `False` in a boolean context the nested schema will not be added to |
| 227 |
the spec and instead defined in-line. |
| 228 |
|
| 229 |
.. note:: |
| 230 |
A `schema_name_resolver` function must return a string name when |
| 231 |
working with circular-referencing schemas in order to avoid infinite |
| 232 |
recursion. |
| 233 |
|
| 234 |
Schema Modifiers |
| 235 |
**************** |
| 236 |
|
| 237 |
apispec will respect schema modifiers such as ``exclude`` and ``partial`` in the generated schema definition. If a schema is initialized with modifiers, apispec will treat each combination of modifiers as a unique schema definition. |
| 238 |
|
| 239 |
Custom DateTime formats |
| 240 |
*********************** |
| 241 |
|
| 242 |
apispec supports all four basic formats of `marshmallow.fields.DateTime`: ``"rfc"`` (for RFC822), ``"iso"`` (for ISO8601), |
| 243 |
``"timestamp"``, ``"timestamp_ms"`` (for a POSIX timestamp). |
| 244 |
|
| 245 |
If you are using a custom DateTime format you should pass a regex string to the ``pattern`` parameter in your field ``metadata`` so that it is included as documentation. |
| 246 |
|
| 247 |
.. code-block:: python |
| 248 |
|
| 249 |
class SchemaWithCustomDate(Schema): |
| 250 |
french_date = ma.DateTime( |
| 251 |
format="%d-%m%Y %H:%M:%S", |
| 252 |
metadata={"pattern": r"^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}$"}, |
| 253 |
) |
| 254 |
|
| 255 |
Custom Fields |
| 256 |
************* |
| 257 |
|
| 258 |
apispec maps standard marshmallow fields to OpenAPI types and formats. If your |
| 259 |
custom field subclasses a standard marshmallow `Field` class then it will |
| 260 |
inherit the default mapping. If you want to override the OpenAPI type and format |
| 261 |
for custom fields, use the |
| 262 |
`map_to_openapi_type <apispec.ext.marshmallow.MarshmallowPlugin.map_to_openapi_type>` |
| 263 |
method. It can be invoked with either a pair of strings providing the |
| 264 |
OpenAPI type and format, or a marshmallow `Field` that has the desired target mapping. |
| 265 |
|
| 266 |
.. code-block:: python |
| 267 |
|
| 268 |
from apispec import APISpec |
| 269 |
from apispec.ext.marshmallow import MarshmallowPlugin |
| 270 |
from marshmallow.fields import Integer, Field |
| 271 |
|
| 272 |
ma_plugin = MarshmallowPlugin() |
| 273 |
|
| 274 |
spec = APISpec( |
| 275 |
title="Demo", version="0.1", openapi_version="3.0.0", plugins=(ma_plugin,) |
| 276 |
) |
| 277 |
|
| 278 |
|
| 279 |
# Inherits Integer mapping of ('integer', None) |
| 280 |
class CustomInteger(Integer): |
| 281 |
pass |
| 282 |
|
| 283 |
|
| 284 |
# Override Integer mapping |
| 285 |
class Int32(Integer): |
| 286 |
pass |
| 287 |
|
| 288 |
|
| 289 |
ma_plugin.map_to_openapi_type(Int32, "string", "int32") |
| 290 |
|
| 291 |
|
| 292 |
# Map to ('integer', None) like Integer |
| 293 |
class IntegerLike(Field): |
| 294 |
pass |
| 295 |
|
| 296 |
|
| 297 |
ma_plugin.map_to_openapi_type(IntegerLike, Integer) |
| 298 |
|
| 299 |
In situations where greater control of the properties generated for a custom field |
| 300 |
is desired, users may add custom logic to the conversion of fields to OpenAPI properties |
| 301 |
through the use of the `add_attribute_function |
| 302 |
<apispec.ext.marshmallow.field_converter.FieldConverterMixin.add_attribute_function>` |
| 303 |
method. Continuing from the example above: |
| 304 |
|
| 305 |
.. code-block:: python |
| 306 |
|
| 307 |
def my_custom_field2properties(self, field, **kwargs): |
| 308 |
"""Add an OpenAPI extension flag to MyCustomField instances""" |
| 309 |
ret = {} |
| 310 |
if isinstance(field, MyCustomField): |
| 311 |
if self.openapi_version.major > 2: |
| 312 |
ret["x-customString"] = True |
| 313 |
return ret |
| 314 |
|
| 315 |
|
| 316 |
ma_plugin.converter.add_attribute_function(my_custom_field2properties) |
| 317 |
|
| 318 |
The function passed to `add_attribute_function` will be bound to the converter. |
| 319 |
It must accept the converter instance as first positional argument. |
| 320 |
|
| 321 |
In some rare cases, typically with container fields such as fields derived from |
| 322 |
:class:`List <marshmallow.fields.List>`, documenting the parameters using this |
| 323 |
field require some more customization. |
| 324 |
This can be achieved using the `add_parameter_attribute_function |
| 325 |
<apispec.ext.marshmallow.openapi.OpenAPIConverter.add_parameter_attribute_function>` |
| 326 |
method. |
| 327 |
|
| 328 |
For instance, when documenting webargs's |
| 329 |
:class:`DelimitedList <webargs.fields.DelimitedList>` field, one may register |
| 330 |
this function: |
| 331 |
|
| 332 |
.. code-block:: python |
| 333 |
|
| 334 |
def delimited_list2param(self, field, **kwargs): |
| 335 |
ret: dict = {} |
| 336 |
if isinstance(field, DelimitedList): |
| 337 |
if self.openapi_version.major < 3: |
| 338 |
ret["collectionFormat"] = "csv" |
| 339 |
else: |
| 340 |
ret["explode"] = False |
| 341 |
ret["style"] = "form" |
| 342 |
return ret |
| 343 |
|
| 344 |
|
| 345 |
ma_plugin.converter.add_parameter_attribute_function(delimited_list2param) |
| 346 |
|
| 347 |
Enum Fields |
| 348 |
*********** |
| 349 |
|
| 350 |
When using `marshmallow.fields.Enum` fields to (de)serialize `enum.Enum` values, we recommend passing a marshmallow field to ``by_value``. |
| 351 |
This ensures the correct ``type`` property is included in the generated OAI spec. |
| 352 |
|
| 353 |
|
| 354 |
.. code-block:: python |
| 355 |
:emphasize-lines: 23,42 |
| 356 |
|
| 357 |
from enum import Enum |
| 358 |
from apispec import APISpec |
| 359 |
|
| 360 |
from apispec.ext.marshmallow import MarshmallowPlugin |
| 361 |
from marshmallow import Schema, fields |
| 362 |
|
| 363 |
spec = APISpec( |
| 364 |
title="Gisty", |
| 365 |
version="1.0.0", |
| 366 |
openapi_version="3.0.2", |
| 367 |
info=dict(description="A minimal gist API"), |
| 368 |
plugins=[MarshmallowPlugin()], |
| 369 |
) |
| 370 |
|
| 371 |
|
| 372 |
class GistVisibility(Enum): |
| 373 |
PRIVATE = "private" |
| 374 |
PUBLIC = "public" |
| 375 |
|
| 376 |
|
| 377 |
class GistSchema(Schema): |
| 378 |
id = fields.Int() |
| 379 |
visibility = fields.Enum(GistVisibility, by_value=fields.String()) |
| 380 |
|
| 381 |
|
| 382 |
spec.components.schema("Gist", schema=GistSchema) |
| 383 |
print(spec.to_yaml()) |
| 384 |
# info: |
| 385 |
# description: A minimal gist API |
| 386 |
# title: Gisty |
| 387 |
# version: 1.0.0 |
| 388 |
# paths: {} |
| 389 |
# openapi: 3.0.2 |
| 390 |
# components: |
| 391 |
# schemas: |
| 392 |
# Gist: |
| 393 |
# type: object |
| 394 |
# properties: |
| 395 |
# id: |
| 396 |
# type: integer |
| 397 |
# visibility: |
| 398 |
# type: string |
| 399 |
# enum: |
| 400 |
# - private |
| 401 |
# - public |
| 402 |
|
| 403 |
|
| 404 |
Next Steps |
| 405 |
---------- |
| 406 |
|
| 407 |
You now know how to use plugins. The next section will show you how to write plugins: :doc:`Writing Plugins <writing_plugins>`. |