├── .github └── workflows │ └── publish-to-pypi.yml ├── .gitignore ├── LICENSE ├── README.md ├── requirements.txt ├── setup.py ├── swagroutes ├── __init__.py ├── __main__.py ├── cli.py └── extractor.py └── tests ├── __init__.py └── test_extractor.py /.github/workflows/publish-to-pypi.yml: -------------------------------------------------------------------------------- 1 | name: Publish Python Package to PyPI 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | jobs: 8 | deploy: 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | 13 | - name: Checkout repository 14 | uses: actions/checkout@v2 15 | 16 | - name: Print working directory and its contents 17 | run: | 18 | pwd 19 | ls -la 20 | tree 21 | 22 | - name: Print swagroutes/__init__.py content 23 | run: cat swagroutes/__init__.py 24 | 25 | - name: Set up Python 26 | uses: actions/setup-python@v2 27 | with: 28 | python-version: 3.x 29 | 30 | - name: Install dependencies 31 | run: | 32 | python -m pip install --upgrade pip 33 | pip install build 34 | - name: Print swagroutes version 35 | run: | 36 | python -c "import swagroutes; print('swagroutes version:', swagroutes.__version__)" 37 | 38 | - name: Build package 39 | run: python -m build 40 | 41 | - name: Publish package 42 | uses: pypa/gh-action-pypi-publish@v1.4.2 43 | with: 44 | user: __token__ 45 | password: ${{ secrets.PYPI_API_TOKEN }} 46 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Amal Murali 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # swagroutes 2 | 3 | swagroutes is a command-line tool that extracts and lists API routes from Swagger files in YAML or JSON format. It simplifies the process of fetching the routes provided by an API and supports processing multiple files or directories at once. 4 | 5 | ![](https://user-images.githubusercontent.com/3582096/233068257-29adfadd-8cd3-45fd-9d1d-f22a9772d139.png) 6 | 7 | ## Install 8 | 9 | ```bash 10 | pip install swagroutes 11 | ``` 12 | 13 | ## Upgrade 14 | ```bash 15 | pip install -U swagroutes 16 | ``` 17 | 18 | ## Help 19 | ``` 20 | usage: swagroutes [-h] [-o OUTPUT] [-p] input [input ...] 21 | 22 | Extract routes from Swagger files. 23 | 24 | positional arguments: 25 | input Input file(s) or directory containing Swagger files. 26 | 27 | options: 28 | -h, --help show this help message and exit 29 | -o OUTPUT, --output OUTPUT 30 | Output file to store the results. 31 | -p, --include-params Include query parameters in the extracted routes. 32 | ``` 33 | 34 | ## Usage 35 | To use swagroutes, simply provide input files or directories containing Swagger files as arguments. The tool will process the files and print the extracted routes. 36 | 37 | #### Single YAML or JSON file 38 | ```bash 39 | swagroutes file.yaml 40 | ``` 41 | 42 | ```bash 43 | swagroutes file.json 44 | ``` 45 | 46 | #### Multiple YAML and/or JSON files 47 | 48 | ```bash 49 | swagroutes file1.yaml file2.json 50 | ``` 51 | 52 | #### Directory containing Swagger files 53 | ```bash 54 | swagroutes directory/ 55 | ``` 56 | 57 | #### Mix of files and directories 58 | ```bash 59 | swagroutes file1.yaml directory1/ file2.json directory2/ 60 | ``` 61 | 62 | #### Extract parameters 63 | ```bash 64 | swagroutes file1.yaml --include-params 65 | ``` 66 | 67 | #### Output to a file 68 | Save the extracted routes to an output file using the `-o` or `--output` option: 69 | 70 | ```bash 71 | swagroutes file.yaml -o output.txt 72 | ``` 73 | 74 | 75 | ## Examples 76 | 77 | **Input:** 78 | ```yaml 79 | basePath: /api 80 | paths: 81 | /users: 82 | get: {} 83 | post: {} 84 | /profile/{profile_id}: 85 | put: {} 86 | ``` 87 | 88 | **Output:** 89 | 90 | ``` 91 | GET /api/users 92 | POST /api/users 93 | PUT /api/profile/{profile_id} 94 | ``` 95 | 96 | --- 97 | 98 | **Input:** 99 | ```yaml 100 | basePath: /api/v1 101 | paths: 102 | /users: 103 | get: 104 | parameters: 105 | - name: limit 106 | in: query 107 | - name: offset 108 | in: query 109 | 110 | /users/{userId}: 111 | get: 112 | parameters: 113 | - name: userId 114 | in: path 115 | required: true 116 | type: string 117 | ``` 118 | 119 | **Output:** 120 | ``` 121 | GET /api/v1/users/{userId} 122 | GET /api/v1/users?limit&offset 123 | ``` -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | PyYAML 2 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | import subprocess 3 | import os 4 | 5 | 6 | with open("README.md", "r", encoding="utf-8") as fh: 7 | long_description = fh.read() 8 | 9 | 10 | def main(): 11 | import swagroutes 12 | setuptools.setup( 13 | name="swagroutes", 14 | version=swagroutes.__version__, 15 | author="Amal Murali", 16 | author_email="amalmurali47@gmail.com", 17 | description="Command-line tool that extracts and lists API routes from Swagger files in YAML or JSON format.", 18 | long_description=long_description, 19 | long_description_content_type="text/markdown", 20 | url="https://github.com/amalmurali47/swagroutes", 21 | packages=setuptools.find_packages(), 22 | package_data={"swagroutes": ["VERSION"]}, 23 | include_package_data=True, 24 | classifiers=[ 25 | "Programming Language :: Python :: 3", 26 | "License :: OSI Approved :: MIT License", 27 | "Operating System :: OS Independent", 28 | ], 29 | python_requires=">=3.6", 30 | entry_points={"console_scripts": ["swagroutes = swagroutes.__main__:main"]}, 31 | install_requires=[ 32 | "PyYAML >= 6.0", 33 | ] 34 | ) 35 | 36 | if __name__ == '__main__': 37 | main() 38 | 39 | -------------------------------------------------------------------------------- /swagroutes/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = "1.0.2" 2 | 3 | -------------------------------------------------------------------------------- /swagroutes/__main__.py: -------------------------------------------------------------------------------- 1 | from .cli import main 2 | 3 | if __name__ == "__main__": 4 | main() 5 | 6 | -------------------------------------------------------------------------------- /swagroutes/cli.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | from pathlib import Path 3 | from .extractor import process_swagger_files 4 | 5 | 6 | def main(): 7 | parser = argparse.ArgumentParser(description='Extract routes from Swagger files.') 8 | parser.add_argument('input', metavar='input', type=str, nargs='+', help='Input file(s) or directory containing Swagger files.') 9 | parser.add_argument('-o', '--output', type=str, help='Output file to store the results.') 10 | parser.add_argument('-p', '--include-params', action='store_true', help='Include query parameters in the extracted routes.') 11 | 12 | args = parser.parse_args() 13 | 14 | input_files = [] 15 | 16 | for input_path in args.input: 17 | path = Path(input_path) 18 | if path.is_file(): 19 | input_files.append(path) 20 | elif path.is_dir(): 21 | input_files.extend(path.glob('**/*.yaml')) 22 | input_files.extend(path.glob('**/*.json')) 23 | 24 | all_routes = process_swagger_files(input_files, args.include_params) 25 | 26 | if args.output: 27 | with open(args.output, 'w') as outfile: 28 | outfile.write('\n'.join(all_routes)) 29 | else: 30 | for route in all_routes: 31 | print(route) 32 | 33 | -------------------------------------------------------------------------------- /swagroutes/extractor.py: -------------------------------------------------------------------------------- 1 | import yaml 2 | import json 3 | from pathlib import Path 4 | 5 | 6 | def load_yaml_file(file_path): 7 | with open(file_path, 'r') as file: 8 | return yaml.safe_load(file) 9 | 10 | 11 | def load_json_file(file_path): 12 | with open(file_path, 'r') as file: 13 | return json.load(file) 14 | 15 | 16 | def extract_routes(swagger_data, include_params=False): 17 | routes = set() 18 | base_path = swagger_data.get('basePath', '') 19 | paths = swagger_data.get('paths', {}) 20 | 21 | http_methods = {'get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'} 22 | 23 | for path, methods in paths.items(): 24 | for method, details in methods.items(): 25 | if method.lower() in http_methods: 26 | route = f'{method.upper()} {base_path}{path}' 27 | if include_params: 28 | parameters = details.get('parameters', []) 29 | query_params = [param['name'] for param in parameters if param['in'] == 'query'] 30 | if query_params: 31 | route += '?' + '&'.join(query_params) 32 | routes.add(route) 33 | 34 | return routes 35 | 36 | 37 | def process_swagger_files(files, include_params=False): 38 | all_routes = set() 39 | 40 | for file in files: 41 | file_extension = file.suffix.lower() 42 | if file_extension == '.yaml': 43 | swagger_data = load_yaml_file(file) 44 | elif file_extension == '.json': 45 | swagger_data = load_json_file(file) 46 | else: 47 | continue 48 | routes = extract_routes(swagger_data, include_params) 49 | all_routes.update(routes) 50 | 51 | return all_routes 52 | 53 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /tests/test_extractor.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from swagroutes.extractor import extract_routes 3 | 4 | 5 | class TestExtractor(unittest.TestCase): 6 | def test_extract_routes(self): 7 | swagger_data = { 8 | "basePath": "/api", 9 | "paths": { 10 | "/users": { 11 | "get": {}, 12 | "post": {} 13 | }, 14 | "/profile/{profile_id}": { 15 | "put": {} 16 | } 17 | } 18 | } 19 | expected_output = { 20 | "GET /api/users", 21 | "POST /api/users", 22 | "PUT /api/profile/{profile_id}" 23 | } 24 | routes = extract_routes(swagger_data) 25 | self.assertEqual(expected_output, routes) 26 | 27 | def test_extract_routes_with_parameters(self): 28 | swagger_data = { 29 | "basePath": "/api", 30 | "paths": { 31 | "/users": { 32 | "get": { 33 | "parameters": [ 34 | { 35 | "name": "limit", 36 | "in": "query", 37 | "type": "integer" 38 | }, 39 | { 40 | "name": "offset", 41 | "in": "query", 42 | "type": "integer" 43 | } 44 | ] 45 | } 46 | } 47 | } 48 | } 49 | expected_output_without_params = { 50 | "GET /api/users" 51 | } 52 | routes_without_params = extract_routes(swagger_data, include_params=False) 53 | self.assertEqual(expected_output_without_params, routes_without_params) 54 | 55 | expected_output_with_params = { 56 | "GET /api/users?limit&offset" 57 | } 58 | routes_with_params = extract_routes(swagger_data, include_params=True) 59 | self.assertEqual(expected_output_with_params, routes_with_params) 60 | 61 | 62 | if __name__ == "__main__": 63 | unittest.main() 64 | 65 | --------------------------------------------------------------------------------