axnsan12 / drf-yasg

Automated generation of real Swagger/OpenAPI 2.0 schemas from Django REST Framework code.
https://drf-yasg.readthedocs.io/en/stable/
Other
3.41k stars 438 forks source link

Correct way to describe query parameters using serializers #677

Closed arlopezg closed 3 years ago

arlopezg commented 3 years ago

Hello,

I've started to document an API with YASG. So far it's worked very well, the only trouble I've had has been using nested serializers, and the doubts stem from:

Example:

# serializers.py
from rest_framework import serializers

class SomeObjectSerializer(serializers.Serializer):    
    id = serializers.IntegerField()
    name = serializers.CharField(required=False, allow_blank=False)

class MultipleIncludesSerializer(serializers.Serializer):
    include = ObjectRequestSerializer(many=True, allow_empty=False)

class MyReportRequestSerializer(serializers.Serializer): 
    # This is the one used in YASG's `query_serializer`
    some_field = MultipleIncludesSerializer()
    another_field = serializers.CharField()
# view.py
from drf_yasg.utils import swagger_auto_schema

from .serializers import MyReportRequestSerializer

class ReportViewSet():
    @swagger_auto_schema(
        operation_id="Example request",
        query_serializer=MyReportRequestSerializer
    )
    def create(self, request):
        (...)

Result If I try to generate my schema, I get the following error:

drf_yasg.errors.SwaggerGenerationError: cannot instantiate nested serializer as Parameter

I get that nested params are not allowed in query_serializer - but what else can I do to describe this request parameters?

dineshtrivedi commented 3 years ago

Did you find how to do this, @arlopezg ?

I am currently having the same issue

arlopezg commented 3 years ago

I ended up using drf-spectacular and it worked out just fine, no dice doing it with YASG. You may want to look into making the move.

dineshtrivedi commented 3 years ago

Awesome, @arlopezg ! Thank you very much, I will check it out

Bubbassauro commented 2 years ago

Just leaving this here in case other people are having trouble with this. I used the query_serializer parameter:

from rest_framework import serializers
from rest_framework import viewsets
from drf_yasg.utils import swagger_auto_schema

class CustomParametersSerializer(serializers.Serializer):
    myparam = serializers.CharField(help_text="My manual querystring parameter")

class MyViewSet(viewsets.ViewSet):
    @swagger_auto_schema(query_serializer= CustomParametersSerializer)
    def my_route(self, request):
        ...