Build a REST API in 30 minutes with Django REST Framework
By: Bennett Garner
Tags: Python, Web Development, Software Development, Coding, Django

3. Set up Django REST Framework

Okay, time to start thinking about our heroes API. We need to serialize the data from our database via endpoints.

To do that, we’ll need Django REST Framework, so let’s get that installed.

$ pip install djangorestframework

Now, tell Django that we installed the REST Framework in mysite/settings.py:

INSTALLED_APPS = [

# All your installed apps stay the same

...

'rest_framework',

]

That’s it!

4. Serialize the Hero model

Now we’re starting to get into some new waters. We need to tell REST Framework about our Hero model and how it should serialize the data.

Remember, serialization is the process of converting a Model to JSON . Using a serializer, we can specify what fields should be present in the JSON representation of the model.

The serializer will turn our heroes into a JSON representation so the API user can parse them, even if they’re not using Python. In turn, when a user POSTs JSON data to our API, the serializer will convert that JSON to a Hero model for us to save or validate.

To do so, let’s create a new file — myapi/serializers.py

In this file, we need to:

Import the Hero model Import the REST Framework serializer Create a new class that links the Hero with its serializer

Here’s how:

# serializers.py from rest_framework import serializers



from .models import Hero



class HeroSerializer(serializers.HyperlinkedModelSerializer):

class Meta:

model = Hero

fields = ('name', 'alias')

5. Display the data

Now, all that’s left to do is wire up the URLs and views to display the data!

5.1 Views

Let’s start with the view. We need to render the different heroes in JSON format.

To do so, we need to:

Query the database for all heroes Pass that database queryset into the serializer we just created, so that it gets converted into JSON and rendered

In myapi/views.py:

# views.py from rest_framework import viewsets



from .serializers import HeroSerializer

from .models import Hero





class HeroViewSet(viewsets.ModelViewSet):

queryset = Hero.objects.all().order_by('name')

serializer_class = HeroSerializer

ModelViewSet is a special view that Django Rest Framework provides. It will handle GET and POST for Heroes without us having to do any more work.

5.2 Site URLs

Okay, awesome. We’re soooooo close. The last step is to point a URL at the viewset we just created.

In Django, URLs get resolved at the project level first. So there’s a file in mysite/ directory called urls.py .

Head over there. You’ll see the URL for the admin site is already in there. Now, we just need to add a URL for our API. For now, let’s just put our API at the index:

# mysite/urls.py from django.contrib import admin

from django.urls import path, include



urlpatterns = [

path('admin/', admin.site.urls),

path('', include('myapi.urls')),

]

5.3 API URLs

If you’re paying attention and not just blindly copy-pasting, you’ll notice that we included 'myapi.urls' . That’s a path to a file we haven’t edited yet. And that’s where Django is going to look next for instructions on how to route this URL.

So, let’s go there next — myapi/urls.py:

# myapi/urls.py from django.urls import include, path

from rest_framework import routers

from . import views



router = routers.DefaultRouter()

router.register(r'heroes', views.HeroViewSet)



# Wire up our API using automatic URL routing.

# Additionally, we include login URLs for the browsable API.

urlpatterns = [

path('', include(router.urls)),

path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))

]

Notice we added something called router that we imported from rest_framework .

The REST Framework router will make sure our requests end up at the right resource dynamically. If we add or delete items from the database, the URLs will update to match. Cool right?

A router works with a viewset (see views.py above) to dynamically route requests. In order for a router to work, it needs to point to a viewset, and in most cases, if you have a viewset you’ll want a router to go with it.

So far, we’ve only added one model+serializer+viewset to the router — Heroes. But we can add more in the future repeating the same process above for different models! (Maybe create a Villains API next?)

Of course, if you only want to use standard DRF Views instead of viewsets, then urls.py will look a little different. You don’t need a router to use simple views, and you can just add them with:

path('path/to/my/view/', MySimpleView.as_view())

Test it out!

Start up the Django server again:

$ python manage.py runserver

Now go to localhost:8000