简体   繁体   English

drf-spectacular:添加响应描述

[英]drf-spectacular: add response description

How can I add description to responses in the @extend_schema decorator?如何在 @extend_schema 装饰器中为响应添加描述?

'500':
  content:
    application/json:
      schema:
        $ref: '#/components/schemas/Error'
      description: ''

that specific description location you are referring to is not easily available through the decorators.您所指的特定描述位置不容易通过装饰器获得。 however, there are multiple places a description can be put.但是,可以在多个地方放置描述。

  1. @extend_schema(description='Your description') this will add the description to the view action (operation). @extend_schema(description='Your description')这会将描述添加到视图操作(操作)中。 However, this is targeted to the operation itself and not the 500 Error case.但是,这是针对操作本身的,而不是针对500错误的情况。

  2. adding a docstring to your Error serializer.将文档字符串添加到您的Error序列化程序。 probably what you want to do.可能是你想做的。

this part is still a bit rough as the "Error" feature is still work in progress.这部分仍然有点粗糙,因为“错误”功能仍在进行中。

Insa's answer and comments led me to a working solution using OpenApiResponse (requires drf-spectacular version >=0.15) Insa 的回答和评论使我找到了一个使用OpenApiResponse的工作解决方案(需要 drf-spectacular version >=0.15)

Here's some example code of how I did it:这是我如何做到的一些示例代码:

from drf_spectacular.utils import extend_schema, OpenApiResponse
from rest_framework import generics

class MyResourceList(generics.ListCreateAPIView):

    @extend_schema(
        summary="Create a new resource",
        responses={
            201: OpenApiResponse(response=MyCustomSerializer,
                                 description='Created. New resource in response'),
            400: OpenApiResponse(description='Bad request (something invalid)'),
        },
    )
    def post(self, request, *args, **kwargs):
        """ 
        Some explanation goes here ...
        """
        return super().post(request, *args, **kwargs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM