How to Prefix Python API URIs with a Version Slug

Build a versioned API endpoint by optionally adding a version prefix like v1 to the URL path using the stdlib urllib module.

Easy Python 3.9+ Aug 9, 2026 API design & gRPC 12 views 0 copies

Python code

14 lines
Python 3.9+
from urllib.parse import urlparse

BASE_URL = "https://api.example.com"

def build_uri(resource, version="v1"):
    """Mock a versioned API URI with an optional v1 prefix."""
    parsed = urlparse(BASE_URL)
    prefix = f"/{version}" if version else ""
    return f"{parsed.scheme}://{parsed.netloc}{prefix}/{resource.lstrip('/')}"

if __name__ == "__main__":
    print(build_uri("users"))
    print(build_uri("orders/123", version="v2"))
    print(build_uri("health", version=None))

Output

stdout
https://api.example.com/v1/users
https://api.example.com/v2/orders/123
https://api.example.com/health

How it works

The urlparse call splits the base URL into scheme and netloc, which are then recombined with the route. The version prefix is inserted only when provided, otherwise the resource is used directly. Using lstrip removes any leading slashes from the resource path to avoid double slashes. The function handles v2 and None prefixes consistently, giving you a simple mock for API versioning.

Common mistakes

  • Forgetting to strip leading slashes from the resource path, causing double slashes.
  • Hardcoding the version into the resource instead of passing it as a parameter.
  • Using string formatting without URL parsing, breaking when the base URL contains a path.

Variations

  1. Use `posixpath.join` or `pathlib.PurePosixPath` for more robust path joining.
  2. Store versions as constants or enums for stricter API contract enforcement.

Real-world use cases

  • Generating client URLs for public API endpoints that require a version prefix.
  • Mocking request targets in unit tests without hitting the network.
  • Building configurable SDKs where users can choose between API versions.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from API design & gRPC

Related tutorials and quizzes for this topic.