You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@@ -6,16 +6,16 @@ Let's introduce a couple of essential building blocks.
6
6
## Request objects
7
7
8
8
REST framework introduces a `Request` object that extends the regular `HttpRequest`, and provides more flexible request parsing. The core functionality of the `Request` object is the `request.data` attribute, which is similar to `request.POST`, but more useful for working with Web APIs.
9
-
10
-
request.POST # Only handles form data. Only works for 'POST' method.
11
-
request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.
12
-
9
+
```python
10
+
request.POST# Only handles form data. Only works for 'POST' method.
11
+
request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.
12
+
```
13
13
## Response objects
14
14
15
15
REST framework also introduces a `Response` object, which is a type of `TemplateResponse` that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.
16
-
17
-
return Response(data) # Renders to content type as requested by the client.
18
-
16
+
```python
17
+
return Response(data) # Renders to content type as requested by the client.
18
+
```
19
19
## Status codes
20
20
21
21
Using numeric HTTP status codes in your views doesn't always make for obvious reading, and it's easy to not notice if you get an error code wrong. REST framework provides more explicit identifiers for each status code, such as `HTTP_400_BAD_REQUEST` in the `status` module. It's a good idea to use these throughout rather than using numeric identifiers.
@@ -34,60 +34,60 @@ The wrappers also provide behavior such as returning `405 Method Not Allowed` re
34
34
## Pulling it all together
35
35
36
36
Okay, let's go ahead and start using these new components to refactor our views slightly.
37
-
38
-
from rest_framework import status
39
-
from rest_framework.decorators import api_view
40
-
from rest_framework.response import Response
41
-
from snippets.models import Snippet
42
-
from snippets.serializers import SnippetSerializer
Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious.
63
63
64
64
Here is the view for an individual snippet, in the `views.py` module.
This should all feel very familiar - it is not a lot different from working with regular Django views.
92
92
93
93
Notice that we're no longer explicitly tying our requests or responses to a given content type. `request.data` can handle incoming `json` requests, but it can also handle other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.
@@ -97,25 +97,23 @@ Notice that we're no longer explicitly tying our requests or responses to a give
97
97
To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as [http://example.com/api/items/4.json][json-url].
98
98
99
99
Start by adding a `format` keyword argument to both of the views, like so.
100
-
101
-
def snippet_list(request, format=None):
102
-
100
+
`def snippet_list(request, format=None):`
103
101
and
104
-
105
-
def snippet_detail(request, pk, format=None):
102
+
`def snippet_detail(request, pk, format=None):`
106
103
107
104
Now update the `snippets/urls.py` file slightly, to append a set of `format_suffix_patterns` in addition to the existing URLs.
105
+
```python
106
+
from django.urls import path
107
+
from rest_framework.urlpatterns import format_suffix_patterns
108
+
from snippets import views
108
109
109
-
from django.urls import path
110
-
from rest_framework.urlpatterns import format_suffix_patterns
111
-
from snippets import views
112
-
113
-
urlpatterns = [
114
-
path('snippets/', views.snippet_list),
115
-
path('snippets/<int:pk>/', views.snippet_detail),
116
-
]
110
+
urlpatterns = [
111
+
path("snippets/", views.snippet_list),
112
+
path("snippets/<int:pk>/", views.snippet_detail),
113
+
]
117
114
118
-
urlpatterns = format_suffix_patterns(urlpatterns)
115
+
urlpatterns = format_suffix_patterns(urlpatterns)
116
+
```
119
117
120
118
We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format.
121
119
@@ -124,65 +122,67 @@ We don't necessarily need to add these extra url patterns in, but it gives us a
124
122
Go ahead and test the API from the command line, as we did in [tutorial part 1][tut-1]. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.
125
123
126
124
We can get a list of all of the snippets, as before.
125
+
```bash
126
+
http http://127.0.0.1:8000/snippets/
127
127
128
-
http http://127.0.0.1:8000/snippets/
129
-
130
-
HTTP/1.1 200 OK
131
-
...
132
-
[
133
-
{
134
-
"id": 1,
135
-
"title": "",
136
-
"code": "foo = \"bar\"\n",
137
-
"linenos": false,
138
-
"language": "python",
139
-
"style": "friendly"
140
-
},
141
-
{
142
-
"id": 2,
143
-
"title": "",
144
-
"code": "print(\"hello, world\")\n",
145
-
"linenos": false,
146
-
"language": "python",
147
-
"style": "friendly"
148
-
}
149
-
]
128
+
HTTP/1.1 200 OK
129
+
...
130
+
[
131
+
{
132
+
"id": 1,
133
+
"title": "",
134
+
"code": "foo = \"bar\"\n",
135
+
"linenos": false,
136
+
"language": "python",
137
+
"style": "friendly"
138
+
},
139
+
{
140
+
"id": 2,
141
+
"title": "",
142
+
"code": "print(\"hello, world\")\n",
143
+
"linenos": false,
144
+
"language": "python",
145
+
"style": "friendly"
146
+
}
147
+
]
148
+
```
150
149
151
150
We can control the format of the response that we get back, either by using the `Accept` header:
0 commit comments