0
# Utility Functions
1
2
Helper functions for OpenAPI specification generation, parameter parsing, schema extraction, and operation management. These utilities support the automatic documentation generation and request validation features of Flask-OpenAPI3.
3
4
## Capabilities
5
6
### OpenAPI Generation Utilities
7
8
Functions for creating and managing OpenAPI operation specifications.
9
10
```python { .api }
11
def get_operation(
12
func: Callable,
13
*,
14
summary: Optional[str] = None,
15
description: Optional[str] = None,
16
openapi_extensions: Optional[dict[str, Any]] = None,
17
) -> Operation:
18
"""
19
Return an Operation object with the specified summary and description.
20
21
Args:
22
func: The function or method for which the operation is being defined.
23
summary: A short summary of what the operation does.
24
description: A verbose explanation of the operation behavior.
25
openapi_extensions: Additional extensions to the OpenAPI Schema.
26
27
Returns:
28
An Operation object representing the operation.
29
"""
30
```
31
32
**Usage Example:**
33
34
```python
35
from flask_openapi3.utils import get_operation
36
37
def my_endpoint():
38
"""Get all users from the database"""
39
return []
40
41
# Create operation from function
42
operation = get_operation(
43
my_endpoint,
44
summary="List Users",
45
description="Retrieve a paginated list of all users",
46
openapi_extensions={"x-custom": "value"}
47
)
48
```
49
50
### Operation ID Generation
51
52
Functions for generating unique operation IDs for API endpoints.
53
54
```python { .api }
55
def get_operation_id_for_path(
56
*,
57
bp_name: str = "",
58
name: str = "",
59
path: str = "",
60
method: str = ""
61
) -> str:
62
"""
63
Generate operation ID for API endpoints.
64
65
Args:
66
bp_name: Blueprint name (if applicable)
67
name: Function name
68
path: URL path
69
method: HTTP method
70
71
Returns:
72
Generated operation ID string
73
"""
74
```
75
76
**Usage Example:**
77
78
```python
79
from flask_openapi3.utils import get_operation_id_for_path
80
81
# Generate operation ID
82
op_id = get_operation_id_for_path(
83
bp_name="users",
84
name="create_user",
85
path="/users",
86
method="POST"
87
)
88
# Result: "users_create_user_post"
89
```
90
91
### Schema Extraction
92
93
Functions for extracting JSON schemas from Pydantic models.
94
95
```python { .api }
96
def get_model_schema(
97
model: Type[BaseModel],
98
mode: JsonSchemaMode = "validation"
99
) -> dict:
100
"""
101
Extract JSON schema from Pydantic model.
102
103
Args:
104
model: Pydantic model class
105
mode: Schema generation mode ("validation" or "serialization")
106
107
Returns:
108
JSON schema dictionary
109
"""
110
```
111
112
**Usage Example:**
113
114
```python
115
from flask_openapi3.utils import get_model_schema
116
from pydantic import BaseModel
117
118
class User(BaseModel):
119
name: str
120
email: str
121
age: int = None
122
123
# Extract schema
124
schema = get_model_schema(User)
125
# Returns JSON schema with properties, required fields, etc.
126
```
127
128
### Parameter Parsing Functions
129
130
Functions for parsing different types of parameters from Pydantic models.
131
132
```python { .api }
133
def parse_parameters(
134
path: Optional[Type[BaseModel]] = None,
135
query: Optional[Type[BaseModel]] = None,
136
header: Optional[Type[BaseModel]] = None,
137
cookie: Optional[Type[BaseModel]] = None,
138
form: Optional[Type[BaseModel]] = None,
139
body: Optional[Type[BaseModel]] = None,
140
raw: Optional[Type[RawModel]] = None
141
) -> ParametersTuple:
142
"""
143
Parse all parameter types for endpoint.
144
145
Args:
146
path: Path parameter model
147
query: Query parameter model
148
header: Header parameter model
149
cookie: Cookie parameter model
150
form: Form data model
151
body: Request body model
152
raw: Raw request model
153
154
Returns:
155
Tuple of processed parameter models
156
"""
157
```
158
159
### Individual Parameter Parsers
160
161
Specialized functions for parsing specific parameter types.
162
163
```python { .api }
164
def parse_header(header: Type[BaseModel]) -> tuple[list[Parameter], dict]:
165
"""
166
Parse header parameters from model.
167
168
Args:
169
header: Pydantic model defining header parameters
170
171
Returns:
172
Tuple of (parameter list, schema dict)
173
"""
174
175
def parse_cookie(cookie: Type[BaseModel]) -> tuple[list[Parameter], dict]:
176
"""
177
Parse cookie parameters from model.
178
179
Args:
180
cookie: Pydantic model defining cookie parameters
181
182
Returns:
183
Tuple of (parameter list, schema dict)
184
"""
185
186
def parse_path(path: Type[BaseModel]) -> tuple[list[Parameter], dict]:
187
"""
188
Parse path parameters from model.
189
190
Args:
191
path: Pydantic model defining path parameters
192
193
Returns:
194
Tuple of (parameter list, schema dict)
195
"""
196
197
def parse_query(query: Type[BaseModel]) -> tuple[list[Parameter], dict]:
198
"""
199
Parse query parameters from model.
200
201
Args:
202
query: Pydantic model defining query parameters
203
204
Returns:
205
Tuple of (parameter list, schema dict)
206
"""
207
208
def parse_form(
209
form: Type[BaseModel],
210
*,
211
multipart: bool = False
212
) -> tuple[Optional[RequestBody], dict]:
213
"""
214
Parse form data parameters from model.
215
216
Args:
217
form: Pydantic model defining form fields
218
multipart: Whether to use multipart/form-data encoding
219
220
Returns:
221
Tuple of (request body, schema dict)
222
"""
223
224
def parse_body(
225
body: Type[BaseModel],
226
*,
227
content_type: str = "application/json"
228
) -> tuple[Optional[RequestBody], dict]:
229
"""
230
Parse request body from model.
231
232
Args:
233
body: Pydantic model defining request body
234
content_type: Media type for request body
235
236
Returns:
237
Tuple of (request body, schema dict)
238
"""
239
```
240
241
**Usage Example:**
242
243
```python
244
from flask_openapi3.utils import parse_query, parse_body
245
from pydantic import BaseModel
246
247
class UserQuery(BaseModel):
248
name: str
249
age: int = None
250
251
class UserBody(BaseModel):
252
email: str
253
password: str
254
255
# Parse query parameters
256
query_params, query_schema = parse_query(UserQuery)
257
258
# Parse request body
259
request_body, body_schema = parse_body(UserBody)
260
```
261
262
### Response Processing
263
264
Functions for processing response definitions.
265
266
```python { .api }
267
def get_responses(
268
responses: Optional[ResponseDict] = None,
269
validation_error_status: Union[str, int] = 422,
270
validation_error_model: Type[BaseModel] = ValidationErrorModel
271
) -> Responses:
272
"""
273
Process response definitions for OpenAPI.
274
275
Args:
276
responses: Response definitions by status code
277
validation_error_status: Status code for validation errors
278
validation_error_model: Model for validation error responses
279
280
Returns:
281
Processed Responses object
282
"""
283
284
def convert_responses_key_to_string(responses: ResponseDict) -> ResponseStrKeyDict:
285
"""
286
Convert response status codes to strings.
287
288
Args:
289
responses: Response dict with int/HTTPStatus keys
290
291
Returns:
292
Response dict with string keys
293
"""
294
```
295
296
### HTTP Method and Rule Parsing
297
298
Utility functions for processing HTTP methods and URL rules.
299
300
```python { .api }
301
def parse_method(method: str) -> HTTPMethod:
302
"""
303
Parse HTTP method from string.
304
305
Args:
306
method: HTTP method string
307
308
Returns:
309
HTTPMethod enum value
310
"""
311
312
def parse_rule(rule: str) -> str:
313
"""
314
Parse URL rule patterns.
315
316
Args:
317
rule: Flask URL rule string
318
319
Returns:
320
Processed rule string
321
"""
322
```
323
324
### Tag Management
325
326
Functions for processing and storing endpoint tags.
327
328
```python { .api }
329
def parse_and_store_tags(
330
tags: Optional[list[Tag]] = None,
331
tag_names: Optional[list[str]] = None
332
) -> list[str]:
333
"""
334
Process and store endpoint tags.
335
336
Args:
337
tags: List of Tag objects
338
tag_names: List of tag name strings
339
340
Returns:
341
List of tag names
342
"""
343
```
344
345
### Error Response Creation
346
347
Functions for creating validation error responses.
348
349
```python { .api }
350
def make_validation_error_response(e: ValidationError) -> dict:
351
"""
352
Create validation error response.
353
354
Args:
355
e: Pydantic ValidationError
356
357
Returns:
358
Error response dictionary
359
"""
360
```
361
362
**Usage Example:**
363
364
```python
365
from flask_openapi3.utils import make_validation_error_response
366
from pydantic import ValidationError, BaseModel
367
368
class User(BaseModel):
369
name: str
370
age: int
371
372
try:
373
User(name="John", age="invalid")
374
except ValidationError as e:
375
error_response = make_validation_error_response(e)
376
# Returns structured error response
377
```
378
379
## Constants and Enums
380
381
### HTTP Status Mappings
382
383
```python { .api }
384
HTTP_STATUS: dict[str, str]
385
"""HTTP status code to phrase mapping"""
386
```
387
388
**Usage Example:**
389
390
```python
391
from flask_openapi3.utils import HTTP_STATUS
392
393
# Get status phrase
394
status_phrase = HTTP_STATUS["200"] # "OK"
395
status_phrase = HTTP_STATUS["404"] # "Not Found"
396
```
397
398
### HTTP Method Enum
399
400
```python { .api }
401
class HTTPMethod(str, Enum):
402
"""HTTP methods enumeration"""
403
GET = "GET"
404
POST = "POST"
405
PUT = "PUT"
406
DELETE = "DELETE"
407
PATCH = "PATCH"
408
HEAD = "HEAD"
409
OPTIONS = "OPTIONS"
410
TRACE = "TRACE"
411
CONNECT = "CONNECT"
412
```
413
414
## Advanced Usage
415
416
### Custom Operation ID Callback
417
418
Create custom operation ID generation logic:
419
420
```python
421
from flask_openapi3 import OpenAPI, Info
422
423
def custom_operation_id(*, bp_name="", name="", path="", method=""):
424
"""Custom operation ID generator"""
425
parts = []
426
if bp_name:
427
parts.append(bp_name)
428
if name:
429
parts.append(name)
430
parts.append(method.lower())
431
return "_".join(parts)
432
433
app = OpenAPI(
434
__name__,
435
info=Info(title="API", version="1.0.0"),
436
operation_id_callback=custom_operation_id
437
)
438
```
439
440
### Custom Schema Processing
441
442
Process schemas with custom logic:
443
444
```python
445
from flask_openapi3.utils import get_model_schema
446
from pydantic import BaseModel
447
448
class User(BaseModel):
449
name: str
450
email: str
451
452
# Get schema with custom processing
453
schema = get_model_schema(User, mode="serialization")
454
455
# Add custom properties
456
schema["x-custom-property"] = "custom-value"
457
```
458
459
### Complex Parameter Parsing
460
461
Handle complex parameter scenarios:
462
463
```python
464
from flask_openapi3.utils import parse_parameters, parse_query, parse_body
465
from pydantic import BaseModel
466
467
class ComplexQuery(BaseModel):
468
filters: dict[str, str] = {}
469
sort: list[str] = []
470
471
class ComplexBody(BaseModel):
472
data: dict[str, Any]
473
metadata: dict[str, str] = {}
474
475
# Parse all parameters
476
params = parse_parameters(
477
query=ComplexQuery,
478
body=ComplexBody
479
)
480
481
# Handle individual parsing
482
query_params, query_schema = parse_query(ComplexQuery)
483
body_params, body_schema = parse_body(ComplexBody)
484
```