RFC 6570 URI Template Processor
The `uri-template` library provides an implementation of RFC 6570 URI Templates in Python. It supports template expansion in strict adherence to the RFC, while also introducing several extensions for handling non-string values, nested structures, and partial expansions. The current version is 1.3.0, released in June 2023. It appears to be maintained with a slower release cadence by a single maintainer.
Warnings
- gotcha There are two similarly named, but distinct, PyPI packages for URI templates: `uri-template` (this package, with a hyphen) and `uritemplate` (without a hyphen). They have different APIs, features, and maintenance statuses. Ensure you install and use the correct package according to your project's needs.
- gotcha The `uri-template` library extends RFC 6570 to handle non-string values and nested data structures (lists, dicts, booleans) by converting them or flattening them in specific ways. While convenient, this behaviour deviates from strict RFC 6570 and may lead to unexpected results if not understood.
- gotcha The `URITemplate.expand()` and `uri_template.expand()` methods can raise an `ExpansionFailed` exception if a composite value (e.g., a list or dictionary) is provided for a variable that uses a prefix modifier (e.g., `{var:10}`).
- gotcha This library only supports default *string* values for variables, as in `{foo=bar}`. It does not currently support default values for lists or associative arrays.
Install
-
pip install uri-template
Imports
- expand
from uri_template import expand
- partial
from uri_template import partial
- URITemplate
from uri_template import URITemplate
Quickstart
from uri_template import URITemplate, expand
# Using the expand function for a simple, one-off expansion
uri_str = "http://example.com/api/{resource}/{id}"
expanded_uri_func = expand(uri_str, resource='users', id='123')
print(f"Function expanded: {expanded_uri_func}")
# Using the URITemplate class for repeated expansions or advanced features
template = URITemplate("http://example.com/search{?query,limit}")
expanded_uri_class = template.expand(query='python', limit=10)
print(f"Class expanded: {expanded_uri_class}")
# Example of partial expansion
partial_template = URITemplate("http://example.com/items/{category}/{item_id}")
partially_expanded = partial_template.partial(category='electronics')
print(f"Partially expanded: {partially_expanded}")
# Further expand the partially expanded template
final_expanded = partially_expanded.expand(item_id='laptop-x')
print(f"Further expanded: {final_expanded}")