djangodjango-rest-frameworkopenapidrf-yasg

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


How can I add example responses -- (openapi doc) to my swagger doc using drf-yasg package?


Solution

  • 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