Skip to content

Instantly share code, notes, and snippets.

@nullenc0de
Created September 23, 2024 18:12
Show Gist options
  • Select an option

  • Save nullenc0de/644c78a217b43fa7537090f38e67b8d5 to your computer and use it in GitHub Desktop.

Select an option

Save nullenc0de/644c78a217b43fa7537090f38e67b8d5 to your computer and use it in GitHub Desktop.
import json
import sys
from collections import Counter
def analyze_openapi_spec(spec):
endpoint_count = 0
request_count = 0
endpoints = []
method_counts = Counter()
parameter_counts = Counter()
response_code_counts = Counter()
tags = set()
if 'paths' in spec:
for path, methods in spec['paths'].items():
endpoint_count += 1
for method, details in methods.items():
if method.lower() in ['get', 'post', 'put', 'delete', 'patch', 'options', 'head']:
request_count += 1
method_counts[method.upper()] += 1
# Analyze parameters
params = details.get('parameters', [])
for param in params:
param_in = param.get('in', 'unknown')
parameter_counts[param_in] += 1
# Analyze request body
if 'requestBody' in details:
parameter_counts['body'] += 1
# Analyze responses
responses = details.get('responses', {})
for response_code in responses:
response_code_counts[response_code] += 1
# Collect tags
tags.update(details.get('tags', []))
endpoints.append({
'method': method.upper(),
'path': path,
'summary': details.get('summary', 'No summary provided'),
'operationId': details.get('operationId', 'No operationId provided'),
'tags': details.get('tags', []),
'parameters': len(params),
'hasRequestBody': 'requestBody' in details,
'responseCodes': list(responses.keys())
})
return {
'endpoint_count': endpoint_count,
'request_count': request_count,
'method_counts': dict(method_counts),
'parameter_counts': dict(parameter_counts),
'response_code_counts': dict(response_code_counts),
'tags': list(tags),
'endpoints': endpoints
}
def main(file_path):
try:
with open(file_path, 'r') as file:
spec_json = file.read()
spec = json.loads(spec_json)
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
return
except json.JSONDecodeError:
print("Error: Invalid JSON in the provided file.")
return
analysis = analyze_openapi_spec(spec)
print(f"Number of endpoints: {analysis['endpoint_count']}")
print(f"Number of possible requests: {analysis['request_count']}")
print(f"\nHTTP Method distribution:")
for method, count in analysis['method_counts'].items():
print(f" {method}: {count}")
print(f"\nParameter types:")
for param_type, count in analysis['parameter_counts'].items():
print(f" {param_type}: {count}")
print(f"\nResponse codes used:")
for code, count in analysis['response_code_counts'].items():
print(f" {code}: {count}")
print(f"\nTags used: {', '.join(analysis['tags'])}")
print("\nEndpoint details:")
for endpoint in analysis['endpoints']:
print(f"{endpoint['method']} {endpoint['path']}")
print(f" Summary: {endpoint['summary']}")
print(f" OperationId: {endpoint['operationId']}")
print(f" Tags: {', '.join(endpoint['tags'])}")
print(f" Parameters: {endpoint['parameters']}")
print(f" Has Request Body: {endpoint['hasRequestBody']}")
print(f" Response Codes: {', '.join(endpoint['responseCodes'])}")
print()
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python openapi_analyzer.py <path_to_openapi_spec.json>")
else:
main(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment