django-rest-framework/docs/tutorial/5-relationships-and-hyperlinked-apis.md

157 lines
7.8 KiB
Markdown
Raw Normal View History

# Tutorial 5: Relationships & Hyperlinked APIs
2012-09-19 16:02:10 +04:00
2014-08-16 06:45:28 +04:00
At the moment relationships within our API are represented by using primary keys. In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships.
2012-08-29 23:57:37 +04:00
2012-10-28 23:25:51 +04:00
## Creating an endpoint for the root of our API
2012-08-29 23:57:37 +04:00
Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the `@api_view` decorator we introduced earlier. In your `snippets/views.py` add:
2012-08-29 23:57:37 +04:00
2012-10-28 23:25:51 +04:00
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
2016-03-01 10:46:20 +03:00
@api_view(['GET'])
2012-10-28 23:25:51 +04:00
def api_root(request, format=None):
return Response({
'users': reverse('user-list', request=request, format=format),
'snippets': reverse('snippet-list', request=request, format=format)
2012-10-28 23:25:51 +04:00
})
2016-07-14 14:44:13 +03:00
Two things should be noticed here. First, we're using REST framework's `reverse` function in order to return fully-qualified URLs; second, URL patterns are identified by convenience names that we will declare later on in our `snippets/urls.py`.
2012-10-28 23:25:51 +04:00
## Creating an endpoint for the highlighted snippets
The other obvious thing that's still missing from our pastebin API is the code highlighting endpoints.
Unlike all our other API endpoints, we don't want to use JSON, but instead just present an HTML representation. There are two styles of HTML renderer provided by REST framework, one for dealing with HTML rendered using templates, the other for dealing with pre-rendered HTML. The second renderer is the one we'd like to use for this endpoint.
2012-10-28 23:25:51 +04:00
2012-10-31 14:12:09 +04:00
The other thing we need to consider when creating the code highlight view is that there's no existing concrete generic view that we can use. We're not returning an object instance, but instead a property of an object instance.
2012-10-28 23:25:51 +04:00
Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. In your `snippets/views.py` add:
from rest_framework import renderers
from rest_framework.response import Response
2012-10-28 23:25:51 +04:00
2013-04-25 01:40:24 +04:00
class SnippetHighlight(generics.GenericAPIView):
queryset = Snippet.objects.all()
renderer_classes = [renderers.StaticHTMLRenderer]
2014-08-16 06:45:28 +04:00
2012-10-28 23:25:51 +04:00
def get(self, request, *args, **kwargs):
snippet = self.get_object()
return Response(snippet.highlighted)
As usual we need to add the new views that we've created in to our URLconf.
We'll add a url pattern for our new API root in `snippets/urls.py`:
2012-10-28 23:25:51 +04:00
path('', views.api_root),
2012-10-28 23:25:51 +04:00
And then add a url pattern for the snippet highlights:
path('snippets/<int:pk>/highlight/', views.SnippetHighlight.as_view()),
2012-10-28 23:25:51 +04:00
## Hyperlinking our API
Dealing with relationships between entities is one of the more challenging aspects of Web API design. There are a number of different ways that we might choose to represent a relationship:
* Using primary keys.
* Using hyperlinking between entities.
* Using a unique identifying slug field on the related entity.
* Using the default string representation of the related entity.
* Nesting the related entity inside the parent representation.
* Some other custom representation.
REST framework supports all of these styles, and can apply them across forward or reverse relationships, or apply them across custom managers such as generic foreign keys.
In this case we'd like to use a hyperlinked style between entities. In order to do so, we'll modify our serializers to extend `HyperlinkedModelSerializer` instead of the existing `ModelSerializer`.
The `HyperlinkedModelSerializer` has the following differences from `ModelSerializer`:
Version 3.5 (#4525) * Start test case * Added 'requests' test client * Address typos * Graceful fallback if requests is not installed. * Add cookie support * Tests for auth and CSRF * Py3 compat * py3 compat * py3 compat * Add get_requests_client * Added SchemaGenerator.should_include_link * add settings for html cutoff on related fields * Router doesn't work if prefix is blank, though project urls.py handles prefix * Fix Django 1.10 to-many deprecation * Add django.core.urlresolvers compatibility * Update django-filter & django-guardian * Check for empty router prefix; adjust URL accordingly It's easiest to fix this issue after we have made the regex. To try to fix it before would require doing something different for List vs Detail, which means we'd have to know which type of url we're constructing before acting accordingly. * Fix misc django deprecations * Use TOC extension instead of header * Fix deprecations for py3k * Add py3k compatibility to is_simple_callable * Add is_simple_callable tests * Drop python 3.2 support (EOL, Dropped by Django) * schema_renderers= should *set* the renderers, not append to them. * API client (#4424) * Fix release notes * Add note about 'User account is disabled.' vs 'Unable to log in' * Clean up schema generation (#4527) * Handle multiple methods on custom action (#4529) * RequestsClient, CoreAPIClient * exclude_from_schema * Added 'get_schema_view()' shortcut * Added schema descriptions * Better descriptions for schemas * Add type annotation to schema generation * Coerce schema 'pk' in path to actual field name * Deprecations move into assertion errors * Use get_schema_view in tests * Updte CoreJSON media type * Handle schema structure correctly when path prefixs exist. Closes #4401 * Add PendingDeprecation to Router schema generation. * Added SCHEMA_COERCE_PATH_PK and SCHEMA_COERCE_METHOD_NAMES * Renamed and documented 'get_schema_fields' interface.
2016-10-10 15:03:46 +03:00
* It does not include the `id` field by default.
2012-10-28 23:25:51 +04:00
* It includes a `url` field, using `HyperlinkedIdentityField`.
2013-02-12 12:57:23 +04:00
* Relationships use `HyperlinkedRelatedField`,
instead of `PrimaryKeyRelatedField`.
2012-10-28 23:25:51 +04:00
We can easily re-write our existing serializers to use hyperlinking. In your `snippets/serializers.py` add:
2012-10-28 23:25:51 +04:00
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
2014-12-11 12:54:55 +03:00
owner = serializers.ReadOnlyField(source='owner.username')
2012-10-30 15:55:02 +04:00
highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')
2014-08-16 06:45:28 +04:00
2012-10-28 23:25:51 +04:00
class Meta:
model = Snippet
fields = ['url', 'id', 'highlight', 'owner',
'title', 'code', 'linenos', 'language', 'style']
2014-08-16 06:45:28 +04:00
2012-10-28 23:25:51 +04:00
class UserSerializer(serializers.HyperlinkedModelSerializer):
snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True)
2014-08-16 06:45:28 +04:00
2012-10-28 23:25:51 +04:00
class Meta:
model = User
fields = ['url', 'id', 'username', 'snippets']
2012-10-28 23:25:51 +04:00
Notice that we've also added a new `'highlight'` field. This field is of the same type as the `url` field, except that it points to the `'snippet-highlight'` url pattern, instead of the `'snippet-detail'` url pattern.
2012-10-30 15:55:02 +04:00
Because we've included format suffixed URLs such as `'.json'`, we also need to indicate on the `highlight` field that any format suffixed hyperlinks it returns should use the `'.html'` suffix.
2012-10-28 23:25:51 +04:00
## Making sure our URL patterns are named
If we're going to have a hyperlinked API, we need to make sure we name our URL patterns. Let's take a look at which URL patterns we need to name.
* The root of our API refers to `'user-list'` and `'snippet-list'`.
* Our snippet serializer includes a field that refers to `'snippet-highlight'`.
* Our user serializer includes a field that refers to `'snippet-detail'`.
* Our snippet and user serializers include `'url'` fields that by default will refer to `'{model_name}-detail'`, which in this case will be `'snippet-detail'` and `'user-detail'`.
After adding all those names into our URLconf, our final `snippets/urls.py` file should look like this:
2012-10-28 23:25:51 +04:00
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
2012-10-28 23:25:51 +04:00
# API endpoints
urlpatterns = format_suffix_patterns([
path('', views.api_root),
path('snippets/',
2012-10-28 23:25:51 +04:00
views.SnippetList.as_view(),
name='snippet-list'),
path('snippets/<int:pk>/',
views.SnippetDetail.as_view(),
2012-10-28 23:25:51 +04:00
name='snippet-detail'),
path('snippets/<int:pk>/highlight/',
2012-10-28 23:25:51 +04:00
views.SnippetHighlight.as_view(),
name='snippet-highlight'),
path('users/',
2012-10-28 23:25:51 +04:00
views.UserList.as_view(),
name='user-list'),
path('users/<int:pk>/',
views.UserDetail.as_view(),
2012-10-28 23:25:51 +04:00
name='user-detail')
])
2014-08-16 06:45:28 +04:00
2012-10-30 15:55:02 +04:00
## Adding pagination
The list views for users and code snippets could end up returning quite a lot of instances, so really we'd like to make sure we paginate the results, and allow the API client to step through each of the individual pages.
We can change the default list style to use pagination, by modifying our `tutorial/settings.py` file slightly. Add the following setting:
2012-10-30 15:55:02 +04:00
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
2015-03-04 18:51:00 +03:00
'PAGE_SIZE': 10
2012-10-30 15:55:02 +04:00
}
Note that settings in REST framework are all namespaced into a single dictionary setting, named `REST_FRAMEWORK`, which helps keep them well separated from your other project settings.
2012-10-30 15:55:02 +04:00
2021-03-16 15:57:04 +03:00
We could also customize the pagination style if we needed to, but in this case we'll just stick with the default.
2012-10-30 15:55:02 +04:00
2013-04-25 01:40:24 +04:00
## Browsing the API
2012-10-28 23:25:51 +04:00
If we open a browser and navigate to the browsable API, you'll find that you can now work your way around the API simply by following links.
2012-10-28 23:25:51 +04:00
You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations.
2012-10-28 23:25:51 +04:00
2013-04-25 01:40:24 +04:00
In [part 6][tut-6] of the tutorial we'll look at how we can use ViewSets and Routers to reduce the amount of code we need to build our API.
2012-10-28 23:25:51 +04:00
2013-04-25 01:40:24 +04:00
[tut-6]: 6-viewsets-and-routers.md