How to Make a URL Shortener in Python

Learn how to use Bitly and Cuttly APIs to shorten long URLs programmatically using requests library in Python.
  · 6 min read · Updated may 2024 · Application Programming Interfaces

Welcome! Meet our Python Code Assistant, your new coding buddy. Why wait? Start exploring now!

A URL shortener is a tool that takes a long URL and turns it into a short one that redirects to the intended page. URL shorteners prove to be useful in many cases, such as tracking the number of clicks or requiring the user to only type a small number of characters, as long URLs are difficult to memorize.

In this tutorial, we will be using Bitly and Cuttly APIs to shorten URLs automatically in Python. Feel free to jump to your favorite provider:

We won't be using any API wrappers in this tutorial. As a result, we will need the requests library for convenience. Let's install it:

pip3 install requests

Bitly API

Bitly is a URL shortening service and a link management platform. It allows you to track the clicks with various information about the clicks. To get started with Bitly API. First, you need to sign up for a new account. It's free, and if you already have one, just use it.

Once you have your Bitly account created, we need to get our account ID to access the API. Go ahead and click on your upper-right profile and click Account Settings:

Go to Account Settings in Bitly

After that, grab the account name that's we going to need in code, as shown in the following image:

Get bitly account name

Alright, that's all we need; let's start with coding now:

import requests

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

the username is the account name I just showed you how to get it, the password is the actual password of your Bitly account, so you should replace them with your credentials.

If you read the Bitly API documentation carefully, you'll see that we need an access token to make API calls to get the shortened URL, so let's create a new access token:

# get the access token
auth_res = requests.post("https://api-ssl.bitly.com/oauth/access_token", 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)
else:
    print("[!] Cannot get access token, exiting...")
    exit()

We used requests.post() method to make a POST request to /oauth/access_token endpoint and obtain our access token. We passed auth parameter to add our account credentials to the request headers.

Now we have our access token, before we dive into shortening URLs, we first need to get the group UID associated with our Bitly account:

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

# get the group UID associated with our account
groups_res = requests.get("https://api-ssl.bitly.com/v4/groups", 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']
else:
    print("[!] Cannot get GUID, exiting...")
    exit()

Now that we have guid, let's make our request to shorten an example URL:

# the URL you want to shorten
url = "https://www.thepythoncode.com/topic/using-apis-in-python"
# make the POST request to get shortened URL for `url`
shorten_res = requests.post("https://api-ssl.bitly.com/v4/shorten", 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)

We're sending a POST request to /v4/shorten endpoint to shorten our url, we passed the group_guid of our account and the url we want to shorten as the body of the request.

We used json parameter instead of data in requests.post() method to automatically encode our Python dictionary into JSON format and send it with Content-Type as application/json, we then added the headers to contain the authorization token we grabbed earlier. Here is my output:

Shortened URL: https://bit.ly/32dtJ00

Great, we have successfully shortened our URL with Bitly! Here is their official documentation.

Cuttly API

Another alternative is using Cuttly API. It is pretty easy to create a new account and use its API. After you signed up for an account, go to "Your account" and click on "Edit Account":

Cuttly Edit Account

After that, you'll see your account details, go on and click on the Change API key to obtain a new API key (so we can make API requests):

Change API key in Cuttly

To shorten your URL using Cuttly, it's pretty straightforward:

import requests

api_key = "64d1303e4ba02f1ebba4699bc871413f0510a"
# the URL you want to shorten
url = "https://www.thepythoncode.com/topic/using-apis-in-python"
# preferred name in the URL
api_url = f"https://cutt.ly/api/api.php?key={api_key}&short={url}"
# or
# api_url = f"https://cutt.ly/api/api.php?key={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)
else:
    print("[!] Error Shortening URL:", data)

Simply replace your API key in api_key and your URL you want to shorten, and you're good to go. Here is my output:

Shortened URL: https://cutt.ly/mpAOd1b

Note that you can specify a unique name, and the result will be something like: https://cutt.ly/some_unique_name, you can accomplish that by simply adding name parameter to the GET request in the URL.

Read more on the Cuttly documentation.

Conclusion

Excellent, now you know how to shorten your URLs using both Bitly and Cuttly shorteners! Note that these providers provide more endpoints for clicks, statistics, and more. You should check their documentation for more details.

Learn also: How to Use Google Custom Search Engine API in Python.

Happy coding ♥

Want to code smarter? Our Python Code Assistant is waiting to help you. Try it now!

View Full Code Transform My Code
Sharing is caring!



Read Also



Comment panel

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!