Python - URL Shortener using Tinyurl API

In the web era, concise links are crucial for sharing hyperlinks via social media, text messages, and other communication methods. Long URLs can be challenging to share and might be truncated in messages. Python provides a convenient approach to interact with URL shortening services like TinyURL through their API.

What is a URL Shortener?

A URL shortener is a service that takes a long URL as input and generates a shorter, more manageable URL. This shortened URL redirects users to the original long URL when clicked. URL shorteners are widely used on social media, email communications, and any situation where long URLs need to be shared efficiently.

Syntax

import requests

url = 'http://tinyurl.com/api-create.php?url='
long_url = 'https://www.example.com/path/to/content/'

response = requests.get(url + long_url)
short_url = response.text

print(short_url)

Algorithm

Follow these steps to create a URL shortener

  • Step 1: Import the requests module

  • Step 2: Define the TinyURL API endpoint

  • Step 3: Set the long URL that needs to be shortened

  • Step 4: Make an HTTP GET request to the TinyURL service

  • Step 5: Extract and display the shortened URL from the response

Method 1: Using requests.get()

This method uses the requests module to directly interact with TinyURL's API ?

import requests

def shorten_url(url):
    api_url = 'http://tinyurl.com/api-create.php?url='
    response = requests.get(api_url + url)
    return response.text

# Example usage
long_url = 'https://www.tutorialspoint.com/python/index.htm'
short_url = shorten_url(long_url)
print(f"Original URL: {long_url}")
print(f"Shortened URL: {short_url}")
Original URL: https://www.tutorialspoint.com/python/index.htm
Shortened URL: https://tinyurl.com/2p8xyz12

The function shorten_url() takes a URL parameter and returns the shortened version. The requests.get() method sends an HTTP GET request to the TinyURL API with the long URL appended. The response contains the shortened URL as plain text.

Method 2: Using PyShorteners Library

PyShorteners is a Python library that provides URL shortening functionality for multiple services ?

# First install: pip install pyshorteners
import pyshorteners

def shorten_with_pyshorteners(url):
    s = pyshorteners.Shortener()
    return s.tinyurl.short(url)

# Example usage
long_url = 'https://www.tutorialspoint.com/python/index.htm'
short_url = shorten_with_pyshorteners(long_url)
print(f"Original URL: {long_url}")
print(f"Shortened URL: {short_url}")
Original URL: https://www.tutorialspoint.com/python/index.htm
Shortened URL: https://tinyurl.com/abc123de

The PyShorteners library provides a cleaner interface. Create a Shortener() object and use the tinyurl.short() method to generate shortened URLs. This approach is more readable and handles errors automatically.

Complete URL Shortener Application

Here's a complete application with error handling and user input ?

import requests

def validate_url(url):
    """Check if URL starts with http:// or https://"""
    return url.startswith(('http://', 'https://'))

def shorten_url(url):
    """Shorten URL using TinyURL API with error handling"""
    if not validate_url(url):
        url = 'http://' + url
    
    try:
        api_url = 'http://tinyurl.com/api-create.php?url='
        response = requests.get(api_url + url, timeout=10)
        
        if response.status_code == 200:
            return response.text.strip()
        else:
            return f"Error: Unable to shorten URL (Status: {response.status_code})"
            
    except requests.exceptions.RequestException as e:
        return f"Error: {str(e)}"

# Test with multiple URLs
test_urls = [
    'https://www.tutorialspoint.com/python/python_overview.htm',
    'www.google.com',
    'https://github.com/python/cpython'
]

for url in test_urls:
    shortened = shorten_url(url)
    print(f"Original: {url}")
    print(f"Shortened: {shortened}")
    print("-" * 50)
Original: https://www.tutorialspoint.com/python/python_overview.htm
Shortened: https://tinyurl.com/2p9abc45
--------------------------------------------------
Original: www.google.com
Shortened: https://tinyurl.com/3xyz789
--------------------------------------------------
Original: https://github.com/python/cpython
Shortened: https://tinyurl.com/4def012
--------------------------------------------------

Comparison

Method Dependencies Error Handling Best For
requests.get() requests only Manual Simple implementations
PyShorteners pyshorteners Built-in Multiple URL shorteners

Conclusion

URL shortening in Python can be accomplished using either the requests module with TinyURL's API or the pyshorteners library. The requests approach offers more control, while PyShorteners provides a cleaner interface with built-in error handling for multiple shortening services.

Updated on: 2026-03-27T10:20:56+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements