-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse_openapi.py
More file actions
119 lines (95 loc) · 4.24 KB
/
parse_openapi.py
File metadata and controls
119 lines (95 loc) · 4.24 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
import json
import logging
def _parse_method_details(method_details):
"""Parse details for a single HTTP method."""
method_data = {
"tags": method_details.get("tags", []),
"summary": method_details.get("summary"),
"operationId": method_details.get("operationId"),
"parameters": [],
"responses": {}
}
# Parse parameters
if "parameters" in method_details and isinstance(method_details["parameters"], list):
for param in method_details["parameters"]:
method_data["parameters"].append({
"name": param.get("name"),
"in": param.get("in"),
"required": param.get("required"),
"schema": param.get("schema")
})
# Parse responses
if "responses" in method_details and isinstance(method_details["responses"], dict):
for status_code, response_details in method_details["responses"].items():
method_data["responses"][status_code] = {
"description": response_details.get("description"),
"content": response_details.get("content", {}).get("application/json", {}).get("schema")
}
return method_data
def _parse_paths(spec):
"""Parse paths section of OpenAPI spec."""
paths_data = {}
if "paths" not in spec or not isinstance(spec["paths"], dict):
print("Warning: 'paths' attribute not found or is not a dictionary in the OpenAPI spec.")
return paths_data
for path_string, path_item in spec["paths"].items():
paths_data[path_string] = {}
for method, method_details in path_item.items():
if method.upper() in ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"]:
paths_data[path_string][method.upper()] = _parse_method_details(method_details)
return paths_data
def _parse_schemas(spec):
"""Parse component schemas section of OpenAPI spec."""
components_schemas_data = {}
if ("components" in spec and
"schemas" in spec["components"] and
isinstance(spec["components"]["schemas"], dict)):
for schema_name, schema_details in spec["components"]["schemas"].items():
components_schemas_data[schema_name] = schema_details
else:
print("Warning: 'components.schemas' attribute not found or is not a dictionary in the OpenAPI spec.")
return components_schemas_data
def parse_openapi_spec(spec_content):
"""
Parses the OpenAPI specification and extracts relevant information.
Args:
spec_content (str): The string content of the openapi_spec.json file.
Returns:
tuple: A tuple containing two dictionaries:
- paths_data: Information about each path and its methods.
- components_schemas_data: Information about component schemas.
"""
try:
spec = json.loads(spec_content)
except json.JSONDecodeError as e:
logging.error(f"Error decoding JSON: {e}")
raise ValueError(f"Failed to parse OpenAPI spec: {e}")
paths_data = _parse_paths(spec)
components_schemas_data = _parse_schemas(spec)
return paths_data, components_schemas_data
if __name__ == "__main__":
try:
with open("openapi_spec.json", "r") as f:
openapi_content = f.read()
except FileNotFoundError:
print("Error: openapi_spec.json not found.")
exit(1)
except IOError as e:
print(f"Error reading openapi_spec.json: {e}")
exit(1)
parsed_paths, parsed_schemas = parse_openapi_spec(openapi_content)
if parsed_paths is not None and parsed_schemas is not None:
# You can optionally print or process the extracted data here
# For now, just acknowledge completion as per the task requirement.
print("OpenAPI specification parsed successfully.")
# Example: Print all paths
# print("\nPaths:")
# for path, methods in parsed_paths.items():
# print(f" {path}: {list(methods.keys())}")
#
# Example: Print all component schema names
# print("\nComponent Schemas:")
# for schema_name in parsed_schemas.keys():
# print(f" {schema_name}")
else:
print("OpenAPI specification parsing failed.")