Last active
June 16, 2022 01:20
-
-
Save jweyrich/3f0d9977346e7eec31fd79a19d035972 to your computer and use it in GitHub Desktop.
Python3 script to list all API and their endpoints that are currently deployed to the AWS API Gateway
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
#!/usr/bin/env python3 | |
# | |
# Author: Jardel Weyrich <jweyrich at gmail dot com> | |
# | |
# How to run: | |
# aws-vault exec <profile> -- python3 aws-apigw-list-endpoints.py | |
# | |
import boto3 | |
import os | |
def get_account_id(): | |
client = boto3.client('sts') | |
response = client.get_caller_identity() | |
return response.get('Account') | |
# Returns a list of all APIs | |
def get_apis(): | |
client = boto3.client('apigateway') | |
paginator = client.get_paginator('get_rest_apis') | |
pages = paginator.paginate() | |
result = [] | |
for page in pages: | |
# response = client.get_rest_apis() | |
result += [{'id': it.get('id'), 'name': it.get('name')} for it in page.get('items')] | |
return result | |
# Returns a list of ENDPOINTS for the given API | |
def get_endpoints_for_api(api_id: str): | |
client = boto3.client('apigateway') | |
paginator = client.get_paginator('get_resources') | |
pages = paginator.paginate(restApiId=api_id) | |
result = [] | |
for page in pages: | |
for it in page.get('items'): | |
path = it.get('path') | |
all_methods_dict = it.get('resourceMethods') | |
# Discard resources that don't have resourceMethods. | |
if not all_methods_dict: | |
continue | |
all_methods = [key for key, _ in all_methods_dict.items()] | |
filtered_methods = filter(lambda method: method != 'OPTIONS', all_methods) | |
partial_endpoints = map(lambda method: {'method': method, 'path': path}, filtered_methods) | |
result += partial_endpoints | |
return result | |
def main(): | |
region = os.environ.get('AWS_REGION', 'us-east-1') | |
account_id = get_account_id() | |
print(f'REGION={region}, ACCOUNT={account_id}') | |
print() | |
apis = get_apis() | |
total_apis = len(apis) | |
total_endpoints = 0 | |
for api in apis: | |
api_id = api['id'] | |
api_name = api['name'] | |
endpoints = get_endpoints_for_api(api_id=api_id) | |
total_endpoints += len(endpoints) | |
print(f'{api_name} ({len(endpoints)} endpoints)') | |
for endpoint in endpoints: | |
endpoint_method = endpoint['method'] | |
endpoint_path = endpoint['path'] | |
print(f' {endpoint_method} {endpoint_path}') | |
print() | |
print(f'TOTAL_APIS={total_apis}') | |
print(f'TOTAL_ENDPOINTS={total_endpoints}') | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment