rfc3986 is a Python implementation of RFC 3986 including validation and authority parsing. This module also supports RFC 6874, which adds support for zone identifiers to IPv6 Addresses. It provides APIs for parsing, validating, and building URIs, with convenience methods for `urllib.parse` compatibility. The current version is 2.0.0, released in January 2022, and the project appears to be actively maintained.
pip install rfc3986Verified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to parse a URI string into a `URIReference` object, access its components, validate it using a `Validator` instance with custom rules, and construct a new URI using `URIBuilder`.
Always ensure URIs conform strictly to RFC 3986, especially by including `//` before the authority. For compatibility with `urllib.parse`'s looser parsing, use `rfc3986.urlparse()` but be aware of its limitations and the stricter RFC 3986 interpretation.
If IRI support is required, consider using a different library (e.g., `rfc3987` or `uritools` with caution) or pre-process IRIs to ensure they are RFC 3986 compatible before passing them to `rfc3986`.
For critical security-sensitive URI validation, do not solely rely on `is_valid()`. Implement additional checks for hostname formats and port number ranges, or combine with a custom `Validator` instance that explicitly defines allowed components.
If you need to extend path components or append to query parameters, retrieve the existing components, manipulate them as strings or lists, and then pass the complete new value to `copy_with`. Alternatively, use `URIBuilder` and its methods for more controlled incremental building.
To specify schemes for validation, pass each scheme as a separate argument (e.g., `validator.allow_schemes('https', 'http')`). If you have a list of schemes, unpack it using the `*` operator: `validator.allow_schemes(*['https', 'http'])`.When using `Validator.allow_schemes()`, provide each scheme as a separate string argument. If you have a list of schemes, unpack it using the `*` operator (e.g., `validator.allow_schemes(*my_schemes)` or `validator.allow_schemes('https')` for a single scheme).from rfc3986 import URIReference
try:
uri = URIReference.from_string('https://example.com/path') # Correct URI
except URIReference.InvalidURIError as e:
print(f"Error: {e}")from rfc3986 import URIReference
uri = URIReference.from_string('https://example.com')from rfc3986 import URIReference
uri = URIReference.from_string('/path/to/resource') # A relative URI without authority
if uri.authority:
print(uri.authority.host)
else:
print("No authority component for this URI")