API reference
This API reference is intended mainly for developers and people looking for in-depth description of the different classes and functions. If you simply want to configure models and parse values into hyperlinks, Getting started gives a better introduction to using the library.
Fundamentals
The two main building blocks of the hrefs
library are
Href
, the class representing hyperlinksReferrable
, the abstract base class of types that can be targets of hyperlinks
- class hrefs.Href(key, url)
Hypertext reference to another model
The class is generic and can be annotated with a type implementing the
Referrable
ABC. IfBook
is assumed to be a type implementingReferrable
, thenHref[Book]
represents a hyperlink to a book.A user typically doesn’t create a
Href
object manually. It is much more common to usepydantic
to parse it from one of the following:Another
Href
instanceAn instance of the referred model
A value of the key type (interpreted as key identifying the referred object)
A url string (interpreted as URL to the referred object)
See Getting started for more information.
- property key
The key of the referred object
- property url
The URL of the referred object
- class hrefs.Referrable
Abstract base class for the targets of
Href
The subclass needs to implement at least
get_key()
to convert between model and key, andkey_to_url()
andurl_to_key()
to specify the conversions between the key and URL representations. The return types of the functions should be annotated to make them available for parsing and serialization at runtime. Here is an example:class Book(Referrable[int, str]): id: int def get_key(self) -> int: return self.id @staticmethod def key_to_url(key: int) -> str: return f"/books/{key}" @staticmethod def url_to_key(url: str) -> int: return url.split("/")[-1]
- abstract get_key() KeyType
Return the key of the model
- abstract classmethod key_to_url(key: KeyType) UrlType
Convert
key
to URL- Raises:
Exception – the implementation should pass validation related errors (
TypeError
,ValueError
etc.) as is.
- classmethod parse_as_key(value: Any) KeyType | None
Attempt to parse
value
as keyThe default implementation reads the return type annotation of
url_to_key()
, and tries to convertvalue
, swallowingTypeError
andValueError
.- Returns:
value
parameter converted to key type, orNone
if unable to parse
- classmethod parse_as_url(value: Any) UrlType | None
Attempt to parse
value
as URLThe default implementation reads the return type annotation of
key_to_url()
, and tries to convertvalue
, swallowingTypeError
andValueError
.- Returns:
value
parameter converted to URL type, orNone
if unable to parse
- abstract classmethod url_to_key(url: UrlType) KeyType
Convert
url
to key- Raises:
Exception – the implementation should pass validation related errors (
TypeError
,ValueError
etc.) as is.
Pydantic models
Any pydantic model that is a target of
hyperlinks should implement BaseReferrableModel
. It inherits both
pydantic.BaseModel
and hrefs.Referrable
.
- class hrefs.BaseReferrableModel
Referrable pydantic model
A subclass of both
pydantic.BaseModel
andhrefs.Referrable
. It should be used as the base class of any pydantic model that will be used as a target ofhrefs.Href
.BaseReferrableModel
provides implementations ofget_key()
andparse_as_key()
based on field annotations. By default, the model key is theid
field (if it exists), but that can be changed by usingPrimaryKey
to annotate other field or fields.BaseReferrableModel
intentionally has tight coupling to the pydantic library. As such, it relies heavily on the facilities of that library to handle annotations and parsing. The URL type of pydantic based referrable models is alwayspydantic.AnyHttpUrl
.While the model class knows how to extract key types from annotations, it doesn’t know how to convert between keys and URLs. For that, it needs to use a
model.HrefResolver
provided by the web framework integration.Subclassing or initializing instances of a subclass raises
hrefs.ReferrableModelError
in case the library detects the model is incorrectly configured.- get_key() Any
Return the model key
- Returns:
The model key based on the field annotations. If the key is composite, returns a tuple containing the parts.
- classmethod has_simple_key() bool
Query if the model has a simple key
- Returns:
True
if the model has simple (single part) key,False
otherwise
- classmethod key_to_params(key: Any) Dict[str, Any]
Convert model key to path/query parameters of an URL
This is a helper that can be used to convert a model key into a dictionary containing the key parts. Hyperlinks are unwrapped (see Hyperlinks as keys). The dictionary can be used to generate the path and query parameters of URLs in a typical HTTP framework.
- Parameters:
key – model key
- Returns:
A dictionary mapping key names to key parts
- classmethod key_to_url(key) AnyHttpUrl
Convert
key
to URLUses the web framework specific resolution logic to convert the model key to URL (a
pydantic.AnyHttpUrl
instance).- Raises:
hrefs.ReferrableModelError – if the model is incorrectly configured
Exception – validation errors when converting
key
are passed as is
- classmethod params_to_key(params: Mapping[str, Any]) Any
Convert path/query parameters of an URL to model key
This helper can be used to convert a parameter mapping to model key. It is the inverse of
key_to_params()
.- Parameters:
params – A mapping from key names to key parts
- Returns:
Model key parsed from
params
- Raises:
ValueError – if
params
does not contain sufficient elements to construct the key
- classmethod parse_as_key(value: Any) Any | None
Parse
value
as a model keyThe type of the model key is based on the field annotations. Either a single type, or (in the case of a composite key), a tuple of the parts.
- classmethod parse_as_url(value: Any) AnyHttpUrl | None
Parse
value
as an URL (apydantic.AnyHttpUrl
instance)
- classmethod update_forward_refs(**localns: Any) None
Try to update ForwardRefs on fields based on this Model, globalns and localns.
- classmethod url_to_key(url: AnyHttpUrl) Any
Convert
url
to model keyUses the web framework specific resolution logic to convert an URL to the model key based on field annotations.
- Raises:
hrefs.ReferrableModelError – if the model is incorrectly configured
Exception – validation errors when converting
url
are passed as is
- class hrefs.PrimaryKey(type_: Type | None = None, name: str | None = None)
Declare a field in
BaseReferrableModel
as the primary keyPrimaryKey
can be used the following way:from typing import Annotation class MyModel(BaseReferrableModel): my_id: Annotated[int, PrimaryKey] # ...the rest of the definitions...
See Configuring model key for more details.
- Parameters:
type – The underlying key type. This parameter is only used when the key part is a hyperlink whose target is a forward reference. See Hyperlinks as keys.
name – The name of the key. This can be used to override the name of the key part (that normally defaults to the field name).
- class hrefs.HrefsConfigDict
Typed dict that extends
pydantiuc.ConfigDict
with configurations used forBaseReferrableModel
- details_view: str
Name of a view used by web framework integration
Starlette integration
The main motivation for writing this library was to make it easy to use hyperlinks in FastAPI and Starlette applications. See Getting started for a fully working example of how to use these classes.
- class hrefs.starlette.HrefMiddleware(app: Callable[[MutableMapping[str, Any], Callable[[], Awaitable[MutableMapping[str, Any]]], Callable[[MutableMapping[str, Any]], Awaitable[None]]], Awaitable[None]])
Middleware for resolving hyperlinks
Provide the necessary context for resolving hyperlinks for a Starlette app.
- hrefs.starlette.href_context(request_or_app: HTTPConnection | Starlette, *, base_url: str | URL | None = None) ContextManager[_StarletteHrefResolver]
Context manager that sets hyperlink context
Makes
request_or_app
convert between keys and URLs in hyperlinks toBaseReferrableModel
. The context can be either of the following:A
starlette.requests.HTTPConnection
instance – that is a HTTP request or websocketA
starlette.applications.Starlette
instance. Note thatbase_url
needs to be provided when using application to convert the URL path to absolute URL.
href_context()
is used as a context manager that automatically clears the context when exiting.with href_context(request): '''Parse and generate hyperlinks, with base URL from the request'''
If you want to use an application as hyperlink context, you’ll need to provide base URL manually:
with href_context(app, base_url="http://example.com"): '''Parse and generate hyperlinks, with base URL from the argument'''
Note
For normal use where hyperlinks are parsed or generated inside request handlers of a Starlette app, it is recommended to use
HrefMiddleware
to automatically set the context.- Parameters:
request_or_app – The request or app to be used as hyperlink
base_url (context) – The base URL (needed when using application as context)
Custom web framework integrations
Developers of custom web framework integrations that work with
BaseReferrableModel
need to implement a hyperlink resolver that acts as
a bridge between the hrefs
library and the framework.
The implementation of hrefs.starlette
can be used as a reference.
- class hrefs.model.HrefResolver(*args, **kwargs)
Hyperlink resolver for
BaseReferrableModel
subclassesA hyperlink resolver acts as an integration point between models and the web framework. A web framework implements its resolver that encapsulates the general logic of converting between keys and URLs. A model that subclasses
BaseReferrableModel
then uses the visitor pattern on the implemented methods to resolve keys and URLs.A user of the
hrefs
library rarely needs to concern themselves with this class. It is meant as a protocol to be implemented by new web framework integrations.See also
resolve_hrefs()
that is used to inject the active resolver context- abstract key_to_url(key: Any, *, model_cls: Type[BaseReferrableModel]) AnyHttpUrl
Convert key to url
- Parameters:
key – The key to convert. The type of the key is assumed to be the key type of
model_cls
.model_cls – The model class performing the conversion
- Returns:
The URL parsed from
key
- Raises:
hrefs.ReferrableModelError – if the model is incorrectly configured
Exception – validation errors when converting
key
are passed as is
- abstract url_to_key(url: AnyHttpUrl, *, model_cls: Type[BaseReferrableModel]) Any
Convert url to key
- Parameters:
url – The url to convert. The structure is assumed to follow the URL structure of
model_cls
.model_cls – The model class performing the conversion
- Returns:
The key parsed from
url
- Raises:
hrefs.ReferrableModelError – if the model is incorrectly configured
Exception – validation errors when converting
url
are passed as is
- hrefs.model.resolve_hrefs(href_resolver: HrefResolver)
Context manager that sets the active hyperlink resolver
Makes
href_resolver
responsible for converting between keys and URLs for subclasses ofBaseReferrableModel
. Any conversion must happen inside the context.from hrefs.model import BaseReferrableModel, HrefResolver, resolve_hrefs class Book(BaseReferrableModel): id: int class MyHrefResolver(HrefResolver): ... with resolve_hrefs(MyHrefResolver(...)) as href_resolver: # uses ``href_resolver`` to convert between keys and URLs pydantic.parse_obj_as(Href[Book], "http://example.com/books/1") pydantic.parse_obj_as(Href[Book], 1) # raises error pydantic.parse_obj_as(Href[Book], "http://example.com/books/1") pydantic.parse_obj_as(Href[Book], 1)
This function is intended for web integration developers. The integrations provide more user friendly ways to expose the resolution functionality, for example hrefs.starlette.HrefMiddleware for Starlette/FastAPI integration.
- Parameters:
href_resolver – The hyperlink resolver to activate
Exceptions
- exception hrefs.ReferrableModelError
An exception indicating error in a referrable model
This exception is raised whenever the library detects an incorrectly configured or otherwise invalid model. It typically indicates an error in the code and not the input.