MEDIA GUIDES / Front-End Development

How to Use Python to Construct URLs for Media Optimization and Image Transformations

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

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.request for opening and reading resources
  • urllib.error containing the exceptions raised by urllib.request
  • urllib.parse for parsing and building URLs
  • urllib.robotparser for parsing robots.txt files

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

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").image(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 ratio
  • q_auto – Tells Cloudinary to apply automatic quality optimization to the image
  • f_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.

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.
QUICK TIPS
Colby Fayock
Cloudinary Logo Colby Fayock

In my experience, here are tips that can help you better construct Python-based URLs for media optimization and image transformations:

  1. Use transformation profiles as serialized templates
    Store transformation patterns (like thumbnail, banner, avatar) in serialized formats (YAML/JSON) and load them dynamically in Python. This separates concerns and allows easier UI-to-backend mapping in headless CMS or design systems.
  2. Introduce transformation chaining logic for multi-step modifications
    Instead of flat parameters, structure your Python transformation builder to support sequential transformation steps (e.g., crop then overlay then format). This matches advanced services like Cloudinary and prevents accidental order-dependent bugs.
  3. Normalize and sanitize all dynamic path segments
    When users provide file names, ensure they’re stripped of whitespace, special characters, or directory traversal attempts. Combine slugify utilities and regex validation to protect media URL integrity and avoid security exploits.
  4. Support contextual versioning for transformation cache busting
    Include a hash or version number tied to transformation rules in the URL path or query to avoid stale caches when transformation logic updates—useful for CDNs and browser caching.
  5. Utilize URL fragments to trigger client-side rendering cues
    While uncommon, image URLs with fragments (e.g., #mobile) can be used to trigger frontend logic, such as lazy loading behavior or conditional overlays—pairing Python URL builders with SPA apps effectively.
  6. Set up unit tests for URL builder integrity
    Treat your URL construction like an API. Use unittest or pytest to ensure consistency and prevent regression when transformations or base paths change. Include validation for common cases and edge scenarios.
  7. Integrate localization tokens into media paths
    For multilingual sites, build URLs that automatically insert locale prefixes (e.g., /fr/media/) to serve localized media and fallback logic. This allows centralized handling of language-based content delivery.
  8. Use dynamic subdomains or buckets for tenant-based media
    If managing media for multiple clients, programmatically switch subdomains or S3 buckets in your Python builder to isolate asset delivery (e.g., tenant1.images.com vs tenant2.images.com) without duplicating logic.
  9. Design with image CDN fallback chains
    Use chained or redundant domains in your URL logic (e.g., cdn1.example.com, fallback cdn2.example.com) and cycle through them on status code errors—Python makes this failover logic easy to embed.
  10. Generate signed, expiring URLs for private asset delivery
    Combine your Python URL logic with HMAC or JWT tokens and expiration timestamps to build time-bound URLs for private media, preventing hotlinking or unauthorized sharing of premium content.
Last updated: Apr 30, 2025