Home > Blockchain >  Generate a custom response for an API endpoint in Django Rest Framework using drf-spectacular
Generate a custom response for an API endpoint in Django Rest Framework using drf-spectacular

Time:08-12

I'm trying to generate the documentation for an function based view in DRF using the drf-spectacular library. The response that I'm trying to generate should look like this: enter image description here

As you can see "data" is a list.

I tried to do the following:

class DocumentSerializer(serializers.Serializer):
    date = serializers.IntegerField(default=123)
    total_documents = serializers.IntegerField(default=1890)

@extend_schema(
    parameters=[
        OpenApiParameter(name='authorization', description='Authorization token', required=True, type=str, location=OpenApiParameter.HEADER),
    ],
    description='Info about the endpoint',
    responses={
        200: inline_serializer(
                name='Successfull response',
                fields={
                    "result_code": serializers.IntegerField(default=200),
                    "result_description": serializers.CharField(default="Transaccion Exitosa"),
                    "data": DocumentSerializer(),
                }
            ),                         
    },
)
@api_view(["GET"])
def my_endpoint_function(request):
    pass

As you can see "data" should be a list of DocumentSerializer, but I don't know how to achieve that. The result I'm obtaining with the code above is the following: enter image description here

Because I don't know how to make that data has a list of DocumentSerializer. It will be great if you can help me, I've searching in the documentation but at this point I'm stuck.

CodePudding user response:

I'm not 100% sure, but adding many=True should definitely generate a list.

"data": DocumentSerializer(many=True)
  • Related