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 jul 2020 · Application Programming Interfaces


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 proves to be useful in many cases, such as tracking number of clicks or requiring the user to only type 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.

We won't be using any API wrappers in this tutorial, as a result, we gonna need requests library for convenience, let's install it:

pip3 install requests

Bitly API

To get started with Bitly API. First, you need to sign up for a new account, it's for free, and if you already have one, then just use it.

Once you have your Bitly account created, we need to get our account ID, so we can 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 gonna 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 show 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 carefuly the Bitly API documentation, you'll see that we need an access token in order 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 get 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 "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 Cuttly documentation.

Conclusion

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

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

Happy Coding ♥

View Full Code
Sharing is caring!



Read Also





Comment panel