4

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)
Ashin Shakya
  • 690
  • 6
  • 9

2 Answers2

3

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.

Insa
  • 1,610
  • 12
  • 17
3

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.

jean
  • 111
  • 2
  • 4
  • This is the better solution, if you don't customize the method! my answer merely explained what went wrong. – Insa Feb 10 '23 at 23:41
  • This is a great solution. The only thing that doesn't quite work is that instead of parameters I passed a serializer. My parameters appear in the docs, but don appear camelized, which I have set up through drf-spectacular. Does any of you have experience with that? – Eddysanoli Mar 22 '23 at 20:13