URL Shortener Python Script

This script is a straightforward and user-friendly URL shortener that leverages the TinyURL API to convert long URLs into compact, shareable links. It prompts the user for a URL, processes it through the API, and then displays both the original and shortened URLs for easy reference.

This script requires the requests library to handle HTTP requests to the TinyURL API. Make sure to install it with pip install requests before running the script.

Click to view script…
#!/usr/bin/env python3
import requests

def shorten_url(url):
    """
    Shortens the given URL using the TinyURL API.
    
    Parameters:
        url (str): The original URL.
    
    Returns:
        str: The shortened URL or None if something went wrong.
    """
    api_url = 'https://tinyurl.com/api-create.php'
    params = {'url': url}
    try:
        response = requests.get(api_url, params=params)
        if response.status_code == 200:
            return response.text.strip()
        else:
            print(f"Error: Unable to shorten URL. Status code: {response.status_code}")
            return None
    except Exception as e:
        print("Error during request:", e)
        return None

def main():
    print("=== Welcome to the Python URL Shortener ===\n")
    
    # Get URL from user
    original_url = input("Enter the URL you want to shorten: ").strip()
    if not original_url:
        print("No URL provided. Exiting.")
        return

    # Get the shortened URL
    shortened_url = shorten_url(original_url)
    if shortened_url:
        # Display the original and shortened URLs
        print("\nHere are your URLs:")
        print("-" * 40)
        print("Original URL:  ", original_url)
        print("Shortened URL: ", shortened_url)
        print("-" * 40)
    else:
        print("Failed to shorten the URL.")

if __name__ == "__main__":
    main()