circuiTician

Making a URL Shortener using Python [Source Code Included]

Table of Contents

In this tutorial, we are going to build a URL Shortener using Python and rebrand.ly API. We are only going to build the backend part of the application. Before jumping into the tutorial, you must know the basics of URL Shortener and API(Application Programming Interface).

What is a URL Shortener?

So, as this tutorial is all about URL Shortener, it is best if you know the basics about it. To put it simply it is a tool that takes a long URL as an input and turns it into a more appealing short URL.

Example:
Long URL: https://circuitician.com/esp32-email-notifier/
Shortened URL: https://rb.gy/b7iqj6

As you can see the shortened URL is more appealing than the long one and it is more readable. Moreover, this shortened URL can be tracked for like no. of clicks, last-click time, etc.
Shortened URLs are widely used by online marketers, promoters, and online entrepreneurs to promote their web links on the internet. If you share shortened URLs instead of long URLs in your social media post then it will look cleaner & readable and saves you more space for your post content.
A custom, or branded URL shortener, is after you connect your own domain to a URL shortener that acts as a base for all the short links you create. rather than employing a generic domain like Bitly or Rebrandly, you’ll choose your own.

What is an API (Application Programming Interface)?

An application-programming interface (API) is a set of programming instructions and defined standards for accessing any Web-based software application. A software company releases its API to the public so that other software developers can design products that are powered by its service.
There are many APIs for URL Shortener, but in this tutorial, we are going to use the rebrand.ly API.

Prerequisite

  • Python 3 is installed in your system.
  • Prior knowledge of Python programming language.

CODE

Code to create a short URL:

At first, we need to import 2 python modules which are request and json. No need to install these modules they are pre-installed.

import requests
import json

Next, we have to prepare our linkRequest.
It requires 4 information which are:

  • destination
  • domain
  • slashtag(optional)
  • title(optional)

These all are the input information required to shorten our URL. Here destination means the destination URL. Domain means domain name, in our case, it will be rebrand.ly. You can also add your custom domain if you have one. You can create your own slashtag, if you don’t it will be generated randomly. The part after the forward-slash in the following example is slashtag. In this case, it is crctn.

Ex: rebrand.ly/crctn

The title is just to identify your link.

We will wrap these 4 items in a dictionary variable.

linkRequest = {
  "destination": "Your Destination Link"
  , "domain": { "fullName": "rebrand.ly" }
 , "slashtag": "Your Custom Slashtag"
 , "title": "Custom Title"
}

If you put your custom slashtag in the code then you have to change it every time you run the code because it should be unique or you can comment out the line and then it will be generated randomly.
Before going to the next step of the code we have to create an API key from the rebrand.ly API dashboard. You can sign up for the API from here.
After logging in click on the profile icon on the top right corner and then click API keys. Then click Generate a new API key.

Now, just copy the API key.

Coming back to code

In the case of any API, we need an API key to send a request to the API for authentication purposes. In our case, we will wrap the API key in a dictionary variable.

requestHeaders = {
  "Content-type": "application/json",
  "apikey": "8b489b24e5a5459ba6bfac4bad878bcc"
}

These two items are requestHeaders.Here “Content-type”:”application/json” indicates that the request body format is JSON.
Now, as we have set all our input data, content type, and API key, it is time to send the request to the API. To do so, we will send POST requests using the post method form request module which we imported at first.

r = requests.post("https://api.rebrandly.com/v1/links", 
    data = json.dumps(linkRequest),
    headers=requestHeaders)

“https://api.rebrandly.com/v1/links” – this is the API link to which we are sending the post request along with the parameters linkRequest and requestHeaders.As you can see here the linkRequest which is a dictionary variable is converted into json format using the dumps method from json module which we also imported at first.

The response to this request is stored in the r variable.

To know whether your URL is shortened or not you have to print this:

print(r.status_code)

If the output is 200 which means OK, then your URL is successfully shortened.If the output is 403 it means the link already exists.
Now to extract info about your new shortened URL you have to convert into json format using the dumps method from json module and store it into another variable link.

if(r.status_code == requests.codes.ok):
    link = r.json()
    print(link)

Here the, if statement is checking the status code, is OK or not. OK means 200.

Output:

{‘id’: ‘203f0cdcae784123b5bda03e833a243d’, ‘title’: ‘Circuitician’, ‘slashtag’: ‘crctn’, ‘destination’: ‘https://circuitician.com/esp32-email-notifier/’, ‘createdAt’: ‘2021-05-12T05:42:22.000Z’, ‘updatedAt’: ‘2021-05-12T05:42:22.000Z’, ‘expiredAt’: None, ‘status’: ‘active’, ‘tags’: [], ‘clicks’: 0, ‘isPublic’: False, ‘shortUrl’: ‘rebrand.ly/ crctn’, ‘domainId’: ‘8f104cc5b6ee4a4ba7897b06ac2ddcfb’, ‘domainName’: ‘rebrand.ly’, ‘domain’: {‘id’: ‘8f104cc5b6ee4a4ba7897b06ac2ddcfb’, ‘ref’: ‘/domains/8f104cc5b6ee4a4ba7897b06ac2ddcfb’, ‘fullName’: ‘rebrand.ly’, ‘sharing’: {‘protocol’: {‘allowed’: [‘http’, ‘https’], ‘default’: ‘https’}}, ‘active’: True}, ‘https’: True, ‘favourite’: False, ‘creator’: {‘id’: ‘f210caa6573346dab4b2d4f867fc12ea’, ‘fullName’: ‘Programmer Bose’, ‘avatarUrl’: ‘https://s.gravatar.com/avatar/9201100e9253862920576001fc242c28?size=80&d=retro&rating=g’}, ‘integrated’: False}

You can see here the destination URL that we have sent and the shortUrl that we got as a response.
If you want to print selective info you can write this instead of print(link) inside the if statement.

print("Long URL was %s, short URL is %s, ID is %s" % 
    (link["destination"], link["shortUrl"],link["id"]))
Output:

Long URL was ‘https://circuitician.com/esp32-email-notifier/ ‘, short URL is rebrand.ly/crctn, ID is 29eac9fe2b1840d4b37e61a9f56808da

Code to extract information about all created short URLs:

import requests
import json

requestHeaders = {
  "Content-type": "application/json",
  "apikey": "8187da6db54f486fa1e7bbcace8d659c",
}

s = requests.get("https://api.rebrandly.com/v1/links", 
    headers=requestHeaders)

if(s.status_code == requests.codes.ok):
  glink=s.json()
  for i in range (0,len(glink)):
    print("Long URL was %s, short URL is %s, ID is %s, clicked %d times" % 
    (glink[i]["destination"], glink[i]["shortUrl"],glink[i]["id"],glink[i]["clicks"]))

The above code is mostly similar to the previous code of creating a new short URL except we will use the get method of request module to get the info of all the links that we have created.
In response to get request, we will get all info of all links that we have created.

That’s all for this tutorial. You can do more with this API. If you want to learn more about this API then click here.
If you like this tutorial then share it with your developer friends. Comment your thoughts and shoot your questions in the comment section.

Thank You.

Like it !! Share it !!

Share on facebook
Share on twitter
Share on linkedin
Share on reddit
Share on pinterest

Related Articles