0

I have created a number of API endpoints for accepting POST requests using DjangoRestFramework. For 5/6 of them, I need to have 1 key in the body present providing some data so for each view I have

if (key not in request.data):
  return Response('please provide key', status=400)

How can I remove this duplication across all views?

Umer
  • 21
  • 2
  • 5
  • 1
    use [serializers](https://www.django-rest-framework.org/api-guide/serializers/) – gmc Jun 20 '20 at 18:52

1 Answers1

0

You can write a common function in a different file and import that function in your views.py which will validate for each view whether in request body key is passed or not.

Your common function will look like this common.py

def get_key(request):
    if (key not in request.data):
        return Response('please provide key', status=400)
    return request.data

And your views will look like this. views.py

from .common import get_key

    @api_view(['GET'])
    def userDetail(request,pk):
        key = get_key(request) #calling the function to check for key
        if key:
            users = User.objects.get(id=pk)
            serializer = UserSerializer(users, many=False)
            return Response(serializer.data)

Here I am assuming you are using a function-based view if you are using class-based view approach will be the same.

Hope it helps. Happy learning.

Rahul Kumar
  • 13
  • 1
  • 4