1

My problem is how to write more strict API using more generic REST API. I have working api in my application but I need to add some more strict services based on generic API and here is a problem because I can't simple override request data because it's immutable. I'm using Django rest framework 3.

Example:

My generic api for animals:

class AnimalService(APIView):
    def get(self, request, *args, **kwargs):
        data = request.data.copy()
        if data.get('type') == 'dog':
            #...do something

Now I need api only for hardcoded dogs:

class DogService(AnimalService):
    def get(self, request, *args, **kwargs):
        #hardcode request.data['type'] = 'dog'
        return super(DogService, self).get(*args, **kwargs)
2
  • A better approach would be to use DRF permission classes and restrict the requests not having type as dog. Commented Sep 11, 2015 at 14:24
  • @RahulGupta yes but I don't need to client send me a type because I can hardcode it in my Dog service. Client don't have to know that I need 'type' in my rest view, so it's impossible to hardcode some arguments? Commented Sep 13, 2015 at 13:02

1 Answer 1

1

Instead of overriding the request object, you can pass the type in kwargs. You can then use these kwargs in AnimalServiceView as these modified kwargs are passed to it.

class DogService(AnimalService):
    def get(self, request, *args, **kwargs):
        kwargs['type'] = 'dog' # set the animal type in kwargs
        return super(DogService, self).get(request, *args, **kwargs)

Then in your AnimalService view, you can do:

class AnimalService(APIView):
    def get(self, request, *args, **kwargs):
        if kwargs.get('type') == 'dog': # check the 'type'
            #...do something

Another way is to write a custom middleware which will set the animal_type attribute on the request depending on the requested resource. Then in your views, you can just check using request.animal_type attribute.

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.