drf spectacular not showing query params in swagger ui

Viewed 2012

I have generic ListAPIView with following list request function. Here category is a query parameter. I am trying to achieve such that the swagger ui also shows the query parameter in the swagger ui doc. How to achieve this? I have the following code.

@extend_schema(
    parameters=[
        OpenApiParameter(name='category',location=OpenApiParameter.QUERY, description='Category Id', required=False, type=int),
    ],
)
def list(self, request, *args, **kwargs):
    category_id = request.query_params.get('category')
    ....
    return Response(data)
2 Answers

The correct entrypoint for annotations on ApiView (here ListAPIView) is the get method, not the list method.

This is because get is the actual method and list is only wrapped to proxy to the mixin.

class ListAPIView(mixins.ListModelMixin, GenericAPIView):
    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

FAQ entry.

Annotate the get method and call self.list() yourself, and the parameter will show up.

I agree with Insa but you can also decorate your View, to avoid implement/override get method just to decorate it.

@extend_schema_view(
    get=extend_schema(
        parameters=[
            OpenApiParameter(name='category', description='Category Id', type=int),
        ]
    )
)
class YourListView(ListAPIView):
...

I dropped OpenApiParameter location and required arguments as they equal default values.

Related