Skip to main content

Making a URL Shortener using Python [Source Code Included] | URL Shortener API


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).

[This Article is originally published here]

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.

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 shortened 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 pgbose.
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 new API key.



You will see this screen after an API key is generated.


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 that 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 r 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': 'Programmer Bose', 'slashtag': 'pgse2', 'destination': 'https://programmer-bose.blogspot.com/', '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/pgse2', '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://programmer-bose.blogspot.com/, short URL is rebrand.ly/pgse2, 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.

Example response:

[{'id': '29eac9fe2b1840d4b37e61a9f56808da', 'title': 'Programmer Bose', 'slashtag': 'pgse2', 'destination': 'https://programmer-bose.blogspot.com/', 'createdAt': '2021-05-12T06:15:21.000Z', 'updatedAt': '2021-05-12T06:15:21.000Z', 'expiredAt': None, 'status': 'active', 'tags': [], 'clicks': 0, 'isPublic': False, 'shortUrl': 'rebrand.ly/pgse2', '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}, {'id': '3e8250da3d1045938f90b544b1249e95', 'title': 'Programmer Bose', 'slashtag': 'pgbose', 'destination': 'https://programmer-bose.blogspot.com/', 'createdAt': '2021-05-12T04:24:27.000Z', 'updatedAt': '2021-05-12T04:24:27.000Z', 'expiredAt': None, 'status': 'active', 'tags': [], 'clicks': 0, 'isPublic': False, 'shortUrl': 'rebrand.ly/pgbose', '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}]

As you can notice here the response is a list variable and it contains information on two links that we have created.

After extracting selective info about our links like no. of clicks, link ID, shortUrl, etc.
Output:

Long URL was https://programmer-bose.blogspot.com/, short URL is rebrand.ly/pgse2, ID is 29eac9fe2b1840d4b37e61a9f56808da, clicked 0 times
Long URL was https://programmer-bose.blogspot.com/, short URL is rebrand.ly/pgbose, ID is 3e8250da3d1045938f90b544b1249e95, clicked 0 times


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.

Comments

Popular posts from this blog

Ordered Vs Unordered Data Structures in Python

Python has multiple data structures like Lists, Tuples, Dictionaries, Sets, and more . Some of them are Ordered and some are Unordered. This article will discuss  Ordered Vs Unordered Data Structures in Python. Lists It is a collection of a mutable ordered sequence of elements and can be accessed through indexing and defined inside []. Each element inside a List is called an item. From the above example, it is clear that the list maintains a sequence in which elements are inserted. So, it is an ordered data structure in python. Tuples It is a collection of immutable ordered elements, which follows a sequence in which elements are inserted. It is defined inside () and accessed through indexing. The above example shows that Tuples are ordered data structure and follow the sequence of insertion. Dictionaries Collection of items, in which items are defined as key-value pair in {}. Dictionaries are ordered data structures in python. It can be accessed through a specific key. Each key is sep

Concepts of Functional Programming in Python with Examples

Functional programming it's not new jargon, it just is a style of writing programming and treating some values and some functions in a bit different way than we used to treat them in object-oriented programming. What is Functional Programming? Functional programming is a programming paradigm in which we evaluate the pure mathematical function as the principal method of computation. “What to solve” is more important in functional programming instead of “How to solve”.   Concepts of Functional Programming Now, every single programmer can debate in the world of functional programming whether this is functional or this is not but there are four core important things on which every single programmer is going to agree that yes these are part of functional programming. Pure functions: Pure Functions always produce the exact same output for the same argument irrespective of anything else. They have no side effects. Recursion: There is no “for” or “while” loop in functional languages. Recur