Search code examples
django-rest-frameworkdrf-yasg

Add documentation to generics.RetrieveAPIView 'retrieve' method's query param


I have a simple view which takes 'email' as a query param and I would like to have it documented in the OpenAPI autogenerated schema. So far I tried applying method_decorator together with swagger_auto_schema on the API View class definition, but without success:

from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from django.utils.decorators import method_decorator


@method_decorator(name='retrieve', decorator=swagger_auto_schema(manual_parameters=[
    openapi.Parameter('email', openapi.IN_QUERY, description="Email to be checked", type=openapi.TYPE_STRING)]))
class EmailCheckView(generics.RetrieveAPIView):
    serializer_class = EmailCheckSerializer

    def get_queryset(self):
        email = self.request.query_params.get('email', None)
        if not email:
            raise Http404
        return User.objects.filter(email=self.kwargs['email'])

the auto generated models contains only information on the body coming from the serializer. Any ideas what's wrong?

DRF: 3.12.2

drf-yasg: 1.20.0

My swagger schema is added in urls.py with:

from drf_yasg.views import get_schema_view
from drf_yasg import openapi
schema_view = get_schema_view(
   openapi.Info(
      title="My API",
      default_version='v1',
      description="",
   ),
   public=True,
   permission_classes=[permissions.AllowAny],
)

urlpatterns = [
    ...
    path('docs/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    ...
] 

Solution

  • Change

    name='retrieve'
    

    to

    name='get'
    

    @method_decorator(
        name="get", # change is here
        decorator=swagger_auto_schema(
            manual_parameters=[
                openapi.Parameter(
                    "email",
                    openapi.IN_QUERY,
                    description="Email to be checked",
                    type=openapi.TYPE_STRING,
                )
            ]
        ),
    )
    class EmailCheckView(generics.RetrieveAPIView):
        serializer_class = EmailCheckSerializer
    
        def get_queryset(self):
            email = self.request.query_params.get("email", None)
            if not email:
                raise Http404
            return User.objects.filter(email=self.kwargs["email"])

    Note: I am not sure whether the issue belongs to method_decorator(...) or drf-yasg itself