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.
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.
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.
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.
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.
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.
"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:
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.
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.
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:
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
Post a Comment