drf spectacular not showing query params in swagger ui
Asked Answered
S

2

6

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)
Shockey answered 6/9, 2021 at 4:40 Comment(0)
C
7

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.

Corr answered 29/7, 2022 at 13:54 Comment(2)
This is the better solution, if you don't customize the method! my answer merely explained what went wrong.Miley
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?Kew
M
4

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.

Miley answered 1/11, 2021 at 16:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.