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.
2. Install the pyshorteners module using: pip install pyshorteners
3. Import the pyshorteners module in your python file.
4. Create a variable to store the long_url input from a user.
5. Initialize the pyshortener library's class object to start shortening your URL.
6. Print the output of the shortened URL to the standard output.
7. Finally, run the program in your terminal.
The whole code and the output
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.