How to Shorten URLs with Python
By Urlzee Team · Published · 5 min read
To shorten a URL in Python, post the long URL to a shortener's API with the requests library and read the short link from the JSON reply. With the Urlzee API it takes about eight lines. This guide builds from that first call to a small client with error handling, retries and a bulk CSV job.
What do you need to set up?
Python 3.8 or newer, the requests package and an API key.
- Install the library:
python3 -m pip install requests
- Create a free Urlzee account, open Dashboard → API keys and create a key. Copy it straight away, because it is displayed once.
- Export the key so your scripts can read it:
export URLZEE_API_KEY="uz_live_YOUR_KEY"
On Windows PowerShell the equivalent is $env:URLZEE_API_KEY = "uz_live_YOUR_KEY".
How do you shorten a single URL?
This is the complete program:
import os
import requests
res = requests.post(
"https://urlzee.com/api/v1/links",
headers={"Authorization": f"Bearer {os.environ['URLZEE_API_KEY']}"},
json={"url": "https://example.com/a/very/long/page"},
timeout=10,
)
res.raise_for_status()
print(res.json()["data"]["short_url"])
A few things are happening:
json=serialises the dictionary and sets theContent-Type: application/jsonheader for you.timeout=10matters. Without it,requestswill wait indefinitely on a stalled connection.raise_for_status()turns any 4xx or 5xx reply into an exception.- The link is under the
datakey, which also holdsid,slug,destination,title,clicks,is_active,expires_atandcreated_at.
A successful creation returns status 201.
How do you add an alias, title or expiry date?
Add fields to the JSON body.
| Field | Purpose | Rules |
|---|---|---|
url | Destination (required) | http or https, at most 2,048 characters |
alias | Custom ending | 3 to 50 characters: letters, numbers, -, _ |
title | Label in your dashboard | Up to 200 characters |
expires_at | When the link stops working | ISO 8601 date; Pro and Business plans |
payload = {
"url": "https://example.com/launch",
"alias": "launch",
"title": "Launch page",
}
Sent with the same requests.post call, that produces https://urlzee.com/launch if the alias is available.
How do you build a reusable client with proper errors?
raise_for_status() tells you that something failed but hides the API's explanation. A small wrapper keeps the useful parts: the status, the error code and the Retry-After value. Save this as urlzee.py.
import os
import requests
API = "https://urlzee.com/api/v1"
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['URLZEE_API_KEY']}"
class UrlzeeError(Exception):
def __init__(self, status, code, message, retry_after=None):
super().__init__(message)
self.status = status
self.code = code
self.retry_after = retry_after
def call(method, path, **kwargs):
res = session.request(method, f"{API}{path}", timeout=10, **kwargs)
try:
body = res.json()
except ValueError:
body = {}
if not res.ok:
err = body.get("error", {})
retry_after = res.headers.get("Retry-After")
raise UrlzeeError(
res.status_code,
err.get("code", "http_error"),
err.get("message", f"HTTP {res.status_code}"),
int(retry_after) if retry_after else None,
)
return body
def shorten(url, **fields):
return call("POST", "/links", json={"url": url, **fields})["data"]
A requests.Session reuses the underlying connection, which makes repeated calls noticeably quicker than opening a new connection each time, and it sends the Authorization header on every request.
Using the client:
from urlzee import shorten, UrlzeeError
try:
link = shorten("https://example.com/launch", alias="launch")
print(link["short_url"])
except UrlzeeError as err:
if err.code == "alias_taken":
print("That alias is in use. Choose another.")
elif err.status == 422:
print(f"Rejected: {err}")
elif err.status == 401:
print("Check URLZEE_API_KEY.")
else:
raise
Errors from the API always look like {"error": {"code": "...", "message": "..."}}. The codes you are most likely to meet are unauthorized (401), plan_required (403), alias_taken (409), alias_invalid and the url_ family (422), and rate_limited (429). A 422 on the URL means Urlzee refused the destination: it was malformed, pointed at a private address or another shortener, or was flagged as unsafe.
How do you shorten a CSV file of URLs?
Read rows, shorten each, write results, and never let one bad row end the run. Assume an input file links.csv:
url,alias
https://example.com/products/linen-apron,apron
https://example.com/products/oak-board,
https://example.com/products/tea-towel-set,tea-towels
The script:
import csv
import time
from urlzee import shorten, UrlzeeError
def shorten_with_retry(url, alias, attempts=3):
fields = {"alias": alias} if alias else {}
for attempt in range(1, attempts + 1):
try:
return shorten(url, **fields)
except UrlzeeError as err:
wait = err.retry_after
if err.status != 429 or wait is None or wait > 60 or attempt == attempts:
raise
time.sleep(wait)
with open("links.csv", newline="") as src, open("short_links.csv", "w", newline="") as dst:
writer = csv.DictWriter(dst, fieldnames=["url", "short_url", "error"])
writer.writeheader()
for row in csv.DictReader(src):
url = row["url"].strip()
alias = (row.get("alias") or "").strip()
try:
link = shorten_with_retry(url, alias)
writer.writerow({"url": url, "short_url": link["short_url"], "error": ""})
except UrlzeeError as err:
writer.writerow({"url": url, "short_url": "", "error": str(err)})
Three design choices are deliberate:
- Sequential requests. The per-minute limit is 10 requests on Free, 60 on Pro and 300 on Business. A simple loop stays close to those limits and the retry handles the rest.
- A ceiling on the wait. A 429 can also mean the monthly quota is used up, in which case
Retry-Afteris usually far too long to sleep through. The script only waits when the delay is a minute or less; otherwise it records the error. - An error column. Failed rows are written with the reason, so you can fix them and run only those again.
Every created link counts toward your plan's monthly link allowance, which is 50 on Free. For a one-off list you can skip the code and paste it into the bulk URL shortener. The spreadsheet preparation is covered in the bulk URL shortening guide.
How do you list, update and delete links?
The call helper handles every endpoint. Use the id from a link, not its slug.
from urlzee import call
# List links, newest first (limit can be 1-100)
page = call("GET", "/links", params={"page": 1, "limit": 25})
print(page["total"], "links in total")
if page["data"]:
link_id = page["data"][0]["id"]
# Pause the link (works on every plan)
call("PATCH", f"/links/{link_id}", json={"is_active": False})
# Click statistics for the last 30 days
stats = call("GET", f"/links/{link_id}/stats", params={"days": 30})
print(stats["data"])
# Delete permanently
call("DELETE", f"/links/{link_id}")
The example pauses and then deletes the newest link in your account, so point it at a test link before running it. PATCH also accepts title, and on Pro or Business url and expires_at. Changing url lets you repoint an existing short link without reissuing it.
What should you watch out for?
- Do not embed the key in a script you share. Read it from the environment, as above. See API key security best practices.
- Count your requests. Listing pages and stats calls use the same quota as link creation: 100 requests a month on Free, 10,000 on Pro.
- Store the
id. Save it next to the short URL in your own database. You need it to update the link or fetch its statistics later. - Treat network errors separately.
requests.exceptions.ConnectionErrorandTimeoutare not API errors. Catch them where a retry makes sense.
For a walk through the raw HTTP requests, see the URL shortener API getting-started guide; the field-by-field reference is the API documentation.
Frequently asked questions
- Which Python library should I use to shorten URLs?
- The requests library is enough. A shortener API such as Urlzee's is plain JSON over HTTPS, so you post the long URL and read the short one from the response without needing a dedicated package.
- How do I shorten a list of URLs from a CSV file in Python?
- Read the file with csv.DictReader, send one POST request per row, and write each short URL to an output file with csv.DictWriter. Pause when the API returns 429 and record failed rows instead of stopping the whole job.
- How do I keep my API key out of my Python code?
- Read it from an environment variable with os.environ. Set the variable in your shell, your scheduler or your hosting platform's secret settings, and never commit it to a repository.
- Can I set a custom alias when shortening with Python?
- Yes. Add an alias field to the JSON body, using 3 to 50 letters, numbers, hyphens or underscores. If the alias is already taken, the Urlzee API responds with status 409 and the code alias_taken.