Debian Codegraph @

docs/special_topics.rst

raw
1 Special Topics
2 ==============
3
4 Solutions to specific problems are documented here.
5
6
7 Adding Additional Fields To Schema Objects
8 ------------------------------------------
9
10 To add additional fields (e.g. ``"discriminator"``) to Schema objects generated from `spec.components.schema <apispec.core.Components.schema>` , pass them
11 to the ``component`` parameter. If your'e using ``MarshmallowPlugin``, the ``component`` properties will get merged with the autogenerated properties.
12
13 .. code-block:: python
14
15 properties = {
16 "id": {"type": "integer", "format": "int64"},
17 "name": {"type": "string", "example": "doggie"},
18 }
19
20 spec.components.schema("Pet", component={"discriminator": "petType"}, schema=PetSchema)
21
22
23 .. note::
24 Be careful about the input that you pass to ``component``. ``apispec`` will not guarantee that the passed fields are valid against the OpenAPI spec.
25
26 Rendering to YAML or JSON
27 -------------------------
28
29 YAML
30 ++++
31
32 .. code-block:: python
33
34 spec.to_yaml()
35
36
37 .. note::
38 `to_yaml <apispec.APISpec.to_yaml>` requires `PyYAML` to be installed. You can install
39 apispec with YAML support using: ::
40
41 pip install 'apispec[yaml]'
42
43
44 JSON
45 ++++
46
47 .. code-block:: python
48
49 import json
50
51 json.dumps(spec.to_dict())
52
53 Documenting Top-level Components
54 --------------------------------
55
56 The ``APISpec`` object contains helpers to add top-level components:
57
58 .. list-table::
59 :header-rows: 1
60
61 * - Component type
62 - Helper method
63 - OpenAPI version
64 * - Schema (f.k.a. "definition" in OAS v2)
65 - `spec.components.schema <apispec.core.Components.schema>`
66 - 2, 3
67 * - Parameter
68 - `spec.components.parameter <apispec.core.Components.parameter>`
69 - 2, 3
70 * - Response
71 - `spec.components.response <apispec.core.Components.response>`
72 - 2, 3
73 * - Header
74 - `spec.components.response <apispec.core.Components.header>`
75 - 3
76 * - Example
77 - `spec.components.response <apispec.core.Components.example>`
78 - 3
79 * - Security scheme
80 - `spec.components.response <apispec.core.Components.security_scheme>`
81 - 2, 3
82
83 Most component registration methods provide a ``lazy`` keyword argument,
84 allowing to define a component but only publish it in the generated
85 documentation if it is actually referenced.
86
87 To add other top-level objects, pass them to the ``APISpec`` as keyword arguments.
88
89 Here is an example that includes a `Server Object <https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#serverObject>`_.
90
91 .. code-block:: python
92
93 import yaml
94 from apispec import APISpec
95 from apispec.ext.marshmallow import MarshmallowPlugin
96
97 OPENAPI_SPEC = """
98 openapi: 3.0.2
99 info:
100 description: Server API document
101 title: Server API
102 version: 1.0.0
103 servers:
104 - url: http://localhost:{port}/
105 description: The development API server
106 variables:
107 port:
108 enum:
109 - '3000'
110 - '8888'
111 default: '3000'
112 """
113
114 settings = yaml.safe_load(OPENAPI_SPEC)
115 # retrieve title, version, and openapi version
116 title = settings["info"].pop("title")
117 spec_version = settings["info"].pop("version")
118 openapi_version = settings.pop("openapi")
119
120 spec = APISpec(
121 title=title,
122 version=spec_version,
123 openapi_version=openapi_version,
124 plugins=(MarshmallowPlugin(),),
125 **settings
126 )
127
128
129 Documenting Security Schemes
130 ----------------------------
131
132 Use `spec.components.security_scheme <apispec.core.Components.security_scheme>`
133 to document `Security Scheme Objects <https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#securitySchemeObject>`_.
134
135 .. code-block:: python
136
137 from pprint import pprint
138 from apispec import APISpec
139
140 spec = APISpec(title="Swagger Petstore", version="1.0.0", openapi_version="3.0.2")
141
142 api_key_scheme = {"type": "apiKey", "in": "header", "name": "X-API-Key"}
143 jwt_scheme = {"type": "http", "scheme": "bearer", "bearerFormat": "JWT"}
144
145 spec.components.security_scheme("api_key", api_key_scheme)
146 spec.components.security_scheme("jwt", jwt_scheme)
147
148 pprint(spec.to_dict()["components"]["securitySchemes"], indent=2)
149 # { 'api_key': {'in': 'header', 'name': 'X-API-Key', 'type': 'apiKey'},
150 # 'jwt': {'bearerFormat': 'JWT', 'scheme': 'bearer', 'type': 'http'}}
151
152 Referencing Top-level Components
153 --------------------------------
154
155 On OpenAPI, top-level component are meant to be referenced using a ``$ref``,
156 as in ``{$ref: '#/components/schemas/Pet'}`` (OpenAPI v3) or
157 ``{$ref: '#/definitions/Pet'}`` (OpenAPI v2).
158
159 APISpec automatically resolves references in paths and in components themselves
160 when a string is provided while a dict is expected. Passing a fully-resolved
161 reference is not supported. In other words, rather than passing
162 ``{"schema": {$ref: '#/components/schemas/Pet'}}``, the user must pass
163 ``{"schema": "Pet"}``. APISpec assumes a schema reference named ``"Pet"`` has
164 been defined and builds the reference using the components location
165 corresponding to the OpenAPI version.