URL Shortener Project (code) in Python

← Back to Projects

URL Shortener in Python.

About the project: This is URL Shortener project for you in Python that shortens a long URL using a public URL shortening service API.

This program will take a long URL as input, send a request to a service like TinyURL, and then print the shortened URL.

How to use this program:

To use this URL Shortener, you'll need to install the requests library.

Open your terminal or command prompt and run:


  pip install requests
  

    Once the libraries are installed, you can run the Python script:

  • Save the code:Save the code as a Python file (e.g., url_shortener.py).
  • Run the script: Open your terminal, navigate to the directory, and run python url_shortener.py.

The program will then prompt you to enter a long URL, and it will provide the shortened version for you. You can continue to shorten URLs until you type q to quit.

Project Level: Intermediate

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

Steps: Follow these steps

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE)




# url_shortener.py

import requests
import json

def shorten_url(long_url):
    """
    Shortens a URL using the TinyURL API.
    
    Args:
        long_url (str): The original, long URL.

    Returns:
        str or None: The shortened URL if successful, otherwise None.
    """
    api_endpoint = "http://tinyurl.com/api-create.php"
    
    try:
        # Parameters for the API request
        params = {
            'url': long_url
        }
        
        # Send a GET request to the TinyURL API
        response = requests.get(api_endpoint, params=params, timeout=10)
        
        # Raise an exception for bad status codes (e.g., 404, 500)
        response.raise_for_status()
        
        # The TinyURL API returns the shortened URL as plain text
        shortened_url = response.text
        
        # Basic check to see if the response is a valid URL
        if shortened_url.startswith("http"):
            return shortened_url
        else:
            # The API might return an error message as plain text
            print(f"Error from TinyURL: {shortened_url}")
            return None
            
    except requests.exceptions.RequestException as e:
        print(f"Network error: {e}")
        return None
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        return None

def main():
    """
    Main function to run the URL Shortener.
    """
    print("--- Python URL Shortener ---")
    print("Enter 'q' at any time to quit.")

    while True:
        long_url = input("\nEnter the URL to shorten: ").strip()

        if long_url.lower() == 'q':
            print("Exiting URL Shortener. Goodbye!")
            break
        
        if not long_url:
            print("URL cannot be empty. Please enter a valid URL.")
            continue
        
        # Add a protocol prefix if the user omits it
        if not long_url.startswith(('http://', 'https://')):
            long_url = 'http://' + long_url

        shortened_url = shorten_url(long_url)
        
        if shortened_url:
            print(f"Shortened URL: {shortened_url}")
        else:
            print("Failed to shorten the URL. Please try again.")

# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
    main()