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

44 lines
2.1 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.
## reverse(viewname, request, *args, **kwargs)
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.
from rest_framework.utils import reverse
from rest_framework.views import APIView
2012-09-01 23:26:27 +04:00
class MyView(APIView):
def get(self, request):
content = {
...
'url': reverse('year-summary', request, args=[1945])
}
return Response(content)
## reverse_lazy(viewname, request, *args, **kwargs)
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