Debian Codegraph @

docs/tutorial/2-requests-and-responses.md

raw
1 # Tutorial 2: Requests and Responses
2
3 From this point we're going to really start covering the core of REST framework.
4 Let's introduce a couple of essential building blocks.
5
6 ## Request objects
7
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 ```python
11 request.POST # Only handles form data. Only works for 'POST' method.
12 request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.
13 ```
14
15 ## Response objects
16
17 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.
18
19 ```python
20 return Response(data) # Renders to content type as requested by the client.
21 ```
22
23 ## Status codes
24
25 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.
26
27 ## Wrapping API views
28
29 REST framework provides two wrappers you can use to write API views.
30
31 1. The `@api_view` decorator for working with function based views.
32 2. The `APIView` class for working with class-based views.
33
34 These wrappers provide a few bits of functionality such as making sure you receive `Request` instances in your view, and adding context to `Response` objects so that content negotiation can be performed.
35
36 The wrappers also provide behavior such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exceptions that occur when accessing `request.data` with malformed input.
37
38 ## Pulling it all together
39
40 Okay, let's go ahead and start using these new components to refactor our views slightly.
41
42 ```python
43 from rest_framework import status
44 from rest_framework.decorators import api_view
45 from rest_framework.response import Response
46 from snippets.models import Snippet
47 from snippets.serializers import SnippetSerializer
48
49
50 @api_view(["GET", "POST"])
51 def snippet_list(request):
52 """
53 List all code snippets, or create a new snippet.
54 """
55 if request.method == "GET":
56 snippets = Snippet.objects.all()
57 serializer = SnippetSerializer(snippets, many=True)
58 return Response(serializer.data)
59
60 elif request.method == "POST":
61 serializer = SnippetSerializer(data=request.data)
62 if serializer.is_valid():
63 serializer.save()
64 return Response(serializer.data, status=status.HTTP_201_CREATED)
65 return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
66 ```
67
68 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.
69
70 Here is the view for an individual snippet, in the `views.py` module.
71
72 ```python
73 @api_view(["GET", "PUT", "DELETE"])
74 def snippet_detail(request, pk):
75 """
76 Retrieve, update or delete a code snippet.
77 """
78 try:
79 snippet = Snippet.objects.get(pk=pk)
80 except Snippet.DoesNotExist:
81 return Response(status=status.HTTP_404_NOT_FOUND)
82
83 if request.method == "GET":
84 serializer = SnippetSerializer(snippet)
85 return Response(serializer.data)
86
87 elif request.method == "PUT":
88 serializer = SnippetSerializer(snippet, data=request.data)
89 if serializer.is_valid():
90 serializer.save()
91 return Response(serializer.data)
92 return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
93
94 elif request.method == "DELETE":
95 snippet.delete()
96 return Response(status=status.HTTP_204_NO_CONTENT)
97 ```
98
99 This should all feel very familiar - it is not a lot different from working with regular Django views.
100
101 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.
102
103 ## Adding optional format suffixes to our URLs
104
105 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].
106
107 Start by adding a `format` keyword argument to both of the views, like so.
108 `def snippet_list(request, format=None):`
109 and
110 `def snippet_detail(request, pk, format=None):`
111
112 Now update the `snippets/urls.py` file slightly, to append a set of `format_suffix_patterns` in addition to the existing URLs.
113
114 ```python
115 from django.urls import path
116 from rest_framework.urlpatterns import format_suffix_patterns
117 from snippets import views
118
119 urlpatterns = [
120 path("snippets/", views.snippet_list),
121 path("snippets/<int:pk>/", views.snippet_detail),
122 ]
123
124 urlpatterns = format_suffix_patterns(urlpatterns)
125 ```
126
127 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.
128
129 ## How's it looking?
130
131 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.
132
133 We can get a list of all of the snippets, as before.
134
135 ```bash
136 http http://127.0.0.1:8000/snippets/
137
138 HTTP/1.1 200 OK
139 ...
140 [
141 {
142 "id": 1,
143 "title": "",
144 "code": "foo = \"bar\"\n",
145 "linenos": false,
146 "language": "python",
147 "style": "friendly"
148 },
149 {
150 "id": 2,
151 "title": "",
152 "code": "print(\"hello, world\")\n",
153 "linenos": false,
154 "language": "python",
155 "style": "friendly"
156 }
157 ]
158 ```
159
160 We can control the format of the response that we get back, either by using the `Accept` header:
161
162 ```bash
163 http http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSON
164 http http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML
165 ```
166
167 Or by appending a format suffix:
168
169 ```bash
170 http http://127.0.0.1:8000/snippets.json # JSON suffix
171 http http://127.0.0.1:8000/snippets.api # Browsable API suffix
172 ```
173
174 Similarly, we can control the format of the request that we send, using the `Content-Type` header.
175
176 ```bash
177 # POST using form data
178 http --form POST http://127.0.0.1:8000/snippets/ code="print(123)"
179
180 {
181 "id": 3,
182 "title": "",
183 "code": "print(123)",
184 "linenos": false,
185 "language": "python",
186 "style": "friendly"
187 }
188
189 # POST using JSON
190 http --json POST http://127.0.0.1:8000/snippets/ code="print(456)"
191
192 {
193 "id": 4,
194 "title": "",
195 "code": "print(456)",
196 "linenos": false,
197 "language": "python",
198 "style": "friendly"
199 }
200 ```
201
202 If you add a `--debug` switch to the `http` requests above, you will be able to see the request type in request headers.
203
204 Now go and open the API in a web browser, by visiting [<http://127.0.0.1:8000/snippets/>][devserver].
205
206 ### Browsability
207
208 Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.
209
210 Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.
211
212 See the [browsable api][browsable-api] topic for more information about the browsable API feature and how to customize it.
213
214 ## What's next?
215
216 In [tutorial part 3][tut-3], we'll start using class-based views, and see how generic views reduce the amount of code we need to write.
217
218 [json-url]: http://example.com/api/items/4.json
219 [devserver]: http://127.0.0.1:8000/snippets/
220 [browsable-api]: ../topics/browsable-api.md
221 [tut-1]: 1-serialization.md
222 [tut-3]: 3-class-based-views.md