0
# Component Management
1
2
Management of reusable OpenAPI components including schemas, responses, parameters, headers, examples, and security schemes. Components enable reusability and maintainability in OpenAPI specifications through reference-based definitions.
3
4
## Capabilities
5
6
### Schema Management
7
8
Register and manage schema components that define data structures used throughout the API specification.
9
10
```python { .api }
11
def schema(
12
self,
13
component_id: str,
14
component: dict | None = None,
15
*,
16
lazy: bool = False,
17
**kwargs: Any
18
) -> Components:
19
"""
20
Add a new schema to the specification.
21
22
Parameters:
23
- component_id: Identifier by which schema may be referenced
24
- component: Schema definition dictionary
25
- lazy: Register component only when referenced in the spec
26
- **kwargs: Plugin-specific arguments (e.g., marshmallow metadata)
27
28
Returns:
29
Self for method chaining
30
31
Raises:
32
- DuplicateComponentNameError: If component_id already exists
33
"""
34
```
35
36
### Response Management
37
38
Register reusable response components that can be referenced across multiple operations.
39
40
```python { .api }
41
def response(
42
self,
43
component_id: str,
44
component: dict | None = None,
45
*,
46
lazy: bool = False,
47
**kwargs: Any
48
) -> Components:
49
"""
50
Add a response which can be referenced.
51
52
Parameters:
53
- component_id: Identifier by which response may be referenced
54
- component: Response definition dictionary
55
- lazy: Register component only when referenced in the spec
56
- **kwargs: Plugin-specific arguments
57
58
Returns:
59
Self for method chaining
60
61
Raises:
62
- DuplicateComponentNameError: If component_id already exists
63
"""
64
```
65
66
### Parameter Management
67
68
Register reusable parameter components for path, query, header, and cookie parameters.
69
70
```python { .api }
71
def parameter(
72
self,
73
component_id: str,
74
location: str,
75
component: dict | None = None,
76
*,
77
lazy: bool = False,
78
**kwargs: Any
79
) -> Components:
80
"""
81
Add a parameter which can be referenced.
82
83
Parameters:
84
- component_id: Identifier by which parameter may be referenced
85
- location: Parameter location ('path', 'query', 'header', 'cookie')
86
- component: Parameter definition dictionary
87
- lazy: Register component only when referenced in the spec
88
- **kwargs: Plugin-specific arguments
89
90
Returns:
91
Self for method chaining
92
93
Raises:
94
- DuplicateComponentNameError: If component_id already exists
95
96
Note:
97
Path parameters automatically have required=True set
98
"""
99
```
100
101
### Header Management
102
103
Register reusable header components for response headers.
104
105
```python { .api }
106
def header(
107
self,
108
component_id: str,
109
component: dict,
110
*,
111
lazy: bool = False,
112
**kwargs: Any
113
) -> Components:
114
"""
115
Add a header which can be referenced.
116
117
Parameters:
118
- component_id: Identifier by which header may be referenced
119
- component: Header definition dictionary
120
- lazy: Register component only when referenced in the spec
121
- **kwargs: Plugin-specific arguments
122
123
Returns:
124
Self for method chaining
125
126
Raises:
127
- DuplicateComponentNameError: If component_id already exists
128
"""
129
```
130
131
### Example Management
132
133
Register reusable example components for request and response examples.
134
135
```python { .api }
136
def example(
137
self,
138
component_id: str,
139
component: dict,
140
*,
141
lazy: bool = False
142
) -> Components:
143
"""
144
Add an example which can be referenced.
145
146
Parameters:
147
- component_id: Identifier by which example may be referenced
148
- component: Example definition dictionary
149
- lazy: Register component only when referenced in the spec
150
151
Returns:
152
Self for method chaining
153
154
Raises:
155
- DuplicateComponentNameError: If component_id already exists
156
"""
157
```
158
159
### Security Scheme Management
160
161
Register security scheme components for API authentication and authorization.
162
163
```python { .api }
164
def security_scheme(self, component_id: str, component: dict) -> Components:
165
"""
166
Add a security scheme which can be referenced.
167
168
Parameters:
169
- component_id: Identifier by which security scheme may be referenced
170
- component: Security scheme definition dictionary
171
172
Returns:
173
Self for method chaining
174
175
Raises:
176
- DuplicateComponentNameError: If component_id already exists
177
"""
178
```
179
180
### Reference Resolution
181
182
Convert component references to proper OpenAPI reference objects or return inline definitions.
183
184
```python { .api }
185
def get_ref(
186
self,
187
obj_type: str,
188
obj_or_component_id: dict | str
189
) -> dict:
190
"""
191
Return object or reference for a component.
192
193
Parameters:
194
- obj_type: Component type ('schema', 'parameter', 'response', 'header', 'example', 'security_scheme')
195
- obj_or_component_id: Either a complete definition dict or a reference ID string
196
197
Returns:
198
Either the complete definition dict or a $ref object
199
"""
200
```
201
202
### Component Serialization
203
204
Convert all registered components to their OpenAPI specification format.
205
206
```python { .api }
207
def to_dict(self) -> dict[str, dict]:
208
"""
209
Convert components to dictionary format for OpenAPI specification.
210
211
Returns:
212
Dictionary mapping component sections to their definitions
213
"""
214
```
215
216
## Properties
217
218
Component storage properties providing access to registered components.
219
220
```python { .api }
221
schemas: dict[str, dict] # Schema components
222
responses: dict[str, dict] # Response components
223
parameters: dict[str, dict] # Parameter components
224
headers: dict[str, dict] # Header components
225
examples: dict[str, dict] # Example components
226
security_schemes: dict[str, dict] # Security scheme components
227
schemas_lazy: dict[str, dict] # Lazy schema components storage
228
responses_lazy: dict[str, dict] # Lazy response components storage
229
parameters_lazy: dict[str, dict] # Lazy parameter components storage
230
headers_lazy: dict[str, dict] # Lazy header components storage
231
examples_lazy: dict[str, dict] # Lazy example components storage
232
openapi_version: Version # OpenAPI version for reference formatting
233
```
234
235
## Usage Examples
236
237
### Schema Components
238
239
```python
240
from apispec import APISpec
241
242
spec = APISpec(title="API", version="1.0.0", openapi_version="3.0.2")
243
244
# Register schema components
245
spec.components.schema("User", {
246
"type": "object",
247
"properties": {
248
"id": {"type": "integer", "readOnly": True},
249
"name": {"type": "string"},
250
"email": {"type": "string", "format": "email"}
251
},
252
"required": ["name", "email"]
253
})
254
255
spec.components.schema("Error", {
256
"type": "object",
257
"properties": {
258
"code": {"type": "integer"},
259
"message": {"type": "string"}
260
},
261
"required": ["code", "message"]
262
})
263
```
264
265
### Response Components
266
267
```python
268
# Register response components
269
spec.components.response("NotFound", {
270
"description": "Resource not found",
271
"content": {
272
"application/json": {
273
"schema": {"$ref": "#/components/schemas/Error"}
274
}
275
}
276
})
277
278
spec.components.response("UserResponse", {
279
"description": "User information",
280
"content": {
281
"application/json": {
282
"schema": {"$ref": "#/components/schemas/User"}
283
}
284
}
285
})
286
```
287
288
### Parameter Components
289
290
```python
291
# Register parameter components
292
spec.components.parameter("UserId", "path", {
293
"description": "Unique identifier for a user",
294
"schema": {"type": "integer", "minimum": 1}
295
})
296
297
spec.components.parameter("Limit", "query", {
298
"description": "Maximum number of results to return",
299
"schema": {"type": "integer", "minimum": 1, "maximum": 100, "default": 20}
300
})
301
```
302
303
### Security Schemes
304
305
```python
306
# Register security schemes
307
spec.components.security_scheme("ApiKeyAuth", {
308
"type": "apiKey",
309
"in": "header",
310
"name": "X-API-Key"
311
})
312
313
spec.components.security_scheme("BearerAuth", {
314
"type": "http",
315
"scheme": "bearer",
316
"bearerFormat": "JWT"
317
})
318
```
319
320
### Using Components in Paths
321
322
```python
323
# Use registered components in path definitions
324
spec.path("/users/{id}", operations={
325
"get": {
326
"summary": "Get user by ID",
327
"parameters": [
328
{"$ref": "#/components/parameters/UserId"}
329
],
330
"responses": {
331
"200": {"$ref": "#/components/responses/UserResponse"},
332
"404": {"$ref": "#/components/responses/NotFound"}
333
},
334
"security": [{"ApiKeyAuth": []}]
335
}
336
})
337
```
338
339
### Lazy Registration
340
341
```python
342
# Register components lazily - only included in spec when referenced
343
spec.components.schema("LazyUser", user_schema_dict, lazy=True)
344
345
# Component will be registered when first referenced
346
user_ref = spec.components.get_ref("schema", "LazyUser")
347
```