Simple Nested API Using Django Rest Framework

In this article, you will learn how to build a REST API using Django Rest Framework. Prerequisites, Python version 3.6, Django 2.1.4, and Django Rest Framework version 3.6 were used to build the API that contained here. In this case, it’s assumed that all every command will be run in the virtual environment.

Let’s get an anology a popular library approach. Example, your API allows you to post data such as the name of the books and also the authors. Mostly, endpoints for authors will look like this:

books/?author={author_id}

However, we want the query from the endpoint to be logically structured which allows it to be like:

authors/{author_id}/books

How we will implement it? for that, we can use nested relationships on the django rest framework. Nested relationships can be expressed by using serializers as fields. If the field is used to represent a to-many relationship, you should add the many=True flag to the serializer field. By default nested serializers are read only. If you want to support write operations to a nested serializer field, you’ll need to create create() and update() methods in order to explicitly specify how the child relationships should be saved.

Now, let’s take a look to build nested relationships in Django Rest Framework:


First of all, we need some interconnected models to wrap our API around. You can get this by create an application. For this case, i’ll create a new application called shelf, and then add our app to settings.py. After that, create a simple models in shelf like this:

And don’t forget to make migrations and apply them by following command py manage.py makemigrations and py manage.py migrate.

For serializers, we need to create some serializers to handle our data interchange. For Django Rest Framework, uses JSON by default but you can change that to XML or YAML. To make the serializer on this API it wasn’t all that hard, we only need a new class which defines the model we have created before.

For note, you can actually replace the values in the attributes of fields using magic values __all__ but i think listing specific fields is highly recommended, it makes your API much safer.

For viewsets, i’ll write using basic viewsets in views.py. You also can separate that API files by create a new files like api.py , and then remember to update imports in other files accordingly. The final step is to create a basic routing for the API and connect the viewsets and then test the API behavior by using py manage.py runserver , then go to http://127.0.0.1:8000/api/ and create some entries. if your API run wells, it will display a page containing data entries. This API has an API feature in general, we can post a data and then we can also edit the data.


Now it’s time for the main subject of this article, how to make a nested relationship API using Django REST Framework. There are a couple packages that handle nesting logic. Such as DRF Nested Routers and DRF-Extensions. To understand it more deeply, you can check it in the django rest framework documentation. For now, we will use DRF-Extensions as it is the most feature rich package that we can use and also it quite simple. First thing to do, install the drf-extensions using pip install drf-extensions and add a mixin to our viewsets. It will ensure that the url params are correctly handled and the queryset filtered properly.

Also don’t forget to to extend our DefaultRouter . To do this, we will create a new file called routing.py in our main directory, and then we can start nesting our routes. This routes allow us to create subrouters to register nested endpoints. It’s almost as simple as registering normal routers, for exception for this case we only need to add two extra params so that the automation will know how to connect everything together.

After these changes we can get a list of all books by a certain author, and reload the server and go to this http://127.0.0.1:8000/api/authors/1/books/. if your API is successful then the display will be like this:

if you look at the navigation section, there is a new link that you can click on and allow you to see the previous section up to API endpoints. If you go through to Author Instance, you will see who the authors of the book, and you can also delete it. For the Author List, it will show a list of authors.

Important to note, base_name in router eneeds to be unique across your API. It’s the name that will be the root for url names used by reverse() function. Now you should be able to build a nested relationship API using Django REST Framework.