django-rest-framework/docs/api-guide/reverse.md

50 lines
2.2 KiB
Markdown
Raw Normal View History

2012-09-09 01:06:13 +04:00
<a class="github" href="reverse.py"></a>
2012-09-12 13:12:13 +04:00
# Returning URLs
2012-09-01 23:26:27 +04:00
> The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.
>
> &mdash; Roy Fielding, [Architectural Styles and the Design of Network-based Software Architectures][cite]
2012-09-12 13:12:13 +04:00
As a rule, it's probably better practice to return absolute URIs from you Web APIs, such as `http://example.com/foobar`, rather than returning relative URIs, such as `/foobar`.
2012-09-01 23:26:27 +04:00
The advantages of doing so are:
* It's more explicit.
* It leaves less work for your API clients.
* 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.
2012-09-06 00:14:00 +04:00
* It makes it easy to do things like markup HTML representations with hyperlinks.
2012-09-01 23:26:27 +04:00
REST framework provides two utility functions to make it more simple to return absolute URIs from your Web API.
There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink it's output for you, which makes browsing the API much easier.
2012-10-02 13:40:04 +04:00
## reverse
**Signature:** `reverse(viewname, request, *args, **kwargs)`
2012-09-01 23:26:27 +04:00
Has the same behavior as [`django.core.urlresolvers.reverse`][reverse], except that it returns a fully qualified URL, using the request to determine the host and port.
import datetime
from rest_framework.utils import reverse
from rest_framework.views import APIView
2012-09-01 23:26:27 +04:00
class APIRootView(APIView):
2012-09-01 23:26:27 +04:00
def get(self, request):
year = datetime.datetime.now().year
data = {
2012-09-01 23:26:27 +04:00
...
'year-summary-url': reverse('year-summary', request, args=[year])
2012-09-01 23:26:27 +04:00
}
return Response(data)
2012-09-01 23:26:27 +04:00
2012-10-02 13:40:04 +04:00
## reverse_lazy
**Signature:** `reverse_lazy(viewname, request, *args, **kwargs)`
2012-09-01 23:26:27 +04:00
Has the same behavior as [`django.core.urlresolvers.reverse_lazy`][reverse-lazy], except that it returns a fully qualified URL, using the request to determine the host and port.
[cite]: http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5
[reverse]: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse
[reverse-lazy]: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-lazy