-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgenerate_from_openapi.py
More file actions
executable file
·1428 lines (1201 loc) · 46.8 KB
/
Copy pathgenerate_from_openapi.py
File metadata and controls
executable file
·1428 lines (1201 loc) · 46.8 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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import re
import shutil
import sys
import yaml
# Configuration constants
OPENAPI_FILE = "./mist_openapi/mist.openapi.yaml"
OPENAPI_JSON = None
ROOT_FOLDER = "./src/mistapi/"
ROOT_API_FOLDER = "api"
# Type mapping from OpenAPI to Python types
var_translation = {
"integer": "int",
"number": "float",
"string": "str",
"array": "list",
"boolean": "bool",
}
DEPRECATED_METHODS = {
"getSiteSleSummary": {
"new_operation_id": "getSiteSleSummaryTrend",
"version_deprecated": "0.59.2",
"version_final": "0.65.0",
},
"getSiteSleClassifierDetails": {
"new_operation_id": "getSiteSleClassifierSummaryTrend",
"version_deprecated": "0.59.2",
"version_final": "0.65.0",
},
}
# Template for __init__.py files in generated packages
INIT_TEMPLATE = """'''
--------------------------------------------------------------------------------
------------------------- Mist API Python CLI Session --------------------------
Written by: Thomas Munzer (tmunzer@juniper.net)
Github : https://github.com/tmunzer/mistapi_python
This package is licensed under the MIT License.
--------------------------------------------------------------------------------
'''
from {path_import} import (
{function_imports}
)
__all__ = [
{all_imports}
]
"""
# Template for individual Python API files
FILE_TEMPLATE = """'''
--------------------------------------------------------------------------------
------------------------- Mist API Python CLI Session --------------------------
Written by: Thomas Munzer (tmunzer@juniper.net)
Github : https://github.com/tmunzer/mistapi_python
This package is licensed under the MIT License.
--------------------------------------------------------------------------------
'''
{imports}
{functions}
"""
# Template for function docstrings
DESCRIPTION_TEMPLATE = """ \"\"\"
API doc: https://www.juniper.net/documentation/us/en/software/mist/api/http/api/{tags_in_url}/{operation}
PARAMS
-----------
mistapi.APISession : mist_session
mistapi session including authentication and Mist host information
{path_params_desc}{query_params_desc}{body_params_desc}
RETURN
-----------
mistapi.APIResponse
response from the API call
\"\"\"
"""
# Template for deprecated GET functions (backward compatibility)
FUNCTION_GET_DEPRECATED_TEMPLATE = """
@deprecation.deprecated(deprecated_in="{version_deprecated}", removed_in="{version_final}", current_version="{version_current}", details="function replaced with {operation_id}")
def {old_operation_id}(mist_session: _APISession{code_path_params}{code_query_params}) -> _APIResponse:
{code_desc}
uri = {uri}{query_code}
resp = mist_session.mist_get(uri=uri, query=query_params)
return resp
"""
# Template for GET method functions
FUNCTION_GET_TEMPLATE = """
def {operation_id}(mist_session: _APISession{code_path_params}{code_query_params}) -> _APIResponse:
{code_desc}
uri = {uri}{query_code}
resp = mist_session.mist_get(uri=uri, query=query_params)
return resp
"""
# Template for DELETE method functions
FUNCTION_DELETE_TEMPLATE = """
def {operation_id}(mist_session: _APISession{code_path_params}{code_query_params}) -> _APIResponse:
{code_desc}
uri = {uri}{query_code}
resp = mist_session.mist_delete(uri=uri, query=query_params)
return resp
"""
# Template for PUT method functions with JSON body
FUNCTION_PUT_TEMPLATE = """
def {operation_id}(mist_session: _APISession{code_path_params}, body:dict) -> _APIResponse:
{code_desc}
uri = {uri}
resp = mist_session.mist_put(uri=uri, body=body)
return resp
"""
# Template for POST method functions without request body
FUNCTION_POST_EMPTY_TEMPLATE = """
def {operation_id}(mist_session: _APISession{code_path_params}) -> _APIResponse:
{code_desc}
uri = {uri}
resp = mist_session.mist_post(uri=uri)
return resp
"""
# Template for POST method functions with JSON body
FUNCTION_POST_BODY_TEMPLATE = """
def {operation_id}(mist_session: _APISession{code_path_params}, body:dict|list) -> _APIResponse:
{code_desc}
uri = {uri}
resp = mist_session.mist_post(uri=uri, body=body)
return resp
"""
# Template for POST method functions with file upload (multipart/form-data)
FUNCTION_POST_FILE_TEMPLATE = """
def {operation_id}(mist_session: _APISession{code_path_params}{multipart}) -> _APIResponse:
{code_desc}
multipart_form_data = {{{multipart_form_data}
}}
uri = {uri}
resp = mist_session.mist_post_file(uri=uri, multipart_form_data=multipart_form_data)
return resp
"""
def keep_deprecated(max_deprecation_version: str, current_version: str) -> bool:
"""
Determine if deprecated functions should be kept based on version comparison.
"""
current = current_version.split(".")
max_version = max_deprecation_version.split(".")
for i, req in enumerate(max_version):
if current[int(i)] < req:
break
if current[int(i)] > req:
return False
return True
def fprint(message: str) -> None:
"""Print a formatted message with left justification to 80 characters."""
print(f"{message}".ljust(80))
def gen_param(data: dict, openapi_schemas: dict) -> dict:
"""
Generate parameter dictionary from OpenAPI parameter definition.
Args:
data: OpenAPI parameter definition containing name, schema, etc.
openapi_schemas: Dictionary of OpenAPI schema components for resolving references
Returns:
dict: Processed parameter with name, type, description, validation rules, etc.
"""
tmp = {}
if data:
if data["schema"].get("$ref"):
# Handle parameter with schema reference - resolve the reference
ref_name = data["schema"]["$ref"].split("/")[-1:][0]
ref = openapi_schemas.get(ref_name, {})
tmp = {
"name": data["name"].replace(" ", "_").replace("-", "_"),
"required": data.get("required", False),
"enum": ref.get("enum", None),
"type": ref.get("type"),
"description": data.get("description"),
"default": ref.get("default"),
"minimum": ref.get("minimum"),
"maximum": ref.get("maximum"),
}
else:
# Handle inline parameter definition - extract directly from schema
tmp = {
"name": data["name"].replace(" ", "_").replace("-", "_"),
"description": data.get("description"),
"required": data.get("required", False),
"enum": data["schema"].get("enum", None),
"type": data["schema"].get("type"),
"default": data["schema"].get("default"),
"minimum": data["schema"].get("minimum"),
"maximum": data["schema"].get("maximum"),
}
return tmp
##################################
# Folder and file management functions
def _gen_imports(has_deprecated: bool) -> str:
"""
Generate import statements for API function files.
Args:
has_deprecated: Whether the file contains deprecated functions requiring deprecation module
Returns:
str: Import statements for the file
"""
if has_deprecated:
return """from mistapi import APISession as _APISession
from mistapi.__api_response import APIResponse as _APIResponse
import deprecation
"""
return """from mistapi import APISession as _APISession
from mistapi.__api_response import APIResponse as _APIResponse
"""
def _init_folder(folder_path: str, folder_name: str, import_path: list = []) -> None:
"""
Initialize folder structure and create basic __init__.py file if needed.
Args:
folder_path: Parent directory path where folder should be created
folder_name: Name of folder to create
import_path: List of module path components for constructing import statements
"""
path = os.path.join(folder_path, folder_name)
init_file = os.path.join(folder_path, "__init__.py")
if not os.path.exists(path):
os.makedirs(path)
import_from = f"mistapi.{'.'.join(import_path)}"
if import_from.endswith("."):
import_from = import_from[:-1]
if folder_path != ROOT_FOLDER:
# Create basic __init__.py in parent folder if it doesn't exist
if not os.path.exists(init_file):
with open(init_file, "w", encoding="utf-8") as f:
f.write(f"from {import_from} import *\r\n")
def _gen_folder_and_file_paths(endpoint: str) -> tuple[list[str], str]:
"""
Generate folder structure and file name from API endpoint path.
Maps API endpoints to organized Python module structure.
Args:
endpoint: API endpoint path (e.g., "/api/v1/orgs/{org_id}/sites")
Returns:
tuple: (folder_path_parts, file_name) - list of folder names and target file name
"""
endpoint_path = endpoint.split("/")
# Remove empty strings and path variables (e.g., {org_id}) from endpoint
tmp = []
installer = False
for part in endpoint_path:
if part == "installer":
installer = True
if part != "" and not part.startswith("{"):
tmp.append(part)
endpoint_path = tmp
# Determine folder structure based on endpoint depth and special cases
if installer and len(endpoint_path) > 4:
# Special handling for installer endpoints with deeper nesting
folder_path_parts = endpoint_path[0:4]
file_name = endpoint_path[4:5][0]
elif len(endpoint_path) > 3:
# Standard case: use first 3 parts for folders, 4th for file
folder_path_parts = endpoint_path[0:3]
file_name = endpoint_path[3:4][0]
else:
# Shallow endpoints: use available parts for folders, last for file
folder_path_parts = endpoint_path[0:3]
file_name = endpoint_path[2:3][0]
# Special case for 128routers endpoint (renamed for Python compatibility)
if file_name == "128routers":
file_name = "ssr"
return folder_path_parts, file_name
def _init_endpoint(endpoint: str) -> tuple[str, str]:
"""
Initialize complete folder structure and determine file path for an API endpoint.
Args:
endpoint: API endpoint path (e.g., "/api/v1/orgs/{org_id}/sites")
Returns:
tuple: (full_folder_path, file_name) - complete path to target folder and file name
"""
full_folder_path = ROOT_FOLDER
full_import_path: list[str] = []
folder_path_parts, file_name = _gen_folder_and_file_paths(endpoint)
# Create nested folder structure progressively
for folder_path_part in folder_path_parts:
_init_folder(full_folder_path, folder_path_part, full_import_path)
full_folder_path = os.path.join(full_folder_path, folder_path_part)
full_import_path.append(folder_path_part)
return full_folder_path, file_name
##################################
# Function generation utilities
def _gen_code_params_default_value(param: dict) -> str:
"""
Generate default value code for function parameters based on OpenAPI specification.
Args:
param: Parameter definition with type, required flag, and default info
Returns:
str: Code string for default value (e.g., '=None', '="default"', '=True')
"""
code_default = ""
if not param["required"]:
code_default = "|None=None"
# if param.get("default"):
# if param["type"] == "string":
# code_default = f'="{param["default"]}"'
# elif param["type"] == "boolean":
# if param["default"] == "true":
# code_default = "=True"
# else:
# code_default = "=False"
# else:
# code_default = f"={param['default']}"
# else:
# # TODO: Fix union type syntax for Python 3.9 compatibility
# code_default = "|None=None"
# # code_default = "=None"
return code_default
def _gen_code_params(endpoint_params: list, operation_id: str) -> tuple[str, str]:
"""
Generate function parameter code and corresponding documentation.
Args:
endpoint_params: List of parameter definitions from OpenAPI
operation_id: OpenAPI operation ID for error reporting
Returns:
tuple: (code_params, code_params_desc) - parameter signature and documentation
"""
code_params = ""
code_params_desc = ""
for param in endpoint_params:
ptype_src = param["type"]
ptype = var_translation.get(ptype_src, "any")
# Log warning for unknown parameter types
if ptype == "any":
fprint(
f"Unable to convert var type {ptype_src} (opid: {operation_id}, param {param['name']})"
)
# Build parameter signature with type annotations
code_params += f", {param['name']}: {ptype}"
# Build parameter documentation for docstring
code_params_desc += f"\r\n {param['name']} : {ptype}"
if param.get("enum"):
# Format enum values as set notation for documentation
code_params_desc += str(param["enum"]).replace("[", "{").replace("]", "}")
if param.get("default"):
code_params_desc += f", default: {param['default']}"
if param.get("description"):
code_params_desc += f"\r\n {param['description']}"
# Add default value to parameter signature
code_params += _gen_code_params_default_value(param)
return code_params, code_params_desc
def _gen_description_property(property_data: dict) -> tuple[str, str]:
"""
Generate property description for multipart form data documentation.
Args:
property_data: Property definition with type, enum, default, description keys
Returns:
tuple: (property_type, property_desc) - formatted type info and description
"""
property_type = property_data["property_type"]
property_desc = ""
if property_data.get("property_enum"):
# Format enum as set notation for documentation
property_type = (
str(property_data["property_enum"]).replace("[", "{").replace("]", "}")
)
if property_data.get("property_default"):
property_type += f", default: {property_data['property_default']}"
if property_data.get("property_desc"):
property_desc = f"\r\n {property_data['property_desc']}"
return property_type, property_desc
def _process_tags(tags: list) -> str:
"""
Process OpenAPI tags to generate URL path for API documentation links.
Args:
tags: List of OpenAPI tags (usually contains one tag with category info)
Returns:
str: Processed tag path for documentation URL (e.g., "orgs/sites")
"""
result = []
splitted_tag = tags[0].split(" ", 1)
result.append(splitted_tag[0].strip().lower())
if len(splitted_tag) > 1:
# Process subcategories separated by " - "
for subcat in splitted_tag[1].split(" - "):
result.append(subcat.strip().replace(" ", "-").lower())
return "/".join(result)
def _gen_description(
operation_id: str,
tags: list,
desc_path_params: str,
desc_query_params: str = "",
with_body: bool = False,
multipart_form_data: dict = {},
) -> str:
"""
Generate complete function docstring with API documentation link and parameter descriptions.
Args:
operation_id: OpenAPI operation ID for generating documentation URL
tags: OpenAPI tags for categorizing API documentation
desc_path_params: Path parameters documentation string
desc_query_params: Query parameters documentation string
with_body: Whether function accepts JSON body parameter
multipart_form_data: Dictionary of multipart form data parameters
Returns:
str: Complete formatted docstring
"""
# Convert camelCase operation ID to kebab-case URL format
r = "(?<!^)(?=[A-Z])"
operation = re.sub(r, "-", operation_id).lower()
tags_in_url = _process_tags(tags)
path_params_desc = ""
query_params_desc = ""
body_params_desc = ""
# Add path parameters section if present
if desc_path_params:
path_params_desc = f"""
PATH PARAMS
-----------{desc_path_params}
"""
# Add query parameters section if present
if desc_query_params:
query_params_desc = f"""
QUERY PARAMS
------------{desc_query_params}
"""
# Add body parameters section for JSON body or multipart data
if with_body or multipart_form_data:
body_params_desc = """
BODY PARAMS
-----------"""
if with_body:
body_params_desc += "\r\n body : dict\r\n JSON object to send to Mist Cloud (see API doc above for more details)"
# Add multipart form data parameters documentation
if multipart_form_data:
for key in multipart_form_data:
if key in ["csv", "file"]:
# Special handling for file upload parameters
body_params_desc += f"\r\n {key} : {multipart_form_data[key]['property_type']}\r\n path to the file to upload. {multipart_form_data[key]['property_desc']}"
else:
property_type, property_desc = _gen_description_property(
multipart_form_data[key]
)
body_params_desc += (
f"\r\n {key} : {property_type}{property_desc}"
)
# Add nested object properties documentation
if multipart_form_data[key]["property_child"]:
for child in multipart_form_data[key]["property_child"]:
property_type, property_desc = _gen_description_property(
multipart_form_data[key]["property_child"][child]
)
body_params_desc += (
f"\r\n {child} : {property_type}{property_desc}"
)
body_params_desc += """
"""
# Generate complete docstring using template
description = DESCRIPTION_TEMPLATE.format(
tags_in_url=tags_in_url,
operation=operation,
path_params_desc=path_params_desc,
query_params_desc=query_params_desc,
body_params_desc=body_params_desc,
)
return description
def _gen_query_code(query_params: list) -> str:
"""
Generate code for building query parameters dictionary from function arguments.
Args:
query_params: List of query parameter definitions
Returns:
str: Code block for constructing query_params dictionary
"""
code = "\r\n query_params:dict[str, str]={}"
if query_params:
for param in query_params:
# Only add parameter to query dict if it has a value (truthy check)
code += f'\r\n if {param["name"]}:\r\n query_params["{param["name"]}"]=str({param["name"]})'
return code
def _gen_uri(endpoint_path: str) -> str:
"""
Generate URI string for API request, handling path parameter substitution.
Args:
endpoint_path: API endpoint path with possible path variables (e.g., "/api/v1/orgs/{org_id}")
Returns:
str: Formatted URI string (f-string if variables present, regular string otherwise)
"""
if "{" in endpoint_path:
# Use f-string for path parameter substitution
return f'f"{endpoint_path}"'
# Use regular string for static paths
return f'"{endpoint_path}"'
########
# HTTP method function generators (CRUD operations)
def _create_get_deprecated(
operation_id: str,
tags: list,
new_operation_id: str,
version_deprecated: str,
version_final: str,
endpoint_path: str,
path_params: list,
query_params: list,
) -> str:
"""
Create deprecated version of GET functions for backward compatibility.
Args:
operation_id: Current OpenAPI operation ID (DeviceEvents*)
endpoint_path: API endpoint path
path_params: Path parameters list
query_params: Query parameters list
Returns:
str: Generated deprecated function code
"""
code = ""
if not keep_deprecated(version_final, VERSION):
print(f"Skipping deprecated function {operation_id} as per version settings.")
return code
code_path_params, desc_path_params = _gen_code_params(path_params, operation_id)
code_query_params, desc_query_params = _gen_code_params(query_params, operation_id)
code_query = _gen_query_code(query_params)
code_desc = _gen_description(
operation_id, tags, desc_path_params, desc_query_params
)
# Generate old operation ID for the deprecated function
code += FUNCTION_GET_DEPRECATED_TEMPLATE.format(
version_deprecated=version_deprecated,
version_final=version_final,
version_current=VERSION,
operation_id=new_operation_id,
old_operation_id=operation_id,
code_path_params=code_path_params,
code_query_params=code_query_params,
code_desc=code_desc,
uri=_gen_uri(endpoint_path),
query_code=code_query,
)
return code
def _create_get(
operation_id: str,
tags: list,
endpoint_path: str,
path_params: list,
query_params: list,
) -> tuple[str, bool]:
"""
Generate GET method function with optional deprecated version for compatibility.
Args:
operation_id: OpenAPI operation ID
tags: OpenAPI tags for documentation
endpoint_path: API endpoint path
path_params: Path parameters list
query_params: Query parameters list
Returns:
tuple: (generated_code, has_deprecated_function)
"""
code = ""
has_deprecated = False
if DEPRECATED_METHODS.get(operation_id):
code += _create_get_deprecated(
operation_id,
tags,
DEPRECATED_METHODS[operation_id]["new_operation_id"],
DEPRECATED_METHODS[operation_id]["version_deprecated"],
DEPRECATED_METHODS[operation_id]["version_final"],
endpoint_path,
path_params,
query_params,
)
if code:
has_deprecated = True
else:
# Generate main function parameters and documentation
code_path_params, desc_path_params = _gen_code_params(path_params, operation_id)
code_query_params, desc_query_params = _gen_code_params(
query_params, operation_id
)
code_query = _gen_query_code(query_params)
code_desc = _gen_description(
operation_id, tags, desc_path_params, desc_query_params
)
# Generate main GET function code
code += FUNCTION_GET_TEMPLATE.format(
operation_id=operation_id,
code_path_params=code_path_params,
code_query_params=code_query_params,
code_desc=code_desc,
uri=_gen_uri(endpoint_path),
query_code=code_query,
)
return code, has_deprecated
def _create_delete(
operation_id: str,
tags: list,
endpoint_path: str,
path_params: list,
query_params: list,
) -> str:
"""
Generate DELETE method function.
Args:
operation_id: OpenAPI operation ID
tags: OpenAPI tags for documentation
endpoint_path: API endpoint path
path_params: Path parameters list
query_params: Query parameters list
Returns:
str: Generated DELETE function code
"""
code = ""
code_path_params, desc_path_params = _gen_code_params(path_params, operation_id)
code_query_params, desc_query_params = _gen_code_params(query_params, operation_id)
code_query = _gen_query_code(query_params)
code_desc = _gen_description(
operation_id, tags, desc_path_params, desc_query_params
)
code += FUNCTION_DELETE_TEMPLATE.format(
operation_id=operation_id,
code_path_params=code_path_params,
code_query_params=code_query_params,
code_desc=code_desc,
uri=_gen_uri(endpoint_path),
query_code=code_query,
)
return code
def _create_post_empty(
operation_id: str,
tags: list,
endpoint_path: str,
path_params: list,
) -> str:
"""
Generate POST method function without request body (empty POST).
Args:
operation_id: OpenAPI operation ID
tags: OpenAPI tags for documentation
endpoint_path: API endpoint path
path_params: Path parameters list
Returns:
str: Generated POST function code
"""
code = ""
code_path_params, desc_path_params = _gen_code_params(path_params, operation_id)
code_desc = _gen_description(operation_id, tags, desc_path_params)
code += FUNCTION_POST_EMPTY_TEMPLATE.format(
operation_id=operation_id,
code_path_params=code_path_params,
code_desc=code_desc,
uri=_gen_uri(endpoint_path),
)
return code
def _create_post(
operation_id: str,
tags: list,
endpoint_path: str,
path_params: list,
) -> str:
"""
Generate POST method function with JSON request body.
Args:
operation_id: OpenAPI operation ID
tags: OpenAPI tags for documentation
endpoint_path: API endpoint path
path_params: Path parameters list
Returns:
str: Generated POST function code
"""
code = ""
code_path_params, desc_path_params = _gen_code_params(path_params, operation_id)
code_desc = _gen_description(operation_id, tags, desc_path_params, with_body=True)
code += FUNCTION_POST_BODY_TEMPLATE.format(
operation_id=operation_id,
code_path_params=code_path_params,
code_desc=code_desc,
uri=_gen_uri(endpoint_path),
)
return code
def _process_multipart_json(properties: dict) -> dict:
"""
Process multipart form data properties into structured format for code generation.
Recursively handles nested object properties.
Args:
properties: OpenAPI schema properties for multipart data
Returns:
dict: Processed multipart form data structure with type info and descriptions
"""
multipart_form_data = {}
for key in properties:
property_type = "dict" # Default type
property_default = properties[key].get("default", None)
property_enum = properties[key].get("enum", None)
property_child = None
# Map OpenAPI types to Python types
match properties[key].get("type"):
case "boolean":
property_type = "bool"
case "string":
property_type = "str"
case "integer":
property_type = "int"
case "number":
property_type = "float"
case "array":
property_type = "list"
case "binary":
property_type = "str" # File paths are strings
case "object":
property_type = "dict"
# Recursively process nested object properties
if properties[key].get("properties"):
property_child = _process_multipart_json(
properties[key]["properties"]
)
multipart_form_data[key] = {
"property_type": property_type,
"property_desc": properties[key].get("description", ""),
"property_default": property_default,
"property_enum": property_enum,
"property_child": property_child,
}
return multipart_form_data
def _create_post_file(
operation_id: str,
tags: list,
endpoint_path: str,
path_params: list,
properties: dict,
) -> str:
"""
Generate POST method function for file uploads using multipart/form-data.
Args:
operation_id: OpenAPI operation ID
tags: OpenAPI tags for documentation
endpoint_path: API endpoint path
path_params: Path parameters list
properties: Multipart form properties from OpenAPI schema
Returns:
str: Generated POST file upload function code
"""
code = ""
code_path_params, desc_path_params = _gen_code_params(path_params, operation_id)
multipart_form_data_parameters = _process_multipart_json(properties)
code_desc = _gen_description(
operation_id,
tags,
desc_path_params,
multipart_form_data=multipart_form_data_parameters,
)
# Build function signature with multipart parameters
multipart = ""
for key, value in multipart_form_data_parameters.items():
multipart += f", {key}:{value['property_type']}|None=None"
# Build multipart form data dictionary for function body
multipart_form_data = ""
for key in multipart_form_data_parameters:
multipart_form_data += f"""
"{key}":{key},"""
code += FUNCTION_POST_FILE_TEMPLATE.format(
operation_id=f"{operation_id}File", # Append "File" to distinguish from regular POST
code_path_params=code_path_params,
code_desc=code_desc,
multipart=multipart,
multipart_form_data=multipart_form_data,
uri=_gen_uri(endpoint_path),
)
return code
def _create_put(
operation_id: str,
tags: list,
endpoint_path: str,
path_params: list,
) -> str:
"""
Generate PUT method function with JSON request body.
Args:
operation_id: OpenAPI operation ID
tags: OpenAPI tags for documentation
endpoint_path: API endpoint path
path_params: Path parameters list
Returns:
str: Generated PUT function code
"""
code = ""
code_path_params, desc_path_params = _gen_code_params(path_params, operation_id)
code_desc = _gen_description(operation_id, tags, desc_path_params, with_body=True)
code += FUNCTION_PUT_TEMPLATE.format(
operation_id=operation_id,
code_path_params=code_path_params,
code_desc=code_desc,
uri=_gen_uri(endpoint_path),
query_code="",
)
return code
########
# Parameter processing functions
def _process_path_params(
endpoint_params: dict, openapi_refs: dict, openapi_schemas: dict
) -> list:
"""
Process path parameters from OpenAPI endpoint definition.
Handles both direct parameter definitions and parameter references.
Args:
endpoint_params: List of OpenAPI parameter objects
openapi_refs: Dictionary of reusable parameter components
openapi_schemas: Dictionary of schema components for resolving references
Returns:
list: Processed path parameters with resolved types and validation rules
"""
params = []
for parameter in endpoint_params:
if parameter.get("$ref"):
# Handle parameter reference - resolve from components
ref_name = parameter["$ref"].split("/")[-1:][0]
data = openapi_refs.get(ref_name, {})
tmp_param = gen_param(data, openapi_schemas)
else:
# Handle inline parameter definition
tmp_param = gen_param(parameter, openapi_schemas)
# Avoid duplicate parameters
if tmp_param not in params:
params.append(tmp_param)
return params
def _process_query_params(
endpoint_params: dict, openapi_refs: dict, openapi_schemas: dict
) -> list:
"""
Process query parameters from OpenAPI endpoint definition.
Handles both direct parameter definitions and parameter references.
Args:
endpoint_params: List of OpenAPI parameter objects
openapi_refs: Dictionary of reusable parameter components
openapi_schemas: Dictionary of schema components for resolving references
Returns:
list: Processed query parameters with resolved types and validation rules
"""
params = []
for parameter in endpoint_params:
if parameter.get("$ref"):
# Handle parameter reference - resolve from components
ref_name = parameter["$ref"].split("/")[-1:][0]
data = openapi_refs.get(ref_name, {})
tmp_param = gen_param(data, openapi_schemas)
else:
# Handle inline parameter definition
tmp_param = gen_param(parameter, openapi_schemas)
# Avoid duplicate parameters
if tmp_param not in params:
params.append(tmp_param)