URI Template (std-uritemplate)
std-uritemplate is a Python library providing a robust and compliant implementation of RFC 6570, the URI Template specification. It allows users to expand URI templates with provided variables, generating complete URIs. The library is actively maintained, with frequent patch releases within major versions, and is currently at version 2.0.8.
Warnings
- breaking Version 2.0.0 introduced a significant API change. The `URITemplate` class is now the primary entry point for working with URI templates, replacing the direct `uritemplate.expand` and `uritemplate.partial_expand` functions.
- deprecated The standalone functions `uritemplate.expand()` and `uritemplate.partial_expand()` have been deprecated in favor of the methods on the `URITemplate` class.
- gotcha The library strictly adheres to RFC 6570. Misunderstandings of the RFC's nuances regarding variable modifiers (e.g., `+`, `#`, `.`, `/`, `;`, `?`, `&`) or how different variable types (simple, lists, dictionaries) are expanded can lead to unexpected URI outputs.
- gotcha The package name for installation is `std-uritemplate`, but the Python module to import is `uritemplate`. This is a common source of `ModuleNotFoundError`.
Install
-
pip install std-uritemplate
Imports
- URITemplate
from uritemplate import URITemplate
Quickstart
from uritemplate import URITemplate
template_str = "https://example.com/api/{resource}{?id,name}"
tpl = URITemplate(template_str)
# Expand with simple variables
expanded_uri = tpl.expand(resource="users", id=123, name="Alice")
print(f"Expanded URI: {expanded_uri}")
# Partial expansion
partially_expanded_tpl = tpl.partial_expand(resource="posts")
print(f"Partially Expanded URI (with resource): {partially_expanded_tpl.template}")
# Final expansion of partially expanded template
final_uri = partially_expanded_tpl.expand(id=456)
print(f"Final URI: {final_uri}")