本文介绍了drf-yasg如何使用api显示示例响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何向我添加

更新

如果您要查看 Swagger 文档,则可能需要点击 示例值" 文本

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

解决方案

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

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

这篇关于drf-yasg如何使用api显示示例响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 00:36