Created
May 29, 2023 03:07
-
-
Save MattHealy/cd27fedf6190c1b7c7bf639701be56a8 to your computer and use it in GitHub Desktop.
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 boto3 | |
import csv | |
import calendar | |
from datetime import date, datetime, timedelta | |
from collections import OrderedDict | |
client = boto3.client('apigateway') | |
endDate = date(year=2023, month=3, day=31) | |
startDate = date(year=2022, month=3, day=1) | |
months = OrderedDict(((startDate + timedelta(_)).strftime("%Y-%m-01"), 0) for _ in range((endDate - startDate).days)) | |
with open('api-gateway-usage.csv', 'w', newline='') as writecsvfile: | |
fieldnames = ['Name', 'Daily Quota'] | |
writer = csv.DictWriter( | |
writecsvfile, fieldnames=fieldnames, quoting=csv.QUOTE_ALL) | |
for m in months: | |
print(m) | |
fieldnames.append(m) | |
print(fieldnames) | |
writer.writeheader() | |
response = client.get_usage_plans() | |
for i in response['items']: | |
quota = None | |
if 'quota' in i: | |
quota = i['quota']['limit'] | |
keys = [] | |
pagesize = 100 | |
position = None | |
while (True): | |
args = {"usagePlanId": i['id'], "limit": pagesize} | |
if position: | |
args['position'] = position | |
response2 = client.get_usage_plan_keys(**args) | |
for k in response2['items']: | |
keys.append(k) | |
if 'position' in response2: | |
position = response2['position'] | |
else: | |
break | |
for k in keys: | |
row = { | |
'Name': k['name'], | |
'Daily Quota': quota, | |
} | |
for m in months: | |
tempStart = datetime.strptime(m, '%Y-%m-%d').date() | |
tempEnd = tempStart.replace(day=calendar.monthrange(tempStart.year, tempStart.month)[1]) | |
response3 = client.get_usage( | |
usagePlanId=i['id'], | |
keyId=k['id'], | |
startDate=tempStart.strftime('%Y-%m-%d'), | |
endDate=tempEnd.strftime('%Y-%m-%d'), | |
) | |
print("range: {} to {}".format(tempStart.strftime('%Y-%m-%d'), tempEnd.strftime('%Y-%m-%d'))) | |
totalCalls = 0 | |
for u in response3['items']: | |
usage = response3['items'][u] | |
for day in usage: | |
totalCalls += day[0] | |
print("{} = {}".format(m, totalCalls)) | |
row[m] = totalCalls | |
print(row) | |
writer.writerow(row) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment