How can I add example responses -- (openapi doc) to my swagger doc using drf-yasg package?
drf-yasg How to show sample response with with api?
Asked Answered
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
Update
its keep loading and not showing anything
You may need to click on "Example Value" text if you are looking in Swagger doc
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 parameter –
Schismatic
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 @Fawad –
Gaggle
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? @DivyaKonda –
Gaggle
@ArakkalAbu I posted more details as an answer. the comments seem to have a character limit –
Prosthesis
I expected a new question with a reference link @DivyaKonda –
Gaggle
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
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.
© 2022 - 2024 — McMap. All rights reserved.