2

I am doing an api for catching webhooks from a site, the website asks you to activate your webhook within the same url that will use when the webhook is called. I will have a lot of webhooks, therefore i will have a lot of repeated logic for activating the webhooks.

How could this be done using Django Rest Framework's APIView?

class MyWebhookView(APIView):
  def post(self, request):  
    data = request.data
    # repeated logic
    if data.get('type') == constants.WEBHOOK_VERIFY:
      hook = Hook(ID, TOKEN)
      code = hook.validate(data.get('hook_id'), data.get('code'))
      return Response({'code': code})

   # custom logic

1 Answer 1

3

You could just make a generic class with a funciton that contains the verification code like this

class GenericWebhookView(APIView):

  def verify(self, data):  

      if data.get('type') == constants.WEBHOOK_VERIFY:
          hook = Hook(ID, TOKEN)
          code = hook.validate(data.get('hook_id'), data.get('code'))
          return code

      return None

Then when you are creating a new view you can subclass this and use the function like this

class SomeOtherWebhookView(GenericWebhookView):

    def post(self, request):

        code = self.verify(request.data)

        if code:
            return Response({'code': code})

        # custom code

You still do need a few lines of code here, but this way you can change the verify function of every subclassed view at once and of course add any other repeated code to the generic view

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.