Backend Development 5 min read

Batch Shortening and Expanding URLs with Python

This article explains how to use Python to convert hundreds of long URLs into short ones and later restore them, covering the rationale for short links, free and paid service options, and providing complete code examples for both shortening and expanding URLs.

IT Services Circle
IT Services Circle
IT Services Circle
Batch Shortening and Expanding URLs with Python

When you need to transform hundreds of long URLs into short ones—and optionally revert them—Python offers a simple solution using HTTP APIs.

Why Use Short Links

Short URLs are essential for marketing messages, SMS, emails, and social media because they reduce character count and improve click‑through rates.

Service Options

Free online tools exist but may be unstable; a recommended aggregator is woobx.cn . Paid services provide reliability but require a subscription.

Python Code for Shortening (Free Service)

The following script URL‑encodes the target link, calls the 3w.cn API, and prints the shortened URL.

from urllib.parse import quote
import requests
import json

# Encode the long URL
url = "https://mp.weixin.qq.com/s?__biz=MzU5Nzg5ODQ3NQ==∣=2247521340&idx=1&sn=90bdde598d4a8f14f582387e702c2c2f&chksm=fe4eb1b8c93938ae18f605a5e42d08c4ab7a83ee2d5a03b27763126e64d77cd1600cf256eb01#rd"
url = quote(url)
key = "***********************"

# Request the API to shorten the URL
html = requests.get(f"http://api.3w.cn/api.htm?format=json&url={url}&key={key}&expireDate=2050-01-01&domain=21").content
data = json.loads(html.decode('utf-8'))
print(data["url"])

The quote function prevents characters like = and & from breaking the request.

Python Code for Expanding a Short Link

Restoring a short URL is even simpler—just send a HEAD request and read the Location header.

import requests

url = "https://sourl.cn/AWeBWs"
res = requests.head(url)
print(res.headers.get('location'))

This prints the original long URL.

Conclusion

Although URL shortening may seem niche, the provided Python snippets enable bulk processing and quick retrieval of original links, which can be valuable in many automation scenarios.

backendPythonAutomationAPIRequestsURL Shortening
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.