Created
February 6, 2025 22:23
-
-
Save joelduvall/0cf5adceaad2737dc734028a4d7cdbc1 to your computer and use it in GitHub Desktop.
Swagger2.0ToJson
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import yaml | |
import json | |
# Load the Swagger YAML file | |
def load_swagger_yaml(file_path): | |
with open(file_path, 'r', encoding='utf-8') as file: | |
return yaml.safe_load(file) | |
# Extract operations into a custom JSON structure | |
def extract_operations(swagger_data): | |
operations = [] | |
if 'paths' not in swagger_data: | |
return operations # No paths defined | |
for path, methods in swagger_data['paths'].items(): | |
for method, details in methods.items(): | |
if method not in ["get", "post", "put", "delete", "patch", "options", "head"]: | |
continue # Skip invalid methods | |
operation = { | |
"path": path, | |
"method": method.upper(), | |
"summary": details.get("summary", ""), | |
"description": details.get("description", ""), | |
"parameters": details.get("parameters", []), | |
"responses": details.get("responses", {}), | |
"tags": details.get("tags", []) | |
} | |
operations.append(operation) | |
return operations | |
# Convert to JSON format | |
def generate_json_output(operations, output_file): | |
with open(output_file, 'w', encoding='utf-8') as file: | |
json.dump(operations, file, indent=4) | |
# Example usage | |
swagger_file = "swagger.yaml" # Path to your Swagger 2.0 YAML file | |
output_json_file = "swagger_operations.json" | |
swagger_data = load_swagger_yaml(swagger_file) | |
operations_json = extract_operations(swagger_data) | |
generate_json_output(operations_json, output_json_file) | |
print(f"JSON file generated: {output_json_file}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment