Back to Insights

Building a Python Script to Automate URL Shortening and Tracking

Building a Python Script to Automate URL Shortening and Tracking

Python is widely recognized as the ultimate programming language for automation, scripting, and data analysis. If you are a digital marketer, data analyst, or developer, you frequently run into tasks that require handling links—such as sending customized email campaigns, compiling daily report spreadsheets, or posting automated updates across social media channels.

Doing this manually is time-consuming. By connecting a simple Python script to a link-shortening REST API, you can automate your workflows in seconds.

In this tutorial, we will show you how to write a reusable Python script to shorten and track URLs programmatically using the LinkZip.uk API and the popular requests library.


1. Prerequisites

To follow this tutorial, you need:

  1. Python installed: Version 3.8 or higher.
  2. The requests library: You can install it via your terminal:
    pip install requests
  3. A LinkZip API Key: Log in to your free account on LinkZip.uk and copy your secret API key from the developer settings tab.

2. Writing a Basic URL Shortening Script

Create a new file named shortener.py and write the following code. This script configures a POST request to send your destination URL and API key to the LinkZip backend.

import requests

def shorten_url(long_url, custom_alias=None):
    """
    Shortens a long URL using the LinkZip.uk REST API.
    
    :param long_url: The destination URL (string)
    :param custom_alias: Optional custom back-half slug (string)
    :return: The shortened URL (string)
    """
    API_KEY = "your_api_key_here"  # Replace with your actual LinkZip API Key
    API_URL = "https://linkzip.uk/api/shorten"
    
    # Configure authorization header
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    
    # Configure body data payload
    data = {
        "url": long_url
    }
    if custom_alias:
        data["alias"] = custom_alias
        
    try:
        response = requests.post(API_URL, headers=headers, json=data)
        
        # Raise an exception for HTTP error codes (4xx or 5xx)
        response.raise_for_status()
        
        response_json = response.json()
        return response_json.get("shortUrl")
        
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err}")
        # Parse error details from API if available
        try:
            print(f"Error message: {response.json().get('message')}")
        except Exception:
            pass
        raise
    except Exception as err:
        print(f"An error occurred: {err}")
        raise

# Example execution:
if __name__ == "__main__":
    target_link = "https://yourwebsite.com/blog/articles/python-automation-guide"
    custom_slug = "py-automation"
    
    print("Sending API request to LinkZip...")
    try:
        short_link = shorten_url(target_link, custom_slug)
        print("\nSuccess!")
        print(f"Original Link: {target_link}")
        print(f"Shortened Link: {short_link}")
    except Exception:
        print("Script failed to shorten link.")

3. Advanced Use Case: Bulk Shortening from a List

A common real-world automation task is reading a list of links (e.g., from a CSV file or database) and shortening them in bulk. Below is an example of how you can loop through a Python list and output a dictionary of shortened links:

def bulk_shorten_links(links_list):
    results = {}
    for index, url in enumerate(links_list):
        alias = f"campaign-link-{index + 1}"
        try:
            short_url = shorten_url(url, alias)
            results[url] = short_url
        except Exception:
            results[url] = "ERROR"
    return results

# Example run:
urls_to_shorten = [
    "https://mystore.com/product/1",
    "https://mystore.com/product/2",
    "https://mystore.com/product/3"
]
bulk_results = bulk_shorten_links(urls_to_shorten)
print(bulk_results)

4. Best Practices for API Scripting

  • Security (Environment Variables): Never store your secret API keys directly in your scripts, especially if you plan to upload them to public repositories like GitHub. Use the os module and store your key in your system environment:
    import os
    API_KEY = os.environ.get("LINKZIP_API_KEY")
  • Handle Rate Limits: If you are running bulk automation, introduce a short pause between requests using the time module to avoid triggering rate limit warnings:
    import time
    time.sleep(0.5)  # Pause for 500 milliseconds between API requests

5. Frequently Asked Questions (FAQ)

What error does the API return if a custom alias is already taken?

The LinkZip API will return an HTTP status code 409 Conflict with a JSON payload explaining that the alias is already in use. The response.raise_for_status() line in our script will capture this and raise an exception.

Does the script work on Python 2?

No, the script utilizes modern Python 3 libraries and practices. Python 2 has been officially deprecated.

Yes. No matter if a link is created through the web interface or programmatically via the Python API, it is automatically tracked. Any clicks on the resulting short link will populate real-time geo and device metrics in your LinkZip dashboard.


Conclusion

Automating your digital marketing workflow with Python and LinkZip.uk is a powerful way to save time and eliminate human error. In just a few lines of code, you can easily integrate secure URL shortening and analytics tracking into your scripts. Put this script to work in your automation pipelines and start analyzing your campaign click metrics programmatically.