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
- Importing
pyshorteners
: Thepyshorteners
library simplifies interactions with URL shortening services like TinyURL. - Input for the Long URL: The
input()
function prompts the user to provide a URL they want to shorten. This URL is stored in thelong_url
variable. - TinyURL Shortening Service:
pyshorteners.Shortener()
initializes a shortener object.- The
.tinyurl.short()
method shortens the provided URL.
- 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:
- Support for Multiple URL Shortening Services.
- Input Validation to ensure users enter valid URLs.
- Error Handling for issues like service failures or invalid API keys.
- Option to Save Shortened URLs in a file.
- 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.