django-rest-framework/docs/tutorial/2-requests-and-responses.md

210 lines
8.7 KiB
Markdown
Raw Normal View History

2012-09-07 12:37:06 +04:00
# Tutorial 2: Requests and Responses
2012-08-29 23:57:37 +04:00
From this point we're going to really start covering the core of REST framework.
Let's introduce a couple of essential building blocks.
## Request objects
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.
2012-08-29 23:57:37 +04:00
request.POST # Only handles form data. Only works for 'POST' method.
request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.
2012-08-29 23:57:37 +04:00
## Response objects
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.
return Response(data) # Renders to content type as requested by the client.
## Status codes
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.
## Wrapping API views
REST framework provides two wrappers you can use to write API views.
1. The `@api_view` decorator for working with function based views.
2. The `APIView` class for working with class-based views.
2012-08-29 23:57:37 +04:00
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.
2012-08-29 23:57:37 +04:00
The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exception that occurs when accessing `request.data` with malformed input.
2012-08-29 23:57:37 +04:00
## Pulling it all together
2014-08-16 06:45:28 +04:00
Okay, let's go ahead and start using these new components to write a few views.
2012-08-29 23:57:37 +04:00
We don't need our `JSONResponse` class in `views.py` any more, so go ahead and delete that. Once that's done we can start refactoring our views slightly.
2012-09-03 18:57:43 +04:00
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
2012-10-28 23:25:51 +04:00
2012-08-29 23:57:37 +04:00
2012-09-03 18:57:43 +04:00
@api_view(['GET', 'POST'])
2012-10-28 23:25:51 +04:00
def snippet_list(request):
2012-08-29 23:57:37 +04:00
"""
List all code snippets, or create a new snippet.
2012-09-03 18:57:43 +04:00
"""
2012-08-29 23:57:37 +04:00
if request.method == 'GET':
2012-10-28 23:25:51 +04:00
snippets = Snippet.objects.all()
2013-02-12 12:57:23 +04:00
serializer = SnippetSerializer(snippets, many=True)
2012-08-29 23:57:37 +04:00
return Response(serializer.data)
elif request.method == 'POST':
serializer = SnippetSerializer(data=request.data)
2012-08-29 23:57:37 +04:00
if serializer.is_valid():
2012-10-28 23:25:51 +04:00
serializer.save()
2012-09-03 18:57:43 +04:00
return Response(serializer.data, status=status.HTTP_201_CREATED)
2013-12-23 12:06:03 +04:00
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
2012-08-29 23:57:37 +04:00
2012-09-03 18:57:43 +04:00
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.
2012-08-29 23:57:37 +04:00
2013-10-18 12:10:54 +04:00
Here is the view for an individual snippet, in the `views.py` module.
2012-09-03 18:57:43 +04:00
@api_view(['GET', 'PUT', 'DELETE'])
2016-10-20 11:42:40 +03:00
def snippet_detail(request, pk):
2012-08-29 23:57:37 +04:00
"""
Retrieve, update or delete a code snippet.
2014-08-16 06:45:28 +04:00
"""
2012-08-29 23:57:37 +04:00
try:
2016-10-20 11:42:40 +03:00
snippet = Snippet.objects.get(pk=pk)
2012-10-28 23:25:51 +04:00
except Snippet.DoesNotExist:
2012-09-03 18:57:43 +04:00
return Response(status=status.HTTP_404_NOT_FOUND)
2013-02-24 01:29:52 +04:00
2012-08-29 23:57:37 +04:00
if request.method == 'GET':
serializer = SnippetSerializer(snippet)
2012-08-29 23:57:37 +04:00
return Response(serializer.data)
2013-02-24 01:29:52 +04:00
2012-08-29 23:57:37 +04:00
elif request.method == 'PUT':
serializer = SnippetSerializer(snippet, data=request.data)
2012-08-29 23:57:37 +04:00
if serializer.is_valid():
2012-10-28 23:25:51 +04:00
serializer.save()
2012-08-29 23:57:37 +04:00
return Response(serializer.data)
2013-12-23 12:06:03 +04:00
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
2012-08-29 23:57:37 +04:00
elif request.method == 'DELETE':
2012-10-28 23:25:51 +04:00
snippet.delete()
2012-09-03 18:57:43 +04:00
return Response(status=status.HTTP_204_NO_CONTENT)
2012-08-29 23:57:37 +04:00
This should all feel very familiar - it is not a lot different from working with regular Django views.
2012-08-29 23:57:37 +04:00
2014-11-29 21:43:05 +03:00
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.
2012-08-29 23:57:37 +04:00
## Adding optional format suffixes to our URLs
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].
2012-08-29 23:57:37 +04:00
Start by adding a `format` keyword argument to both of the views, like so.
2012-10-28 23:25:51 +04:00
def snippet_list(request, format=None):
2012-08-29 23:57:37 +04:00
and
2016-10-20 11:42:40 +03:00
def snippet_detail(request, pk, format=None):
2012-08-29 23:57:37 +04:00
Now update the `snippets/urls.py` file slightly, to append a set of `format_suffix_patterns` in addition to the existing URLs.
2012-08-29 23:57:37 +04:00
2015-07-01 22:39:05 +03:00
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
2012-08-29 23:57:37 +04:00
urlpatterns = [
url(r'^snippets/$', views.snippet_list),
2016-10-20 11:42:40 +03:00
url(r'^snippets/(?P<pk>[0-9]+)$', views.snippet_detail),
]
2014-08-16 06:45:28 +04:00
2012-08-29 23:57:37 +04:00
urlpatterns = format_suffix_patterns(urlpatterns)
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.
2012-08-29 23:57:37 +04:00
## How's it looking?
2012-09-19 16:02:10 +04:00
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.
2012-08-29 23:57:37 +04:00
2013-02-24 01:29:52 +04:00
We can get a list of all of the snippets, as before.
2014-12-08 18:41:01 +03:00
http http://127.0.0.1:8000/snippets/
2014-12-01 16:39:53 +03:00
2014-12-04 14:20:33 +03:00
HTTP/1.1 200 OK
...
2014-12-01 16:39:53 +03:00
[
{
"id": 1,
"title": "",
"code": "foo = \"bar\"\n",
"linenos": false,
"language": "python",
"style": "friendly"
},
{
"id": 2,
"title": "",
"code": "print \"hello, world\"\n",
"linenos": false,
"language": "python",
"style": "friendly"
}
]
2013-02-24 01:29:52 +04:00
We can control the format of the response that we get back, either by using the `Accept` header:
2014-12-01 16:39:53 +03:00
http http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSON
http http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML
2013-02-24 01:29:52 +04:00
Or by appending a format suffix:
http http://127.0.0.1:8000/snippets.json # JSON suffix
http http://127.0.0.1:8000/snippets.api # Browsable API suffix
2013-02-24 01:29:52 +04:00
Similarly, we can control the format of the request that we send, using the `Content-Type` header.
# POST using form data
2014-12-01 16:39:53 +03:00
http --form POST http://127.0.0.1:8000/snippets/ code="print 123"
2013-02-24 01:29:52 +04:00
2014-12-01 16:39:53 +03:00
{
"id": 3,
"title": "",
"code": "print 123",
"linenos": false,
"language": "python",
"style": "friendly"
}
2014-08-16 06:45:28 +04:00
2013-02-24 01:29:52 +04:00
# POST using JSON
2014-12-01 16:39:53 +03:00
http --json POST http://127.0.0.1:8000/snippets/ code="print 456"
{
"id": 4,
"title": "",
"code": "print 456",
2014-12-15 12:24:12 +03:00
"linenos": false,
2014-12-01 16:39:53 +03:00
"language": "python",
"style": "friendly"
}
2012-08-29 23:57:37 +04:00
If you add a `--debug` switch to the `http` requests above, you will be able to see the request type in request headers.
Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/snippets/][devserver].
2012-09-10 00:46:05 +04:00
### Browsability
2013-05-28 19:13:12 +04:00
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.
2013-02-24 01:29:52 +04:00
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.
2012-09-10 00:46:05 +04:00
See the [browsable api][browsable-api] topic for more information about the browsable API feature and how to customize it.
2012-09-10 00:46:05 +04:00
2012-08-29 23:57:37 +04:00
## What's next?
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.
2012-08-29 23:57:37 +04:00
[json-url]: http://example.com/api/items/4.json
2012-10-28 23:37:27 +04:00
[devserver]: http://127.0.0.1:8000/snippets/
[browsable-api]: ../topics/browsable-api.md
2012-09-19 16:02:10 +04:00
[tut-1]: 1-serialization.md
[tut-3]: 3-class-based-views.md