Code for How to Make a URL Shortener in Python Tutorial

View on Github

import requests

# account credentials
username = "o_3v0ulxxxxx"
password = "your_password_here"

# the URL you want to shorten
url = ""

# get the access token
auth_res ="", auth=(username, password))
if auth_res.status_code == 200:
    # if response is OK, get the access token
    access_token = auth_res.content.decode()
    print("[!] Got access token:", access_token)
    print("[!] Cannot get access token, exiting...")

# construct the request headers with authorization
headers = {"Authorization": f"Bearer {access_token}"}

# get the group UID associated with our account
groups_res = requests.get("", headers=headers)
if groups_res.status_code == 200:
    # if response is OK, get the GUID
    groups_data = groups_res.json()['groups'][0]
    guid = groups_data['guid']
    print("[!] Cannot get GUID, exiting...")

# make the POST request to get shortened URL for `url`
shorten_res ="", json={"group_guid": guid, "long_url": url}, headers=headers)
if shorten_res.status_code == 200:
    # if response is OK, get the shortened URL
    link = shorten_res.json().get("link")
    print("Shortened URL:", link)

import requests

# replace your API key
api_key = "64d1303e4ba02f1ebba4699bc871413f0510a"

# the URL you want to shorten
url = ""

# preferred name in the URL

api_url = f"{api_key}&short={url}"
# or
# api_url = f"{api_key}&short={url}&name=some_unique_name"

# make the request
data = requests.get(api_url).json()["url"]
if data["status"] == 7:
    # OK, get shortened URL
    shortened_url = data["shortLink"]
    print("Shortened URL:", shortened_url)
    print("[!] Error Shortening URL:", data)