Reputation: 1276
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)
Upvotes: 1
Views: 1085
Reputation: 47846
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.
Upvotes: 1