Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRF Shows incorrect schema

I have a following viewset:

class MyViewSet:
    @action(detail=False)
    def statuses(self, *args, **kwargs):
        serializer = self.get_serializer(MyModel.Statuses, many=True)
        return Response(serializer.data)

And serializer for it:

class LabelValueSerializer(serializers.Serializer):
    label = serializers.CharField()
    value = serializers.CharField()

    class Meta:
        fields = ("label", "value")

I get the correct API response:

[
  {
    "label": "New",
    "value": "new"
  },
  {
    "label": "Processing",
    "value": "processing"
  },
  {
    "label": "Finished",
    "value": "finished"
  }
]

But the Swagger API suggest that the model is like this suggesting only 1 object is returned and not the list of them.

Swagger API documentation. Status 200 media type application/json, single object JSON response.

How can I fix this and get the documentation like:

[
  {
    "label": string,
    "value": string
  }
]
like image 516
gonczor Avatar asked Aug 20 '26 22:08

gonczor


1 Answers

If you're using drf-spectacular, you need to extend the schema to indicate this is a many=True endpoint.

class MyViewSet:
    @extend_schema(responses=LabelValueSerializer(many=True))
    @action(detail=False)
    def statuses(self, *args, **kwargs):
        serializer = self.get_serializer(MyModel.Statuses, many=True)
        return Response(serializer.data)

more: https://drf-spectacular.readthedocs.io/en/latest/faq.html#i-m-using-action-detail-false-but-the-response-schema-is-not-a-list

(if not using drf-spectacular your implementation would depend on what package you are using to create your schema)

like image 67
Ashley H. Avatar answered Aug 24 '26 03:08

Ashley H.