drf-yasg How to show sample response with with api?

11.3k views Asked by At
2

There are 2 answers

11
JPG On BEST ANSWER

Use drf_yasg.openapi.Response--(drf-yasg doc) with the help of @swagger_auto_schema(...)--(drf-yasg doc) decorator as

from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from rest_framework.response import Response
from rest_framework.views import APIView

response_schema_dict = {
    "200": openapi.Response(
        description="custom 200 description",
        examples={
            "application/json": {
                "200_key1": "200_value_1",
                "200_key2": "200_value_2",
            }
        }
    ),
    "205": openapi.Response(
        description="custom 205 description",
        examples={
            "application/json": {
                "205_key1": "205_value_1",
                "205_key2": "205_value_2",
            }
        }
    ),
}


class MyTestAPIView(APIView):

    @swagger_auto_schema(responses=response_schema_dict)
    def post(self, request, *args, **kwargs):
        return Response({"foo": "bar"})

Schema rendered Result

Schema rendered Result

Update

its keep loading and not showing anything

You may need to click on "Example Value" text if you are looking in Swagger doc

loading spinner

0
Farooq On

In response to @JPG's response, there is a quick fix for that. Go to settings and add this.

SWAGGER_SETTINGS = {
    "DEFAULT_MODEL_RENDERING": "example"
}

This will render the example first.