Build a URL Shortener Client with Python
A Python class that shortens long URLs and resolves short codes using a REST API built with requests.
pip install requests
Python code
35 linesimport json
import sys
import requests
class URLShortenerClient:
def __init__(self, base_url="http://tinyurl.com"):
self.base_url = base_url
def shorten_url(self, long_url):
payload = {"url": long_url}
headers = {"Content-Type": "application/json"}
response = requests.post(f"{self.base_url}/api/url/", json=payload, headers=headers)
if response.status_code == 201:
data = response.json()
return data.get("short_url", "Short URL not found in response")
else:
return f"Error: {response.status_code} - {response.text}"
def resolve_url(self, short_code):
response = requests.get(f"{self.base_url}/api/url/{short_code}")
if response.status_code == 200:
data = response.json()
return data.get("long_url", "Long URL not found in response")
else:
return f"Error: {response.status_code} - {response.text}"
if __name__ == "__main__":
client = URLShortenerClient()
long_url = "https://www.example.com/very/long/url/that/needs/shortening"
short = client.shorten_url(long_url)
print(f"Shortened URL: {short}")
if not short.startswith("Error"):
short_code = short.split("/")[-1]
resolved = client.resolve_url(short_code)
print(f"Resolved URL: {resolved}")
Output
Shortened URL: https://tinyurl.com/abc123
Resolved URL: https://www.example.com/very/long/url/that/needs/shortening
How it works
The URLShortenerClient class wraps API calls to a URL shortening service. The shorten_url method sends a POST request with the long URL in JSON format and extracts the short URL from a successful 201 response. The resolve_url method performs a GET request using the short code (the last segment of the short URL) and returns the original long URL. Error handling checks the HTTP status code to return a descriptive message if the API call fails.
Common mistakes
- Assuming the API always returns status 201 for a successful creation — some services use 200.
- Hard-coding the API base URL without making it configurable for different services.
- Not handling network errors (e.g., timeouts, connection refused) that raise exceptions in requests.
- Extracting the short code from the short URL with split() — the URL format may differ across providers.
Variations
- Use urljoin from urllib.parse to safely join base URL and endpoint paths.
- Support custom expiration or alias parameters in the POST request payload.
Real-world use cases
- Integrating link shortening into a social media scheduler to post shorter URLs.
- Building a customer support tool that logs short links for tracking shared resources.
- Creating a CLI utility for DevOps teams to generate short references to long deployment URLs.
Sponsored
Keep learning
Related tutorials and quizzes for this topic.