drf-yasg是Django RestFramework的一个扩展, 可以根据路由生成OpenApi接口, 不过用起来和在Java平台和.NetCore有很多不一样的, 有些自定义的地方也比较麻烦, 不过看看文档也还好, 可以解决.

本文记录几个在实际开发中遇到的, 虽然是细节, 但是优化好细节可以给对接的同事带来很大的方便~

顺带一提, Python写后台真的太快了, 一上午出几十个接口你能信?

设置请求参数和接口说明

实现代码

@swagger_auto_schema(request_body=openapi.Schema(
    type=openapi.TYPE_OBJECT,
    required=['phone'],
    properties={'phone': openapi.Schema(type=openapi.TYPE_STRING)}
), operation_summary='更新手机号码')
@action(detail=True, methods=['PUT'], permission_classes=[permissions.IsAuthenticated])
def phone(self, request, pk=None):
    """更新手机号码"""
    if request.method == 'POST':
        phone_num = request.data.get('phone')
        profile_obj: UserProfile = get_object_or_404(UserProfile.objects.all(),
                                                     user=request.user)
        profile_obj.phone = phone_num
        profile_obj.save()
        return Response({'detail': '更新手机号成功'})

效果

参考资料

给每个分组加上说明

drf-yasg默认是不支持这个功能的, 这是我在翻Stack Overflow时找到的解决方案, 算是有点曲线救国吧...

默认状态是这样的

代码

class CustomOpenAPISchemaGenerator(OpenAPISchemaGenerator):
    """重写 OpenAPISchemaGenerator 实现每个tag的说明文本"""

    def get_schema(self, request=None, public=False):
        swagger = super().get_schema(request, public)

        swagger.tags = [
            {
                "name": "core",
                "description": "核心功能",
            },
            {
                'name': 'external_units',
                'description': '外部单位'
            },
            {
                'name': 'field_investigation',
                'description': '现场勘查'
            },
            {
                'name': 'require',
                'description': '需求'
            },
            {
                'name': 'require_delivered',
                'description': '需求分配'
            },
            {
                'name': 'scheme_appraisal',
                'description': '方案评审'
            }
        ]

        return swagger

修改完的效果

参考资料