drf-yasg How to show sample response with with api?
Asked Answered
S

2

7

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

Schismatic answered 28/9, 2020 at 20:37 Comment(0)
G
18

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

Gaggle answered 29/9, 2020 at 3:56 Comment(11)
So I have to write custom response for every api ? I have 22 apis . so for all of them ?Schismatic
Yes, unless any of them are returning the same response.Gaggle
Sir , Can You tell how I can add post parameter in it as well ? I can't send post parameterSchismatic
This is an "another question", please do ask a new question regarding the new issue. BTW, please do accept and upvote the answer if you found this answer was helpful.Gaggle
Then there must be some configuration issue in your case. This answer will work as-is @FawadGaggle
In my case too, the examples is just loading and not showing anything.Prosthesis
Can you add a minimal-reproducible-example to reproduce the issue? @DivyaKondaGaggle
@ArakkalAbu I posted more details as an answer. the comments seem to have a character limitProsthesis
I expected a new question with a reference link @DivyaKondaGaggle
someone actually answered on git - github.com/axnsan12/drf-yasg/issues/86 seems to be a css issue.Prosthesis
@FawadRana I hope the update might be useful for you!!!Gaggle
C
3

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.

Coenurus answered 21/7, 2022 at 18:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.