DEV Community

Christoffer Lybekk
Christoffer Lybekk

Posted on

How to: Get Netlify Bandwith Usage Programatically For Free

Using Python

Explanation

In the script below, replace the following variable's values

Setting Explanation
ACCOUNT_NAME The account name associated with the account.
SITE_NAME The site name can be found in 'Site information' in the project's settings, or at the top in the overview.
EMAIL The email used during account registration.
PERSONAL_ACCESS_TOKEN Created at https://app.netlify.com/user/applications

Full Python script

import requests

# Edit these
ACCOUNT_NAME = 'youraccountname'
SITE_NAME = 'projectsitename'
EMAIL = 'name@example.com'
PERSONAL_ACCESS_TOKEN = "longlonglongstringgeneratedbynetlify"

# Leave the rest
bandwidth_api_url = 'https://api.netlify.com/api/v1/accounts/{}/bandwidth'.format(ACCOUNT_NAME)

auth_string = "Bearer " + PERSONAL_ACCESS_TOKEN

response = requests.get(bandwidth_api_url, headers = {
    'User-Agent': '{0} ({1})'.format(SITE_NAME, EMAIL),
    "Authorization": auth_string
})
response = response.json()

# Optional printing to console. Can be removed
print('Raw response: ', response)

def calculate(key):
    return int(response[key]) / 1000000

print_list = {
    "Included in plan": calculate("included"),
    "Used": calculate("used"),
    "Remaining":  calculate("included") - calculate("used"),
}
print('Human readable:')
for item in print_list.items():
    print(item[0], ': ', round(item[1], 2), ' MB')
Enter fullscreen mode Exit fullscreen mode

Note: The returned usage will be a bit higher than how Netlify calculates it.

Using Javascript

Netlify Bandwidth Checker Tool

If you are comfortable pasting your Personal Access Token in a web form, try this tool, which does the same as the Python script, only in JavaScript.
One way to mitigate risk is to create a token, and revoke it just after using this tool.

Source code

Top comments (0)