DRF YASG 定制

DRF YASG Customizing

我正在尝试使用 yasg 自定义我的 api 文档构建。

首先,我想确定我自己的部分的命名,以及该部分中应包含哪些端点。似乎sections的命名是基于第一个不属于最长公共前缀的前缀e.g.:

如果我们有 url api/v1/message 和 api/v1/test,那么这些部分将被命名为 message 和 test。有没有办法让我确定此部分的自定义命名?

另外,每节的介绍都是空的,请问这里要怎么加文字呢?

最后但同样重要的是,Stripe 有这些惊人的部分分隔符,我如何在 drf yasg 中添加它们。

目前,我正在使用 APIView 和@swagger_auto_schema 来定义我的端点的文档。

在下面的代码中,您可以看到如何添加更多信息来定义您的端点。希望对你有帮助

##serializers.py

class CategorySerializer(serializers.ModelSerializer):
    """
    Serializing Categories 
    """
    class Meta:
        model = Category
        fields = [
            'id', 'name', 'slug'
        ]
        read_only_fields = [
           'slug', 
        ]


##views.py

username_param = openapi.Parameter('username', in_=openapi.IN_QUERY, description='Username',
                                type=openapi.TYPE_STRING)
email = openapi.Parameter('email', in_=openapi.IN_QUERY, description='Email',
                                type=openapi.TYPE_STRING)  
category_response = openapi.Response('response description', CategorySerializer)    

class CategoryList(APIView):
    permission_classes = [AllowAny]
          
    @swagger_auto_schema(
        manual_parameters=[username_param, email],
        query_serializer=CategorySerializer,
        responses = {
            '200' : category_response,
            '400': 'Bad Request'
        },        
        security=[],
        operation_id='List of categories',
        operation_description='This endpoint does some magic',
    )
    def get(self, request, format=None):
        """
        GET:
        Return a list of all the existing categories.
        """
        categories = Category.objects.all()
        serializer = CategorySerializer(categories, many=True)
        return Response(serializer.data)


    @swagger_auto_schema(
        request_body=CategorySerializer,
        query_serializer=CategorySerializer,
        responses={
            '200': 'Ok Request',
            '400': "Bad Request"
        },
        security=[],
        operation_id='Create category',
        operation_description='Create of categories',
    )
    def post(self, request, format=None):
        """
        POST:
        Create a new category instance.
        """
        serializer = CategorySerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(created_by=self.request.user)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

最后,如果您想按 link 分组查看您的端点,您可以在 urls.py

中测试评论下面的行
#urlpatterns = format_suffix_patterns(urlpatterns)

下面是您应该如何查看的一些屏幕

您可以在以下内容中找到更多信息link:https://drf-yasg.readthedocs.io/en/stable/custom_spec.html