
Key takeaways:
- For general URLs, the standard library is enough: urlencode builds query strings, quote and quote_plus encode path and query values, and urlunparse assembles the parts.
- Watch urljoin: if the base URL does not end with a slash, it replaces the last path segment instead of appending to it.
- For Cloudinary media URLs, let the SDK build them. CloudinaryImage(…).build_url() and cloudinary_url() return the URL; CloudinaryImage(…).image() returns an HTML img tag.
- Prefer f_auto over a fixed format such as f_webp so each browser gets the best format it supports, and sign URLs when transformations should not be editable.
Many businesses and platforms dynamically build URLs to serve various goals like advertising, media optimizations, metrics tracking, and more. In media optimization, image transformation techniques, such as resizing, cropping, and formatting, using python to construct URLs allow you to adapt images to various devices and contexts.
At the heart of this process are URLs, which serve as the primary means for accessing and manipulating media assets, enabling seamless delivery and on-the-fly transformations. For many media files, the URLs not only point to the file but can also contain instructions for how the media should be transformed before delivery.
In this article, we’ll explore why URL construction is essential in media workflows, how you can use python to construct URLs, and the best practices to follow to ensure your approach is maintainable and secure.
In this article:
- Why Constructing URLs Matters in Media Workflows
- Common Python Tools for URL Construction
- urllib, requests, yarl or the Cloudinary SDK: Which Should You Use?
- Cloudinary and Python: Building Image Transformation URLs
- Addressing Common URL Building Issues
- Best Practices for Maintainable and Scalable URL Construction
Why Constructing URLs Matters in Media Workflows
Constructing URLs effectively is crucial in media workflows because they are the foundation for accessing and managing digital assets, such as videos and images. Here’s some of the importance of URL construction in media delivery.
- Improved user experience: URLs play a crucial role in enhancing the user experience. For instance, clean and descriptive URLs are more likely to drive engagement and increase click-through rates. They also make it easier for users to understand what to expect when clicking a link, contributing to trust and usability.
- Improved SEO performance: Descriptive URLs that include relevant keywords can significantly boost SEO value. Search engines like Google favor URLs that clearly reflect page content. Google also provides best practices for optimizing URLs to help your content rank higher in search results.
- Dynamic content delivery: Constructing URLs with query parameters enables real-time image and media transformations, such as resizing, cropping, and format conversion, without needing to upload multiple versions. This allows you to serve optimized content based on device type, screen resolution, or user preferences.
- Tracking and analytics: URLs are key tools for tracking campaign performance and understanding user behavior. By embedding parameters like UTM tags, you can monitor traffic sources, user engagement, and conversion rates, helping marketing and product teams make data-driven decisions.
- Easy access and management: In development and team environments, URLs allow for quick and easy access to media assets, whether for design reviews, marketing collateral, integration with content management systems, facilitating collaboration and sharing among team members and stakeholders.
Common Python Tools for URL Construction
Python is a popular programming language with built-in and third-party libraries that make constructing URLs simple and efficient. In this section, we’ll look at some of the tools you can use to create complex URLs in your Python applications.
Using urllib and urllib.parse
urllib is a built-in Python library that contains a collection of modules for working with URLs. It contains:
urllib.requestfor opening and reading resourcesurllib.errorcontaining the exceptions raised byurllib.requesturllib.parsefor parsing and building URLsurllib.robotparserfor parsingrobots.txtfiles
A typical URL has various parts including the scheme (such as http or https), domain (like google.com), optional port (such as :8080), path (which specifies the location of the resource on the server), and query parameters (used to pass data in key-value pairs).
Here’s an example of a URL with query parameters:
https://www.example.com/products/shoes?id=1234&color=black
Now let’s explore how to use the urllib.parse module to construct URLs in object-oriented way in Python. This method is especially useful when you need to build URLs repeatedly or manipulate different parts dynamically.
from urllib.parse import urlencode, urlunparse
class URLBuilder:
def __init__(self, scheme='https', domain='', port=None, path='', query_params=None):
self.scheme = scheme
self.domain = domain
self.port = port
self.path = path
self.query_params = query_params or {}
def set_scheme(self, scheme):
self.scheme = scheme
return self
def set_domain(self, domain):
self.domain = domain
return self
def set_port(self, port):
self.port = port
return self
def set_path(self, path):
self.path = path
return self
def add_query_param(self, key, value):
self.query_params[key] = value
return self
def build(self):
# Combine domain and port (if provided)
full_domain = self.domain
if self.port:
full_domain += f":{self.port}"
# Encode query parameters
query = urlencode(self.query_params)
# Build and return the final URL
return urlunparse((self.scheme, full_domain, self.path, '', query, ''))
# Usage
url = (
URLBuilder()
.set_scheme('https')
.set_domain('www.example.com')
.set_path('/products/shoes')
.add_query_param('id', '1234')
.add_query_param('color', 'black')
.build()
)
print(url)
# Output: https://www.example.com/products/shoes?id=1234&color=black
Leveraging requests and Other Popular Libraries
requests is a third-party Python library that simplifies making HTTP requests in Python applications but also helps in URL building. Requests is also one of the most downloaded Python libraries, with over 300 million monthly downloads.
While the requests library is mostly used for HTTP operations, the prepare_url method of the PreparedRequest object can be used for using Python to construct URLs.
First, you’ll need to install requests with the following command:
python -m pip install requests
Then use it like so:
from requests.models import PreparedRequest
req = PreparedRequest()
req.prepare_url("https://example.com/api/image", {"format": "webp", "quality": "80"})
print(req.url)
# Output: https://example.com/api/image?format=webp&quality=80
urllib, requests, yarl or the Cloudinary SDK: Which Should You Use?
| Tool | What it does well | Use it when |
|---|---|---|
| urllib.parse | Encoding (urlencode, quote, quote_plus), parsing and assembling URLs | You want no dependencies and full control |
| requests | Adds query parameters when it prepares a request | You are about to send the request anyway |
| yarl | Immutable URL objects with methods such as with_path, with_query and update_query | You build and modify many URLs in one codebase |
| Cloudinary Python SDK | Builds media URLs with transformations, versions and signatures in the right order | The URLs point to images or videos in Cloudinary |
For media URLs, the SDK matters because transformation URLs have rules a generic builder does not know: the order of transformation components, the version segment and the signature all affect whether the URL works.
Cloudinary and Python: Building Image Transformation URLs
Cloudinary enables dynamic, on-the-fly image transformations through URL-based parameters. With just a few adjustments, you can use Python to construct URLs that:
- Optimize image delivery by automatically adjusting quality, format, and dimensions based on the user’s device or bandwidth.
- Apply visual enhancements like filters, effects, and overlays to maximize engagement.
- Use Generative AI for intelligent cropping, background removal, or style transformations.
Here’s an example of a transformation URL with filters applied to it:
https://res.cloudinary.com/demo/image/upload/c_thumb,g_face,h_200,w_200/r_max/f_auto/woman-blackdress-stairs.png
To Python to construct URLs, you can use Cloudinary’s Python SDK, which gives you programmatic access to construct URLs from within your Python applications. Additionally, you can use the Transformation Builder to try things out yourself before diving into code and get a sense of how URL transformation with Cloudinary works.
Want to see what the Cloudinary Python SDK can do? Look at our documentation to find out more.
You can install Cloudinary in your application with Pip as follows:
pip install cloudinary
Here’s example code to generate a transformation URL with Cloudinary in Python:
import cloudinary
import cloudinary.uploader
import cloudinary.api
from cloudinary import CloudinaryImage
cloudinary.config(
cloud_name="your_cloudinary_cloud_name",
api_key="your_cloudinary_api_key",
api_secret="your_cloudinary_api_secret",
secure=True
)
transformedURL = CloudinaryImage("your_image.png").build_url(
transformation=[
{"width": 500, "crop": "scale"},
{"quality": "auto"},
{"fetch_format": "webp"}
# If you need to add more transformations,
# simply add more dictionaries to the list.
]
)
print(transformedURL)
The above code applies the following transformations to the uploaded image:
c_scale,w_500– Scales the image to 500px width while maintaining aspect ratioq_auto– Tells Cloudinary to apply automatic quality optimization to the imagef_webp– Tells Cloudinary to deliver the image in WebP format
Here’s what the resulting transformation URL will look like:
https://res.cloudinary.com/your_cloud_name/image/upload/c_scale,w_500/q_auto/f_webp/your_image.png
You can read more about Python image transformations in the Cloudinary docs.
How Do You Build f_auto and Signed URLs in Python?
The example above forces WebP with f_webp. In most cases f_auto is the better choice, because it delivers each image in the optimal format for the requesting browser. And when users should not be able to change the transformation in a URL, sign it: the SDK adds a signature segment that Cloudinary checks against your API secret.
from cloudinary.utils import cloudinary_url
# Let Cloudinary choose the format per browser instead of forcing WebP
url, _ = cloudinary_url(
"your_image.png",
transformation=[
{"width": 500, "crop": "scale"},
{"quality": "auto", "fetch_format": "auto"},
],
)
# https://res.cloudinary.com/<cloud_name>/image/upload/c_scale,w_500/f_auto,q_auto/your_image.png
# Sign the URL so nobody can edit the transformation in it
signed_url, _ = cloudinary_url("your_image.png", width=500, crop="scale", sign_url=True)
# https://res.cloudinary.com/<cloud_name>/image/upload/s--<signature>--/c_scale,w_500/your_image.png
A signature on its own stops visitors from creating new transformations only when strict transformations are enabled. To keep the asset itself private, upload it with the authenticated delivery type, which requires a signed URL for the original and every derived version.
Addressing Common URL Building Issues
While constructing URLs might seem straightforward, there are several challenges that can arise, impacting security, maintainability and other aspects of URL construction. Here, we’ll take a comprehensive look at some common issues you might encounter when working with URLs, and how you can solve them.
Manage Query Parameters and Encodings
URLs often include query parameters to pass data to the server (e.g., ?search=example&page=2). These parameters can contain special characters such as spaces, &, ?, and so on, which have specific meanings in URLs and must be properly encoded to avoid misinterpretation.
One efficient solution is to use Python’s urllib.parse.urlencode to convert dictionaries of parameters into URL-encoded strings. This replaces special characters with their percent-encoded equivalents. For instance, space becomes + and ampersand becomes %26.
Here’s an example:
from urllib.parse import urlencode
params = {
"search": "Tennis shoes",
"page": 2,
"sort": "recent",
"filter": "price <= 100",
"user": "admin&test"
}
# Convert dictionary to a URL-encoded string
encoded_params = urlencode(params)
print(encoded_params)
Output:
search=Tennis+shoes&page=2&sort=recent&filter=price+%3C%3D+100&user=admin%26test
Debug and Validate Constructed URLs
When constructing complex URLs with multiple parameters and transformations, it’s easy to make mistakes that lead to invalid or incorrect URLs. These errors can be difficult to track down and debug.
One good way to prevent this is to print the constructed URLs to the console or use a debugger to inspect them before using them in production. Additionally, you can make use of requests.get(url).status_code to check if your links return 404 error before making them public.
Best Practices for Maintainable and Scalable URL Construction
When building URLs, there are a few things that could go wrong. To avoid these problems and make sure your URL building process stays consistent and maintainable over time, here are some best practices you should consider:
- Break down URL construction into smaller, reusable functions or classes. This makes the code easier to understand, test, and modify.
- Use descriptive names for URLs to improve readability, SEO, and engagement.
- Store base URLs and common parameters in configuration files or constants rather than hardcoding them. This makes it easier to update URLs if the server or API changes.
- Follow a consistent URL structure across your application. This makes it easier to understand and maintain the URLs, and it can also improve SEO.
- Validate URLs before use to ensure they work as intended and lead to the right resource.
- Always treat user-provided input with caution. Sanitize and encode any user input before incorporating it into a URL to prevent URL injection attacks.
Frequently Asked Questions
How do you build a URL with query parameters in Python?
Put the parameters in a dictionary and pass it to urllib.parse.urlencode, which percent-encodes each key and value and joins them with ampersands. Then combine the result with the rest of the URL, either with urlunparse as in the URLBuilder example or by appending it after a question mark. Never concatenate raw user input into a URL without encoding it.
What is the difference between quote and quote_plus?
quote encodes a value for the path of a URL: a space becomes %20 and slashes are kept by default, so quote(“summer sale/hero 1.jpg”) gives summer%20sale/hero%201.jpg. quote_plus encodes for query strings and HTML forms: spaces become plus signs and slashes are encoded, giving summer+sale%2Fhero+1.jpg. urlencode uses quote_plus by default.
Why does urljoin drop part of my path?
urljoin treats the base URL like a browser does: the last segment is a file unless the base ends with a slash. So urljoin(“https://cdn.example.com/media”, “photo.jpg”) returns https://cdn.example.com/photo.jpg, while the same call with a base ending in /media/ returns https://cdn.example.com/media/photo.jpg. Keep a trailing slash on base URLs you join to.
How do you generate a Cloudinary image URL in Python?
Install the SDK with pip install cloudinary, configure your cloud name, and call CloudinaryImage(“public_id”).build_url(transformation=[…]) or cloudinary.utils.cloudinary_url(“public_id”, …). Both return the delivery URL as a string. CloudinaryImage(…).image() is different: it returns a complete HTML img tag, which is useful in templates but not when you need the URL itself.
