I'm using Django REST Framework with django-rest-swagger to create browsable interface for my API. I can specify a request body serializer using YAML docstring, but I haven't found a way to specify a serializer for request query parameters. The view I am using is pretty like:
class ListBans(BaseBanView):
def get(self, request):
"""
List all profile bans
---
response_serializer: backend_serializers.BanSerializer
request_serializer: moderator_serializers.ListBansSerializer
"""
serializer = moderator_serializers.ListBansSerializer(data=request.query_params)
if serializer.is_valid(raise_exception=True):
# query profile bans
data = []
return APIResponse(status=status.HTTP_200_OK, data=data)
class ListBansSerializer(serializers.Serializer):
limit = serializers.IntegerField(default=10, help_text='query limit')
offset = serializers.IntegerField(default=0, help_text='query offset')
what I am trying to achieve is to make django-rest-swagger
create form fields for query parameters from ListBansSerializer
so that I wouldn't have to specify the parameters
section manually in the docstring. Is there a way to do that?
Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
Django's serialization framework provides a mechanism for “translating” Django models into other formats. Usually these other formats will be text-based and used for sending Django data over a wire, but it's possible for a serializer to handle any format (text-based or not).
The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields. The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model.
I've created a simple decorator that automatically appends query parameters to the docstring. The source is available at github. Here's a usage example:
class ListBansSerializer(serializers.Serializer):
limit = serializers.IntegerField(default=10, help_text='query limit')
offset = serializers.IntegerField(default=0, help_text='query offset')
class ListBans(BaseBanView):
@add_query_parameters(ListBansSerializer)
def get(self, request):
"""
List all profile bans
---
response_serializer: backend_serializers.BanSerializer
"""
serializer = moderator_serializers.ListBansSerializer(data=request.query_params)
if serializer.is_valid(raise_exception=True):
# query profile bans
data = []
return APIResponse(status=status.HTTP_200_OK, data=data)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With