@@ -145,7 +145,7 @@ Deserialization is similar. First we parse a stream into python native datatype
serializer.is_valid()
# True
serializer.object
# <Comment object at 0x10633b2d0>
# <Comment: Comment object>
Notice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer.
Our instance view is an improvement over the previous example. It's slightly more concise, and the code now feels very similar to if we were working with the Forms API.
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.
@api_view(allow=['GET', 'PUT', 'DELETE'])
@api_view(['GET', 'PUT', 'DELETE'])
def comment_instance(request, pk):
"""
Retrieve, update or delete a comment instance.
...
...
@@ -69,7 +74,7 @@ Our instance view is an improvement over the previous example. It's slightly mo
try:
comment = Comment.objects.get(pk=pk)
except Comment.DoesNotExist:
return Response(status=HTTP_404_NOT_FOUND)
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = CommentSerializer(instance=comment)
...
...
@@ -82,19 +87,19 @@ Our instance view is an improvement over the previous example. It's slightly mo
This should all feel very familiar - it looks a lot like working with forms in regular Django views.
This should all feel very familiar - there's not a lot different to working with regular Django views.
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 `yaml` and 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.
## Adding optional format suffixes to our URLs
To take advantage of that, let's add support for format suffixes to our API endpoints, so that we can use URLs that explicitly refer to a given format. That means our API will be able to handle URLs such as [http://example.com/api/items/4.json][1].
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].
Start by adding a `format` keyword argument to both of the views, like so.
...
...
@@ -131,7 +136,7 @@ Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/][3
In [tutorial part 3][4], we'll start using class based views, and see how generic views reduce the amount of code we need to write.