DEV Community

Cover image for How to build an URL Shortener & Expander using Python
Sai Ashish
Sai Ashish

Posted on • Updated on • Originally published at theinsightfulcoder.com

How to build an URL Shortener & Expander using Python

Welcome to the Python Projects for Beginners Series πŸ™‹πŸ»β€β™‚οΈ

I'm Sai Ashish and today, I'm going to show you how to build an URL Shortener & Expander using Python😍

How cool is that? Let's get started πŸš€

What are we going to learn today?

1. What is a URL?
2. Understanding the URL structure
3. Why do we shorten or expand an URL?
4. Basics of Python: Conditional Statements, Type Casting, Functions
5. The Pyshorteners module
6. Implementation of the URL Shortener & Expander with detailed explanation
Enter fullscreen mode Exit fullscreen mode

1. What is a URL?

What is a URL?
A Uniform Resource Locator(URL) is a web address which specifies the location of a particular file on the internet. That particular file could be the HTML webpage itself or the CSS style sheet, images, video embeds etc.

2. Understanding the URL Structure

Understanding/ What is the URL Structure
Typically a URL has 5 parts:

1. The Scheme

The Scheme tells the web servers which protocol to use while accessing a page on a website. The most common examples are http and https, while there are quite a few other such as ftp and mailto. The Insightful Coder uses the https: protocol, indicating the Hyper Text Transfer Protocol with a Secure Sockets layer .

2. The Subdomain

The Subdomain is an additional part to the domain name. For example, blog, shop or offers provides the website’s blog, shop or offers page. It is used to indicate that a website has more than one part apart from the main page. At The Insightful Coder, we only have the second-level domain.

3. The Second-level domain

The Second-level domain is the name of the website. theinsightfulcoder is the second-level domain of our website.

4. The Top-level domain

The Top-level domain or TLD specifies the entity a website gets registered on the internet. The most commonly used TLD are .com, .org, .net, .dev, .in etc. As you can see, The Insightful Coder has a TLD of .com

5. The Subdirectory

The Subdirectory specifies the page you're currently on. For eg, for this article the subdirectory is /create-your-very-own-url-shortener-and-expander-using-python

3. Why do we shorten or expand a URL?

image.png

a. URL Shortener:

A URL shortener is a tool to shorten a URL.

Which URL would you rather prefer http://somerandomkeywords.randomdomainname.tld/unecessary-long-post-slug-uggh! or https://theinsightfulcoder.com?

We use URL shortening for:

  • Beautification: A shortened URL is a beautiful URL. A shortened URL looks neat and clean, easy to understand and hence, can generate more traffic to your website.

  • Easy to remember: A short URL is easier to remember than a long one.

  • Word of Mouth Communication: Suppose you want to share the name of your website with a friend, a colleague or a recruiter. Or you want to print the name of your website on a card or display it during a presentation or video conference. Which URL would you choose? With a shorter URL you can leverage word of mouth communication.

  • Social media marketing: Social Media such as Instagram or Twitter provide a strict number of characters or links you can use to showcase your URL. A shorter URL gives the users the chance to focus on what's important.

  • More Clicks = More Traffic = Better page visibility: URL Shortening becomes a major factor to get clicks website. More clicks = More traffic = Better page visibility.

b. URL Expander

image.png
A URL expander is a tool used to expand a URL.

We use URL expanding for:

While shortening a URL has many benefits, spammers and hackers have found a convenient way to redirect a shortened URL to a spammy or malicious website. To be aware of such malpractices and which website you're visiting, it is a good practice to check where the shortened URL points at.

Time to Code:

Time to Code by The Insightful Coder

You can access the exclusive theory for this build hereπŸ“„

For this build, we would be using the pyshorteners module. As per the official documentation , Pyshorteners is a Python lib to help you short and expand urls using the most famous URL Shorteners availables.

The Pyshorteners module provides a variety of different services to choose from. Some of them are Adf.ly, Bit.ly, Cutt.ly, Git.io, Po.st, Short.cm, Tiny.cc, TinyURL.com, Tiny.cc.

To install the pyshorteners module, run the following command in the terminal:

pip install pyshorteners
Enter fullscreen mode Exit fullscreen mode

For our build, we will be using tinyurl but you are free to choose any service you like to.

The first step is to import Shorteners from the pyshorteners module. We implement it as:

#importing the required library
from pyshorteners import Shortener
Enter fullscreen mode Exit fullscreen mode

Let's store an instance of the shortener in a variable.

s = Shortener()
Enter fullscreen mode Exit fullscreen mode

Now, we can just use s to access the functionalities of Shortener().

Next, we want to ask the user if he wants to expand a URL or shorten it.

choice = int(input("Enter 1 for link shortener and 2 for link expander: "))
Enter fullscreen mode Exit fullscreen mode

Let's define a function, short() to execute link shortener.

def short():
Enter fullscreen mode Exit fullscreen mode

Next, we want the link to be shortened.

link = input("Enter the link to be shortened: ")
Enter fullscreen mode Exit fullscreen mode

Pass this link to tinyurl's short function.

shortened_link = s.tinyurl.short(link)
Enter fullscreen mode Exit fullscreen mode

Let's give our users the short link.

print(" The Shortened Link is: " + shortened_link)
Enter fullscreen mode Exit fullscreen mode

Similarly, let's define a function for link expander. The only difference being, instead of using short(), use the expand() function.

def expand():
       link = input("Enter the link to be expanded: ")
       expanded_link = s.tinyurl.expand(link)
       print("The Expanded link is: " + expanded_link)
Enter fullscreen mode Exit fullscreen mode

If the user chose 1, we call the short() function, the expand() function if 2 and an error message for any other input.

if choice == 1:
    short()
elif choice == 2:
    expand()
else:
    print("Wrong Entry. Please try again.")
Enter fullscreen mode Exit fullscreen mode

The Final Source Code is given below:

The Final Source Code for URL Shortener and Expander

Code in Action πŸ’ͺ🏻:

URL Shortener using python

URL Expander using python

We did it πŸ₯³ We have made our own URL Shortener & Expander using Python! How amazing is that? As a gift for staying till now, you get access to my Python For Beginners Series Repository 😍 This repository contains all the source code you'd need to get started as a Python Developer 🐍.

You can also download the source code to this project here. Do hit the twinkle star, if this article provided value to you πŸ”₯

And while you're at it, consider giving this blog the maximum love you can and I promise to give you such value bombs every week πŸ’£ Until then, take care πŸ™‹πŸ»β€β™‚οΈ

Bonus Insights by The Insightful Coder :

  • Interested in Building Your Own Artificial Intelligence Projects using Python?: Check out the Python AI Series🧠

  • Wanna Discover Some Valuable Tech-Hacks πŸ› ?: Check out the Tech-Hacks for Everybody Series😎

  • I'm also dropping daily value bombs and development insights on my Instagram Page. Make sure to follow me up πŸ’―

  • Find and Download All My Project Source Codes at My Github Repository 🎁

Top comments (2)

Collapse
 
rishitkhandelwal profile image
Rishit Khandelwal

Actually it isn't our own, we are using a external library

Collapse
 
theinsightfulcoder profile image
Sai Ashish

Thanks for pointing it out. Fixed it 😊