Abhinav verma
Abhinav verma

Reputation: 11

Django Rest Framework - Efficient API Design

In any rest API,

  1. Data comes in request body
  2. We perform some Logic on data and perform some queries

3.finally API responds serialized data.

My question is :- Where to put data processing Logic? And what is the efficient way of designing any REST API?

Upvotes: 0

Views: 415

Answers (1)

Reactoo
Reactoo

Reputation: 1032

Logic on data is mainly put on the views. You can use any views, be it functional, generic API views, and viewsets. There are three types of views in DRF.

You should be comfortable in using one of them, however should understand all of them. Go through this link. https://micropyramid.com/blog/generic-functional-based-and-class-based-views-in-django-rest-framework/

I personally find comfort in using CBV (Class-Based Views). It is in the views where most of the SQL joins take place too.

For eg:

class GetReviewAPIView(ListAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = ReviewSerializer

    def get_queryset(self):
        user = self.request.user
        return Review.objects.filter(user=user)

The above is a good example of CBV where the API call gets all the reviews of a particular user only. There is a SQL join happening between the User table and Review table.

Also, you can write the logic in the serializer class as well instead of view. This is done mainly when you have to write the logic for each serializer field differently and set characteristics for each field. I can give you an example for this as well if you want.

Upvotes: 1

Related Questions