Debian Codegraph @

docs/tutorial/5-relationships-and-hyperlinked-apis.md

raw
1 # Tutorial 5: Relationships & Hyperlinked APIs
2
3 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.
4
5 ## Creating an endpoint for the root of our API
6
7 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:
8
9 ```python
10 from rest_framework.decorators import api_view
11 from rest_framework.response import Response
12 from rest_framework.reverse import reverse
13
14
15 @api_view(["GET"])
16 def api_root(request, format=None):
17 return Response(
18 {
19 "users": reverse("user-list", request=request, format=format),
20 "snippets": reverse("snippet-list", request=request, format=format),
21 }
22 )
23 ```
24
25 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`.
26
27 ## Creating an endpoint for the highlighted snippets
28
29 The other obvious thing that's still missing from our pastebin API is the code highlighting endpoints.
30
31 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.
32
33 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.
34
35 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:
36
37 ```python
38 from rest_framework import renderers
39
40
41 class SnippetHighlight(generics.GenericAPIView):
42 queryset = Snippet.objects.all()
43 renderer_classes = [renderers.StaticHTMLRenderer]
44
45 def get(self, request, *args, **kwargs):
46 snippet = self.get_object()
47 return Response(snippet.highlighted)
48 ```
49
50 As usual we need to add the new views that we've created in to our URLconf.
51 We'll add a url pattern for our new API root in `snippets/urls.py`:
52
53 ```python
54 path("", views.api_root),
55 ```
56
57 And then add a url pattern for the snippet highlights:
58
59 ```python
60 path("snippets/<int:pk>/highlight/", views.SnippetHighlight.as_view()),
61 ```
62
63 ## Hyperlinking our API
64
65 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:
66
67 * Using primary keys.
68 * Using hyperlinking between entities.
69 * Using a unique identifying slug field on the related entity.
70 * Using the default string representation of the related entity.
71 * Nesting the related entity inside the parent representation.
72 * Some other custom representation.
73
74 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.
75
76 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`.
77
78 The `HyperlinkedModelSerializer` has the following differences from `ModelSerializer`:
79
80 * It does not include the `id` field by default.
81 * It includes a `url` field, using `HyperlinkedIdentityField`.
82 * Relationships use `HyperlinkedRelatedField`,
83 instead of `PrimaryKeyRelatedField`.
84
85 We can easily re-write our existing serializers to use hyperlinking. In your `snippets/serializers.py` add:
86
87 ```python
88 class SnippetSerializer(serializers.HyperlinkedModelSerializer):
89 owner = serializers.ReadOnlyField(source="owner.username")
90 highlight = serializers.HyperlinkedIdentityField(
91 view_name="snippet-highlight", format="html"
92 )
93
94 class Meta:
95 model = Snippet
96 fields = [
97 "url",
98 "id",
99 "highlight",
100 "owner",
101 "title",
102 "code",
103 "linenos",
104 "language",
105 "style",
106 ]
107
108
109 class UserSerializer(serializers.HyperlinkedModelSerializer):
110 snippets = serializers.HyperlinkedRelatedField(
111 many=True, view_name="snippet-detail", read_only=True
112 )
113
114 class Meta:
115 model = User
116 fields = ["url", "id", "username", "snippets"]
117 ```
118
119 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.
120
121 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.
122
123 !!! note
124 When you are manually instantiating these serializers inside your views (e.g., in `SnippetDetail` or `SnippetList`), you **must** pass `context={'request': request}` so the serializer knows how to build absolute URLs. For example, instead of:
125
126 serializer = SnippetSerializer(snippet)
127
128 You must write:
129
130 serializer = SnippetSerializer(snippet, context={"request": request})
131
132 If your view is a subclass of `GenericAPIView`, you may use the `get_serializer_context()` as a convenience method.
133
134 ## Making sure our URL patterns are named
135
136 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.
137
138 * The root of our API refers to `'user-list'` and `'snippet-list'`.
139 * Our snippet serializer includes a field that refers to `'snippet-highlight'`.
140 * Our user serializer includes a field that refers to `'snippet-detail'`.
141 * 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'`.
142
143 After adding all those names into our URLconf, our final `snippets/urls.py` file should look like this:
144
145 ```python
146 from django.urls import path
147 from rest_framework.urlpatterns import format_suffix_patterns
148 from snippets import views
149
150 # API endpoints
151 urlpatterns = format_suffix_patterns(
152 [
153 path("", views.api_root),
154 path("snippets/", views.SnippetList.as_view(), name="snippet-list"),
155 path(
156 "snippets/<int:pk>/", views.SnippetDetail.as_view(), name="snippet-detail"
157 ),
158 path(
159 "snippets/<int:pk>/highlight/",
160 views.SnippetHighlight.as_view(),
161 name="snippet-highlight",
162 ),
163 path("users/", views.UserList.as_view(), name="user-list"),
164 path("users/<int:pk>/", views.UserDetail.as_view(), name="user-detail"),
165 ]
166 )
167 ```
168
169 ## Adding pagination
170
171 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.
172
173 We can change the default list style to use pagination, by modifying our `tutorial/settings.py` file slightly. Add the following setting:
174
175 ```python
176 REST_FRAMEWORK = {
177 "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
178 "PAGE_SIZE": 10,
179 }
180 ```
181
182 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.
183
184 We could also customize the pagination style if we needed to, but in this case we'll just stick with the default.
185
186 ## Browsing the API
187
188 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.
189
190 You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations.
191
192 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.
193
194 [tut-6]: 6-viewsets-and-routers.md