...

/

Nesting Routes for the Comment Resource

Nesting Routes for the Comment Resource

Implement nested routing for posting and retrieving comments under posts.

Now that the comment serializer is ready, we can proceed to write the viewsets concerning the comment feature. But before that, let’s talk about the endpoint of the resource.

To create, update, or delete comments, we need to add ViewSet. In the comment directory, create a file called viewsets.py. This file will contain the code for the CommentViewSet class. We won’t be writing all the code for this viewset because we need to get some clear ideas on the structure of the endpoint.

So, add the following content for the moment:

Press + to interact
from django.http.response import Http404
from rest_framework.response import Response
from rest_framework import status
from core.abstract.viewsets import AbstractViewSet
from core.comment.models import Comment
from core.comment.serializers import CommentSerializer
from core.auth.permissions import UserPermission
class CommentViewSet(AbstractViewSet):
http_method_names = ('post', 'get', 'put', 'delete')
permission_classes = (UserPermission,)
serializer_class = CommentSerializer
...

Endpoint architecture

Great, now let’s talk about the endpoint architecture. The following table shows the structure of the endpoint concerning the comment. We have the method, the URL of the endpoint, and finally, the result of a call on this endpoint:

Comment endpoint structure

Method

URL

Result

GET

/api/comment/

Lists all the comments related to a post

GET

/api/comment/comment_pk/

Retrieves a specific comment

POST

/api/comment/

Creates a comment

PUT

/api/comment/comment_pk/

Modifies a comment

DELETE

/api/comment/comment_pk/

Deletes a comment

However, for the comment feature, we are working with posts. And it’s definitely a great idea if comments are directly related to posts. Therefore, a great structure for our endpoints would look like this:

Comment endpoint structure—nested

Method

URL

Result

GET

/api/post/post_pk/comment/

Lists all the comments related to a post

GET

/api/post/post_pk/comment/comment_pk/

Retrieves a specific comment

POST

/api/post/post_pk/comment/

Creates a comment

PUT

/api/post/post_pk/comment/comment_pk/

Modifies a comment

DELETE

/api/post/post_pk/comment/comment_pk/

Deletes a comment

In this structure, the endpoint is nested, meaning that comment resources live under post resources.

But how do we achieve this simply?

The Django ecosystem has a library called ...