Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy pathopenapi.py
More file actions
Latest commit
555 lines (482 loc) · 22.4 KB
/
Copy pathopenapi.py
File metadata and controls
555 lines (482 loc) · 22.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
importre
fromcollections.abcimportIterator
fromcopyimportdeepcopy
fromdataclassesimportdataclass, field
fromtypingimportAny, Protocol
frompydanticimportValidationError
from .. importschemaasoai
from .. importutils
from ..configimportConfig
from ..utilsimportPythonIdentifier
from .bodiesimportBody, body_from_data
from .errorsimportGeneratorError, ParseError, PropertyError
from .propertiesimport (
Class,
EnumProperty,
LiteralEnumProperty,
ModelProperty,
Parameters,
Property,
Schemas,
build_parameters,
build_schemas,
property_from_data,
)
from .properties.schemasimportparameter_from_reference
from .responsesimportHTTPStatusPattern, Responses, response_from_data
_PATH_PARAM_REGEX=re.compile("{([a-zA-Z_-][a-zA-Z0-9_-]*)}")
defimport_string_from_class(class_: Class, prefix: str="") ->str:
"""Create a string which is used to import a reference"""
returnf"from {prefix}.{class_.module_name} import {class_.name}"
@dataclass
classEndpointCollection:
"""A bunch of endpoints grouped under a tag that will become a module"""
tag: str
endpoints: list["Endpoint"] =field(default_factory=list)
parse_errors: list[ParseError] =field(default_factory=list)
@staticmethod
deffrom_data(
*,
data: dict[str, oai.PathItem],
schemas: Schemas,
parameters: Parameters,
request_bodies: dict[str, oai.RequestBody|oai.Reference],
responses: dict[str, oai.Response|oai.Reference],
config: Config,
) ->tuple[dict[utils.PythonIdentifier, "EndpointCollection"], Schemas, Parameters]:
"""Parse the openapi paths data to get EndpointCollections by tag"""
endpoints_by_tag: dict[utils.PythonIdentifier, EndpointCollection] = {}
methods= ["get", "put", "post", "delete", "options", "head", "patch", "trace"]
forpath, path_dataindata.items():
formethodinmethods:
operation: oai.Operation|None=getattr(path_data, method)
ifoperationisNone:
continue
tags= [utils.PythonIdentifier(value=tag, prefix="tag") fortaginoperation.tagsor ["default"]]
ifnotconfig.generate_all_tags:
tags=tags[:1]
collections= [endpoints_by_tag.setdefault(tag, EndpointCollection(tag=tag)) fortagintags]
endpoint, schemas, parameters=Endpoint.from_data(
data=operation,
path=path,
method=method,
tags=tags,
schemas=schemas,
parameters=parameters,
request_bodies=request_bodies,
responses=responses,
config=config,
)
# Add `PathItem` parameters
ifnotisinstance(endpoint, ParseError):
endpoint, schemas, parameters=Endpoint.add_parameters(
endpoint=endpoint,
data=path_data,
schemas=schemas,
parameters=parameters,
config=config,
)
ifnotisinstance(endpoint, ParseError):
endpoint=Endpoint.sort_parameters(endpoint=endpoint)
ifisinstance(endpoint, ParseError):
endpoint.header=f"WARNING parsing {method.upper()}{path} within {'/'.join(tags)}. Endpoint will not be generated."
forcollectionincollections:
collection.parse_errors.append(endpoint)
continue
forerrorinendpoint.errors:
error.header=f"WARNING parsing {method.upper()}{path} within {'/'.join(tags)}."
forcollectionincollections:
collection.parse_errors.append(error)
forcollectionincollections:
collection.endpoints.append(endpoint)
returnendpoints_by_tag, schemas, parameters
defgenerate_operation_id(*, path: str, method: str) ->str:
"""Generate an operationId from a path"""
clean_path=path.replace("{", "").replace("}", "").replace("/", "_")
ifclean_path.startswith("_"):
clean_path=clean_path[1:]
ifclean_path.endswith("_"):
clean_path=clean_path[:-1]
returnf"{method}_{clean_path}"
models_relative_prefix: str="..."
classRequestBodyParser(Protocol):
__name__: str="RequestBodyParser"
def__call__(
self, *, body: oai.RequestBody, schemas: Schemas, parent_name: str, config: Config
) ->tuple[Property|PropertyError|None, Schemas]: ... # pragma: no cover
@dataclass
classEndpoint:
"""
Describes a single endpoint on the server
"""
path: str
method: str
description: str|None
name: str
requires_security: bool
tags: list[PythonIdentifier]
summary: str|None=""
relative_imports: set[str] =field(default_factory=set)
query_parameters: list[Property] =field(default_factory=list)
path_parameters: list[Property] =field(default_factory=list)
header_parameters: list[Property] =field(default_factory=list)
cookie_parameters: list[Property] =field(default_factory=list)
responses: Responses=field(default_factory=lambda: Responses(patterns=[], default=None))
bodies: list[Body] =field(default_factory=list)
errors: list[ParseError] =field(default_factory=list)
@staticmethod
def_add_responses(
*,
endpoint: "Endpoint",
data: oai.Responses,
schemas: Schemas,
responses: dict[str, oai.Response|oai.Reference],
config: Config,
) ->tuple["Endpoint", Schemas]:
endpoint=deepcopy(endpoint)
forcode, response_dataindata.items():
status_code=HTTPStatusPattern.parse(code)
ifisinstance(status_code, ParseError):
endpoint.errors.append(status_code)
continue
response, schemas=response_from_data(
status_code=status_code,
data=response_data,
schemas=schemas,
responses=responses,
parent_name=endpoint.name,
config=config,
)
ifisinstance(response, ParseError):
detail_suffix=""ifresponse.detailisNoneelsef" ({response.detail})"
endpoint.errors.append(
ParseError(
detail=(
f"Cannot parse response for status code {code}{detail_suffix}, "
f"response will be omitted from generated client"
),
data=response.data,
)
)
continue
# No reasons to use lazy imports in endpoints, so add lazy imports to relative here.
endpoint.relative_imports|=response.prop.get_lazy_imports(prefix=models_relative_prefix)
endpoint.relative_imports|=response.prop.get_imports(prefix=models_relative_prefix)
ifresponse.is_default():
endpoint.responses.default=response
else:
endpoint.responses.patterns.append(response)
endpoint.responses.patterns.sort()
returnendpoint, schemas
@staticmethod
defadd_parameters(
*,
endpoint: "Endpoint",
data: oai.Operation|oai.PathItem,
schemas: Schemas,
parameters: Parameters,
config: Config,
) ->tuple["Endpoint | ParseError", Schemas, Parameters]:
"""Process the defined `parameters` for an Endpoint.
Any existing parameters will be ignored, so earlier instances of a parameter take precedence. PathItem
parameters should therefore be added __after__ operation parameters.
Args:
endpoint: The endpoint to add parameters to.
data: The Operation or PathItem to add parameters from.
schemas: The cumulative Schemas of processing so far which should contain details for any references.
parameters: The cumulative Parameters of processing so far which should contain details for any references.
config: User-provided config for overrides within parameters.
Returns:
`(result, schemas, parameters)` where `result` is either an updated Endpoint containing the parameters or a
ParseError describing what went wrong. `schemas` is an updated version of the `schemas` input, adding any
new enums or classes. `parameters` is an updated version of the `parameters` input, adding new parameters.
See Also:
- https://swagger.io/docs/specification/describing-parameters/
- https://swagger.io/docs/specification/paths-and-operations/
"""
# There isn't much value in breaking down this function further other than to satisfy the linter.
ifdata.parametersisNone:
returnendpoint, schemas, parameters
endpoint=deepcopy(endpoint)
unique_parameters: set[tuple[str, oai.ParameterLocation]] =set()
parameters_by_location: dict[str, list[Property]] = {
oai.ParameterLocation.QUERY: endpoint.query_parameters,
oai.ParameterLocation.PATH: endpoint.path_parameters,
oai.ParameterLocation.HEADER: endpoint.header_parameters,
oai.ParameterLocation.COOKIE: endpoint.cookie_parameters,
}
forparamindata.parameters:
# Obtain the parameter from the reference or just the parameter itself
param_or_error=parameter_from_reference(param=param, parameters=parameters)
ifisinstance(param_or_error, ParseError):
returnparam_or_error, schemas, parameters
param=param_or_error# noqa: PLW2901
ifparam.param_schemaisNone:
continue
unique_param= (param.name, param.param_in)
ifunique_paraminunique_parameters:
return (
ParseError(
data=data,
detail=(
"Parameters MUST NOT contain duplicates. "
"A unique parameter is defined by a combination of a name and location. "
f"Duplicated parameters named `{param.name}` detected in `{param.param_in}`."
),
),
schemas,
parameters,
)
unique_parameters.add(unique_param)
ifany(
other_paramforother_paraminparameters_by_location[param.param_in] ifother_param.name==param.name
):
# Defined at the operation level, ignore it here
continue
prop, new_schemas=property_from_data(
name=param.name,
required=param.required,
data=param.param_schema,
schemas=schemas,
parent_name=endpoint.name,
config=config,
)
ifisinstance(prop, ParseError):
return (
ParseError(
detail=f"cannot parse parameter of endpoint {endpoint.name}: {prop.detail}",
data=prop.data,
),
schemas,
parameters,
)
schemas=new_schemas
location_error=prop.validate_location(param.param_in)
iflocation_errorisnotNone:
location_error.data=param
returnlocation_error, schemas, parameters
# No reasons to use lazy imports in endpoints, so add lazy imports to relative here.
endpoint.relative_imports.update(prop.get_lazy_imports(prefix=models_relative_prefix))
endpoint.relative_imports.update(prop.get_imports(prefix=models_relative_prefix))
parameters_by_location[param.param_in].append(prop)
returnendpoint._check_parameters_for_conflicts(config=config), schemas, parameters
def_check_parameters_for_conflicts(
self,
*,
config: Config,
previously_modified_params: set[tuple[oai.ParameterLocation, str]] |None=None,
) ->"Endpoint | ParseError":
"""Check for conflicting parameters
For parameters that have the same python_name but are in different locations, append the location to the
python_name. For parameters that have the same name but are in the same location, use their raw name without
snake casing instead.
Function stops when there's a conflict that can't be resolved or all parameters are guaranteed to have a
unique python_name.
"""
modified_params=previously_modified_paramsorset()
used_python_names: dict[PythonIdentifier, tuple[oai.ParameterLocation, Property]] = {}
reserved_names= ["client", "url"]
forparameterinself.iter_all_parameters():
location, prop=parameter
ifprop.python_nameinreserved_names:
prop.set_python_name(new_name=f"{prop.python_name}_{location}", config=config)
modified_params.add((location, prop.name))
continue
conflicting=used_python_names.pop(prop.python_name, None)
ifconflictingisNone:
used_python_names[prop.python_name] =parameter
continue
conflicting_location, conflicting_prop=conflicting
if (conflicting_location, conflicting_prop.name) inmodified_paramsor (
location,
prop.name,
) inmodified_params:
returnParseError(
detail=f"Parameters with same Python identifier {conflicting_prop.python_name} detected",
)
iflocation!=conflicting_location:
conflicting_prop.set_python_name(
new_name=f"{conflicting_prop.python_name}_{conflicting_location}", config=config
)
prop.set_python_name(new_name=f"{prop.python_name}_{location}", config=config)
elifconflicting_prop.name!=prop.name: # Use the name to differentiate
conflicting_prop.set_python_name(new_name=conflicting_prop.name, config=config, skip_snake_case=True)
prop.set_python_name(new_name=prop.name, config=config, skip_snake_case=True)
modified_params.add((location, conflicting_prop.name))
modified_params.add((conflicting_location, conflicting_prop.name))
used_python_names[prop.python_name] =parameter
used_python_names[conflicting_prop.python_name] =conflicting
iflen(modified_params) >0andmodified_params!=previously_modified_params:
returnself._check_parameters_for_conflicts(config=config, previously_modified_params=modified_params)
returnself
@staticmethod
defsort_parameters(*, endpoint: "Endpoint") ->"Endpoint | ParseError":
"""
Sorts the path parameters of an `endpoint` so that they match the order declared in `endpoint.path`.
Args:
endpoint: The endpoint to sort the parameters of.
Returns:
Either an updated `endpoint` with sorted path parameters or a `ParseError` if something was wrong with
the path parameters and they could not be sorted.
"""
endpoint=deepcopy(endpoint)
parameters_from_path=re.findall(_PATH_PARAM_REGEX, endpoint.path)
try:
endpoint.path_parameters.sort(
key=lambdaparam: parameters_from_path.index(param.name),
)
exceptValueError:
pass# We're going to catch the difference down below
ifparameters_from_path!= [param.nameforparaminendpoint.path_parameters]:
returnParseError(
detail=f"Incorrect path templating for {endpoint.path} (Path parameters do not match with path)",
)
forparameterinendpoint.path_parameters:
endpoint.path=endpoint.path.replace(f"{{{parameter.name}}}", f"{{{parameter.python_name}}}")
returnendpoint
@staticmethod
deffrom_data(
*,
data: oai.Operation,
path: str,
method: str,
tags: list[PythonIdentifier],
schemas: Schemas,
parameters: Parameters,
request_bodies: dict[str, oai.RequestBody|oai.Reference],
responses: dict[str, oai.Response|oai.Reference],
config: Config,
) ->tuple["Endpoint | ParseError", Schemas, Parameters]:
"""Construct an endpoint from the OpenAPI data"""
ifdata.operationIdisNone:
name=generate_operation_id(path=path, method=method)
else:
name=data.operationId
endpoint=Endpoint(
path=path,
method=method,
summary=utils.remove_string_escapes(data.summary) ifdata.summaryelse"",
description=utils.remove_string_escapes(data.description) ifdata.descriptionelse"",
name=name,
requires_security=bool(data.security),
tags=tags,
)
result, schemas, parameters=Endpoint.add_parameters(
endpoint=endpoint,
data=data,
schemas=schemas,
parameters=parameters,
config=config,
)
ifisinstance(result, ParseError):
returnresult, schemas, parameters
result, schemas=Endpoint._add_responses(
endpoint=result,
data=data.responses,
schemas=schemas,
responses=responses,
config=config,
)
ifisinstance(result, ParseError):
returnresult, schemas, parameters
bodies, schemas=body_from_data(
data=data, schemas=schemas, config=config, endpoint_name=result.name, request_bodies=request_bodies
)
body_errors= []
forbodyinbodies:
ifisinstance(body, ParseError):
body_errors.append(body)
continue
result.bodies.append(body)
result.relative_imports.update(body.prop.get_imports(prefix=models_relative_prefix))
result.relative_imports.update(body.prop.get_lazy_imports(prefix=models_relative_prefix))
iflen(result.bodies) >0:
result.errors.extend(body_errors)
eliflen(body_errors) >0:
return (
ParseError(
header="Endpoint requires a body, but none were parseable.",
detail="\n".join(error.detailor""forerrorinbody_errors),
),
schemas,
parameters,
)
returnresult, schemas, parameters
defresponse_type(self) ->str:
"""Get the Python type of any response from this endpoint"""
types=sorted({response.prop.get_type_string() forresponseinself.responses})
iflen(types) ==0:
return"Any"
iflen(types) ==1:
returntypes[0]
return" | ".join(types)
defiter_all_parameters(self) ->Iterator[tuple[oai.ParameterLocation, Property]]:
"""Iterate through all the parameters of this endpoint"""
yieldfrom ((oai.ParameterLocation.PATH, param) forparaminself.path_parameters)
yieldfrom ((oai.ParameterLocation.QUERY, param) forparaminself.query_parameters)
yieldfrom ((oai.ParameterLocation.HEADER, param) forparaminself.header_parameters)
yieldfrom ((oai.ParameterLocation.COOKIE, param) forparaminself.cookie_parameters)
deflist_all_parameters(self) ->list[Property]:
"""Return a list of all the parameters of this endpoint"""
return (
self.path_parameters
+self.query_parameters
+self.header_parameters
+self.cookie_parameters
+ [body.propforbodyinself.bodies]
)
@dataclass
classGeneratorData:
"""All the data needed to generate a client"""
title: str
description: str|None
version: str
models: list[ModelProperty]
errors: list[ParseError]
endpoint_collections_by_tag: dict[utils.PythonIdentifier, EndpointCollection]
enums: list[EnumProperty|LiteralEnumProperty]
@staticmethod
deffrom_dict(data: dict[str, Any], *, config: Config) ->"GeneratorData | GeneratorError":
"""Create an OpenAPI from dict"""
try:
openapi=oai.OpenAPI.model_validate(data)
exceptValidationErroraserr:
detail=str(err)
if"swagger"indata:
detail= (
"You may be trying to use a Swagger document; this is not supported by this project.\n\n"+detail
)
returnGeneratorError(header="Failed to parse OpenAPI document", detail=detail)
schemas=Schemas()
parameters=Parameters()
ifopenapi.componentsandopenapi.components.schemas:
schemas=build_schemas(components=openapi.components.schemas, schemas=schemas, config=config)
ifopenapi.componentsandopenapi.components.parameters:
parameters=build_parameters(
components=openapi.components.parameters,
parameters=parameters,
config=config,
)
request_bodies= (openapi.componentsandopenapi.components.requestBodies) or {}
responses= (openapi.componentsandopenapi.components.responses) or {}
endpoint_collections_by_tag, schemas, parameters=EndpointCollection.from_data(
data=openapi.paths,
schemas=schemas,
parameters=parameters,
request_bodies=request_bodies,
responses=responses,
config=config,
)
enums= [
propforpropinschemas.classes_by_name.values() ifisinstance(prop, EnumProperty|LiteralEnumProperty)
]
models= [propforpropinschemas.classes_by_name.values() ifisinstance(prop, ModelProperty)]
returnGeneratorData(
title=openapi.info.title,
description=openapi.info.description,
version=openapi.info.version,
endpoint_collections_by_tag=endpoint_collections_by_tag,
models=models,
errors=schemas.errors+parameters.errors,
enums=enums,
)