java 单机接口限流处理方案
337
2022-08-26
Swagger documentation in Dango
利用rest_framework.views.APIView模块,Django提供了非常有效的RestAPI开发。但是RestAPI文档是一个比较棘手的问题。
怎么制定简洁明了的RestAPI文档去有效的表达endpoint, input and response怎么版本管理文档开发、怎样去保证代码和文档的一致性
drf-swagger提供了很好的解决方案, 通过decorator的形式和RestAPI方法绑定的一起。下面是我的一些理解。
Installation
pip install drf-yasg
django配置可以参照Parameter Request
这个适用GET method
from drf_yasg.utils import swagger_auto_schemafrom rest_framework.decorators import api_view@swagger_auto_schema( operation_description="get latest docker image version", operation_id='get latest docker version', method='get', manual_parameters=[openapi.Parameter( name='repository', in_=openapi.IN_QUERY, required=True, type=openapi.TYPE_STRING, description='repository name' )] tags=['pr'])@api_view(['GET'])def get_latest_docker(request):
manual_parameters: 参照openapi.Parametertype: 参照openapi.TYPE
Body Request
适用于PUT, POST methods
@swagger_auto_schema( operation_description="insert pull request record", operation_id='insert pull request record', request_body=openapi.Schema( type=openapi.TYPE_OBJECT, required=['repository', 'number'], properties={ 'repository': openapi.Schema( type=openapi.TYPE_STRING, description='repository name' ), 'number': openapi.Schema( type=openapi.TYPE_NUMBER, description='pull request number' ) }, ), tags=['pr'])def post(self, request):
request_body:参照openapi.Schemaproperties:同样参照openapi.Schema
如果比较复杂的json data
@swagger_auto_schema(operation_description="insert pull request record", operation_id='insert pull request record', request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'dependency': openapi.Schema( type=openapi.TYPE_ARRAY, items=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'name': openapi.Schema(type=openapi.TYPE_STRING, description='module name'), 'version': openapi.Schema(type=openapi.TYPE_STRING, description='module version') }, description='list of package dependencies' ), description='python package dependencies' }, ), tags=['pr'] )def post(self, request):
如果是array,就用type=openapi.TYPE_OBJECT和items如果是dict, 就用type=openapi.TYPE_OBJECT和properties
代码和文档分离
可以放到不同文件管理
insert_doc = dict(operation_description="insert pull request record", operation_id='insert pull request record', request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'dependency': openapi.Schema( type=openapi.TYPE_ARRAY, items=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'name': openapi.Schema(type=openapi.TYPE_STRING, description='module name'), 'version': openapi.Schema(type=openapi.TYPE_STRING, description='module version') }, description='list of package dependencies' ), description='python package dependencies' }, ), tags=['pr'])@swagger_auto_schema(**insert_doc)def post(self, request):
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~