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.
Python code
14 linesfrom 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
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
- Use `posixpath.join` or `pathlib.PurePosixPath` for more robust path joining.
- 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
More from API design & gRPC
- Build a Bulk Array POST Mock Server in Python medium
- Build a Mock REST API with PUT and GET in Python medium
- Convert Protobuf to JSON and Dict in Python easy
- Create a Data Helper in Python for gRPC-style APIs easy
- Format data in Python using dataclasses like gRPC messages easy
- Generate an OpenAPI Spec from Mock Routes in Python easy
Keep learning
Related tutorials and quizzes for this topic.