| 1 |
--- |
| 2 |
source: |
| 3 |
- reverse.py |
| 4 |
--- |
| 5 |
|
| 6 |
# Returning URLs |
| 7 |
|
| 8 |
> The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components. |
| 9 |
> |
| 10 |
> — Roy Fielding, [Architectural Styles and the Design of Network-based Software Architectures][cite] |
| 11 |
|
| 12 |
As a rule, it's probably better practice to return absolute URIs from your Web APIs, such as `http://example.com/foobar`, rather than returning relative URIs, such as `/foobar`. |
| 13 |
|
| 14 |
The advantages of doing so are: |
| 15 |
|
| 16 |
* It's more explicit. |
| 17 |
* It leaves less work for your API clients. |
| 18 |
* There's no ambiguity about the meaning of the string when it's found in representations such as JSON that do not have a native URI type. |
| 19 |
* It makes it easy to do things like markup HTML representations with hyperlinks. |
| 20 |
|
| 21 |
REST framework provides two utility functions to make it more simple to return absolute URIs from your Web API. |
| 22 |
|
| 23 |
There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink its output for you, which makes browsing the API much easier. |
| 24 |
|
| 25 |
## reverse |
| 26 |
|
| 27 |
**Signature:** `reverse(viewname, *args, **kwargs)` |
| 28 |
|
| 29 |
Has the same behavior as [`django.urls.reverse`][reverse], except that it returns a fully qualified URL, using the request to determine the host and port. |
| 30 |
|
| 31 |
You should **include the request as a keyword argument** to the function, for example: |
| 32 |
|
| 33 |
from rest_framework.reverse import reverse |
| 34 |
from rest_framework.views import APIView |
| 35 |
from django.utils.timezone import now |
| 36 |
|
| 37 |
class APIRootView(APIView): |
| 38 |
def get(self, request): |
| 39 |
year = now().year |
| 40 |
data = { |
| 41 |
... |
| 42 |
'year-summary-url': reverse('year-summary', args=[year], request=request) |
| 43 |
} |
| 44 |
return Response(data) |
| 45 |
|
| 46 |
## reverse_lazy |
| 47 |
|
| 48 |
**Signature:** `reverse_lazy(viewname, *args, **kwargs)` |
| 49 |
|
| 50 |
Has the same behavior as [`django.urls.reverse_lazy`][reverse-lazy], except that it returns a fully qualified URL, using the request to determine the host and port. |
| 51 |
|
| 52 |
As with the `reverse` function, you should **include the request as a keyword argument** to the function, for example: |
| 53 |
|
| 54 |
api_root = reverse_lazy('api-root', request=request) |
| 55 |
|
| 56 |
[cite]: https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5 |
| 57 |
[reverse]: https://docs.djangoproject.com/en/stable/ref/urlresolvers/#reverse |
| 58 |
[reverse-lazy]: https://docs.djangoproject.com/en/stable/ref/urlresolvers/#reverse-lazy |