How to create a simple URL shortner in Python using Tinyurl API

in blurtafrica •  6 days ago  (edited)• 3 min read


url shortener whole code.PNG


Hello everyone, welcome to my blog!

Today, I want to teach you how to create a simple URL shortener in Python. Many of us here, if not all has at some point posted links to social media platforms like facebook, twitter, instagram, e.t.c. with the purpose of affiliate marketing or otherwise. So in this article, I will teach you with code how you can create a simple url shortener for your personal use. So, if you're ready to learn with me, let's dive in...


If you know very well, tinyurl.com can help you achieve this goal, but this blog will assist you to personally create one for yourself and run it in your terminal environment anytime you want to shorten any url. Python programming language has an inbuilt tinyurl library called Pyshortener that can be used to achieve this goal.

But before you start, make sure you have text editor called visual studio code installed to write your Python codes. However, if you don't have any, download one from here visual studio code

Steps to follow


1. Open your text editor, create a folder, and open the folder in your text editor. After opening the project folder in your vs code, create a new file called "url_shortener.py" and open it.

url_shortener screenshot.PNG

2. Install the pyshorteners module using: pip install pyshorteners

pip install pyshorteners.PNG

3. Import the pyshorteners module in your python file.

import pyshorteners.PNG

4. Create a variable to store the long_url input from a user.


url input.PNG

5. Initialize the pyshortener library's class object to start shortening your URL.


shorten the url.PNG

6. Print the output of the shortened URL to the standard output.


url output.PNG

7. Finally, run the program in your terminal.


the final output.PNG


The whole code and the output


url shortener whole code.PNG

As you can see from the above code, we imported pyshorteners module from python library, then we accepted the url input from the user and then print out to the standard output using the print() function.

Looking into the terminal at the bottom of the screenshot, you can see that we copied a long url from the internet and pasted it to the terminal. And when we hit enter, the tiny_url function worked on the long url and shortened the url for us as you can also see in the screenshot.

I advice you to practice this code on your own terminal to see the magic. Python is a very powerful programming language as you can see.


This is the end of this article, I'm glad you've learnt something new today!!


I am @anyiglobal

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!