httpx
httpx copied to clipboard
Document the `Response.links` property
In #211 the Response.links property was added, but so far it's undocumented.
In code, the links function's (correctly) annotated as returning a dict[str | None, dict[str, str]], because going only be the typing information key in line 775 could be None. We know that parse_header_links will always include url in its response dict though, so for the documentation we can safely assume the type of .links to be dict[str, dict[str, str]].
Great thanks for taking a look at this.
I don't recall what Links headers look like, or an example of the return results of the .links property. Perhaps we could also supplement the docstring with an example?
I don't recall what
Linksheaders look like
it's dict[str | None, dict[str, str]], types in current PR is not 100% match.
Hi, I totally forgot about this PR, sorry!
it's
dict[str | None, dict[str, str]], types in current PR is not 100% match.
That's correct, the code defines the type of the links property as dict[str | None, dict[str, str]].
I tried to explain in my initial comment that this could be narrowed down to dict[str, dict[str, str]] though, because the parse_header_links func that is being used to populate the result returns dicts that will always include a "url" key, so the key in line 775 will never be None.
We could reflect this by changing line 775 in httpx/_models.py from
key = link.get("rel") or link.get("url")
to
key = link.get("rel") or link["url"]
I thought it would be nice to have the narrowed down type available in the documentation already, but I also understand if you would rather have the documentation correctly reflect the typing information as it is given in the code.
@tomchristie @trim21 Let me know if or how I should update this PR.
Hello from 2024 :). This is still undocumented, any docs would be better than none, with no docs folks wind up grabbing them from .headers and googling "how to parse link headers".
I think the wording in the PR is good as-is, but maybe if more examples are better it could be modified to include the following details?
* `.links` - **Dict[str, Dict[str, str]]**
* All parsed links from [the `link` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link), mapping each link's `rel` _or_ otherwise `url` to a `dict` of the link's params.
The link params always include its `url`, i.e. `{"url": "https://example.com", ...}`.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link
Link: <https://one.example.com>; rel="preconnect", <https://two.example.com>; rel="preconnect", <https://three.example.com>; rel="preconnect"
To that end, from the MDN docs you can have multiple instances of a rel per request, which probably would cause bad behavior here. I'd not suggest switching to dict[str, list[dict[str, str]]] to manage that, but it's a curious issue.