How to Make Unique Short URL with Python

Today, I want to share an exciting project I recently worked on: building a URL shortener in Python. URL shorteners are handy tools that take long URLs and create shorter versions, which are easier to share.

Project Overview

At its core, this Python project takes a long URL from the user, shortens it using a service like TinyURL, and displays the shortened URL. While this is useful on its own, I decided to add more features to make the tool practical and user-friendly.

The Basic Code

Here’s the initial version of the URL shortener:

codeimport pyshorteners

long_url = input("Enter the URL to shorten: ")

# TinyURL shortening service
type_tiny = pyshorteners.Shortener()
short_url = type_tiny.tinyurl.short(long_url)

print("The Shortened URL is: " + short_url)

Code Explanation

  1. Importing pyshorteners: The pyshorteners library simplifies interactions with URL shortening services like TinyURL.
  2. Input for the Long URL: The input() function prompts the user to provide a URL they want to shorten. This URL is stored in the long_url variable.
  3. TinyURL Shortening Service:
    • pyshorteners.Shortener() initializes a shortener object.
    • The .tinyurl.short() method shortens the provided URL.
  4. Displaying the Shortened URL: The shortened URL is saved in the short_url variable and printed to the console.

Example Run:

codeEnter the URL to shorten: https://www.clcoding.com/p/python.html
The Shortened URL is: https://tinyurl.com/2zb6hedv

Enhancing the Code

While the basic script works, I wanted to add some real-world functionality:

  1. Support for Multiple URL Shortening Services.
  2. Input Validation to ensure users enter valid URLs.
  3. Error Handling for issues like service failures or invalid API keys.
  4. Option to Save Shortened URLs in a file.
  5. Menu-Based User Interaction to make it intuitive.

Here’s the improved code:

codeimport pyshorteners
import validators

def shorten_url():
print("Choose a shortening service:")
print("1. TinyURL")
print("2. Bitly (requires API key)")
choice = input("Enter your choice (1 or 2): ")

# Prompt for the long URL
long_url = input("Enter the URL to shorten: ")

# Validate the input URL
if not validators.url(long_url):
print("Invalid URL. Please enter a valid URL.")
return

try:
shortener = pyshorteners.Shortener()

if choice == "1":
short_url = shortener.tinyurl.short(long_url)
elif choice == "2":
api_key = input("Enter your Bitly API Key: ")
shortener = pyshorteners.Shortener(api_key=api_key)
short_url = shortener.bitly.short(long_url)
else:
print("Invalid choice.")
return

print(f"The Shortened URL is: {short_url}")

# Ask to save the result
save_choice = input("Would you like to save this shortened URL to a file? (yes/no): ").strip().lower()
if save_choice == "yes":
with open("shortened_urls.txt", "a") as file:
file.write(f"Original URL: {long_url}\nShortened URL: {short_url}\n\n")
print("URL saved successfully in 'shortened_urls.txt'.")
except Exception as e:
print(f"An error occurred: {e}")

if __name__ == "__main__":
print("=== URL Shortener ===")
shorten_url()

Enhance Features Explained

Multiple Shortening Services

  • Users can choose between TinyURL (free, no authentication) and Bitly (requires an API key for access).
  • Bitly adds flexibility for users who prefer it or have existing API keys.

Input Validation

  • I added the validators.url function to verify that the provided URL is valid before shortening. If the URL is invalid, the script prompts the user to try again.

Error Handling

  • Using a try-except block ensures the script gracefully handles errors such as:
    • Invalid API keys for Bitly.
    • Service outages or unexpected issues.

Saving Shortened URLs

  • The script allows users to save the original and shortened URLs in a file named shortened_urls.txt. This is helpful for keeping track of multiple URLs.

Menu-Based Interaction

  • The menu makes it easy to select a URL shortening service, enhancing usability.

Output Examples

Using TinyURL

code=== URL Shortener ===
Choose a shortening service:
1. TinyURL
2. Bitly (requires API key)
Enter your choice (1 or 2): 1
Enter the URL to shorten: https://www.clcoding.com/p/python.html
The Shortened URL is: https://tinyurl.com/2zb6hedv
Would you like to save this shortened URL to a file? (yes/no): yes
URL saved successfully in 'shortened_urls.txt'.

Invalid URL

code=== URL Shortener ===
Choose a shortening service:
1. TinyURL
2. Bitly (requires API key)
Enter your choice (1 or 2): 1
Enter the URL to shorten: invalid_url
Invalid URL. Please enter a valid URL.

Using Bitly

code=== URL Shortener ===
Choose a shortening service:
1. TinyURL
2. Bitly (requires API key)
Enter your choice (1 or 2): 2
Enter the URL to shorten: https://www.example.com
Enter your Bitly API Key: YOUR_API_KEY_HERE
The Shortened URL is: https://bit.ly/3abcxyz
Would you like to save this shortened URL to a file? (yes/no): no

Conclusion

Building this URL shortener was a fun and educational journey. It helped me enhance my Python skills by integrating with web services, handling user input validation, and implementing practical features like error handling and saving results. This project is highly customizable, and I encourage you to try it, tweak it, and make it your own.

Related blog posts