In the previous lesson, I talked about the Django REST Framework serialization mechanism and how to use the
@api_view decorator to create a view. In this lesson, I’m going to be drilling down more on views and introducing the DRF ViewSets class. As a quick refresher, here are the DRF components so far. You’ve seen the
The DRF provides decorators to make this a little easier. The heart of it is you have to return a DRF
Response object with your serialized data inside of it for what to respond to with the view. To make your life easier, the DRF also has a concept called ViewSets.
ViewSet is a class that encapsulates the common REST HTTP method calls, things like the gets, the posts, the patches, et cetera. Using a
ViewSet makes it far faster to implement a series of REST calls on a class of objects. Going with the
ViewSet is the concept of a
Router allows you to use a
ViewSet to declare a series of URLs. This means you have far less work to do. You just map the
ViewSet to a
Router, and the DRF takes care of the rest of it for you.
Here’s an example base
ViewSet, taken straight out of the DRF docs. As you can see, it declares six methods on the
.list() maps to the
GET method for listing the objects.
This would be used to do something similar to the people list view that I showed you in the previous lesson.
.create() maps to the
POST, allowing you to create a new object.
.retrieve() maps to the
GET, but for a specific identifier, so to get book number
.update() maps to HTTP
PUT, taking an object as well as some fields, those fields updating the values inside of the object specified.
.partial_update() maps to
PATCH, taking an object as well as a subset of fields, only updating those fields that are given. And
.destroy() maps to the HTTP
DELETE method. Throughout this course, I’m going to continue building on the
Fedora project. For the most part, I’m going to create a new app for each lesson.
I won’t stepwise go through the process of creating each app—I will just quickly summarize it in order to save time. If you need guidance on how to do this, see the previous lesson or dig into one of the other Django courses. To get going for this lesson, I’m going to create another app, this one called
I’m going to have to edit the
settings.py file, adding
artifacts to the
INSTALLED_APPS list. I’m going to have to edit the
Fedora/urls file to add the
artifacts.urls file in the
urlpatterns list. And then for the rest of this lesson, I’m going to show you the contents of
You can code along with me as I go. In order to play with the REST interface, you’re going to need some data, so you can either create an
admin.py file to go with the
models.py or you can use the one supplied in the supplemental materials.
Like before, I need a serializer. Inside of a new file called
serializers.py, I’m creating the
ArtifactSerializer. As in the previous lesson, all I need to do here is identify the model that’s being serialized, which in this case is the
Artifact, and the list of fields that I want serialized. The DRF provides a handy shortcut.
Instead of writing a view, this time I’m going to write a
ViewSet is a view class, and to keep things short and sweet, all you have to do is provide the
Serializer that you want associated with the
ViewSet and the queryset associated with that
Serializer, and the DRF will create everything else for you. So on line 7, by convention, I name it the
ArtifactViewSet. You’ll notice this pattern seems to hold—
ArtifactSerializer goes with our
This inherits from the
ModelViewSet class. On line 8, I specify the
Serializer class, which is the
ArtifactSerializer. And on line 10 and 11, I override the
.get_queryset() method, returning the queryset of what I want. In this case, it’s all of the
Artifact objects. Essentially, I’m accomplishing the same kind of thing that I did with the
people list in the previous lesson. I’m listing off all of the artifacts, but this time, because I’m implementing the
ModelViewSet, not only am I getting the
GET for the listing, I’m also provided with retrieves, deletes, creates, and both kinds of updates.
In a separate window, I’m running the Django development server. Now I’m going to demonstrate hitting those REST URLs with
curl. First off, a simple
GET. I’m hitting
artifacts/ and piping it through
json.tool to get a pretty print.
artifacts/ in that URL is part of the path from my
include(). The second
artifacts/ in that URL is placed there from the registration of the
router. In later lessons, after you’ve registered a bunch of different routers, this listing will be helpful.
Notice it’s just a list in this case—there’s no dictionary to go with it. I can also do a
GET on a specific value from the database by appending the ID of the object to the previous URL. Still a
It hits the URL. It’s a bit of a long command line there, so notice that it’s wrapped around to the second line. And what comes back is JSON of the new item created, the
"Ark of the Covenant", with the
shiny, of course, being
True. This time I didn’t pass it through the pretty printer, so it just gets spit out all in one line.
you’ll notice that the
"Ark of the Covenant" has been added to our list of artifacts. Now let’s do an
.update(). Once again, using the
-X, this time using the HTTP
PUT method, specifying fields for
"Golden Idol" and
"shiny=True", and the full URL of the object that I’m replacing, object
09:58 I get back an error from the server. Notice that this error is similar to how a Django form field works. If you fail to specify a required field in a Django form, Django gives you error information about what field failed. Django REST Framework is doing the same thing here.
And because I failed to provide the
name field, I get back a dictionary with an error that says the
name is required. If I only want to update the single field, instead of using a
PUT, I have to use a
PATCH. A similar concept here, this time using HTTP
PATCH, provide only the
shiny field and same URL.
And this time it worked. I don’t know what Belloq did to that pretty little gold statue to make it no longer shiny, but the database reflects it now. The only HTTP method left is
DELETE so here it goes. Once again capital
-X, this time with
DELETE, specify a URL that has a specific object. In this case, you get nothing back from the server. If I run the listing,
By using a
ViewSet instead of a view, you automatically get the
.delete() methods for your object. In just a couple of lines of code, you fully defined a REST interface for your object.
In addition to the convenience of having the
ViewSet define all of those things, the router means you don’t have to define the mappings for all of those.
.delete() are all created by the router in a single line.
12:14 The DRF saves you an awful lot of work and an awful lot of definition. Everything’s about the shortcuts here. So, that was ViewSets. Next up, I’ll show you the web interface, a great way to debug your REST application.
Become a Member to join the conversation.