Created
January 30, 2024 14:55
-
-
Save joeke80215/47b42793f0ba0b8ea6092d33db7499ac to your computer and use it in GitHub Desktop.
This Python script is designed to split a large Swagger YAML file into smaller OpenAPI 3.0.0 files based on tags.
This file contains hidden or 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 os | |
import argparse | |
def split_yaml_file_by_tag(file_path, output_dir, server_url): | |
with open(file_path, 'r', encoding='utf-8') as file: | |
data = yaml.safe_load(file) | |
openapi_version = '3.0.0' # OpenAPI version | |
info = data.get('info', {}) | |
common_components = data.get('components', {}) | |
if not os.path.exists(output_dir): | |
os.makedirs(output_dir) | |
tag_paths = {} | |
for path, path_data in data.get('paths', {}).items(): | |
for operation in path_data.values(): | |
tags = operation.get('tags', ['untagged']) | |
for tag in tags: | |
if tag not in tag_paths: | |
tag_paths[tag] = {} | |
tag_paths[tag][path] = path_data | |
for tag, paths in tag_paths.items(): | |
new_data = { | |
'openapi': openapi_version, | |
'info': info, | |
'servers': [{'url': server_url, 'description': 'API server'}], | |
'paths': paths, | |
'components': common_components | |
} | |
output_file = os.path.join(output_dir, f'{tag}.yaml') | |
with open(output_file, 'w', encoding='utf-8') as file: | |
yaml.dump(new_data, file, allow_unicode=True) | |
def main(): | |
parser = argparse.ArgumentParser( | |
description='Split a large Swagger YAML file into smaller OpenAPI 3.0.0 files by tag.') | |
parser.add_argument('input_file', type=str, help='Path to the large Swagger YAML file') | |
parser.add_argument('output_dir', type=str, help='Directory to store the output smaller YAML files') | |
parser.add_argument('server_url', type=str, help='The base URL for the API server') | |
args = parser.parse_args() | |
split_yaml_file_by_tag(args.input_file, args.output_dir, args.server_url) | |
if __name__ == "__main__": | |
main() | |
# python split_swagger.py path_to_your_large_swagger_file.yaml output_directory_by_tag http://localhost:8080 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment