大摇大摆的rest api构建器
swaggapi的Python项目详细描述
swaggapi
python的包装器。
这个包的目标是让rest api的使用和访问变得更好、更快和更容易。 为此,您需要设置几个模型并“告诉”系统每个模型的结构 你的请求和回应。
这个python库还将自动构建swagger.json文件,稍后可以使用 swagger用户界面。
功能:
- 客户端和服务器rest的使用。
- 动态生成swagger文件。
- 验证输入参数和输出响应。
建立您的模型
型号
首先,每个uri方法(“post”、“get”、“patch”等)都必须有一个表示它的模型。 模型类-
classAbstractAPIModel(object):TITLE=NonePROPERTIES=[]EXAMPLE=None
您的模型应该继承自此对象。 示例:
classGenericModel(AbstractAPIModel):"""This is an empty model."""TITLE="Generic Object"PROPERTIES=[]EXAMPLE={}
classCatModel(AbstractAPIModel):TITLE="Cat"PROPERTIES=[NumberField(name="id"),StringField(name="name"),ArrayField(name="friends_ids",items_type=int)]EXAMPLE={"id":0,"name":"Garfield","friends_ids":[1,3]}
类属性:
- title(str)-模型的名称(如果未设置)-默认情况下采用类名。
- 属性(列表)-表示模型结构的字段的列表。
- 示例(对象)-任何类型的JSON可序列化对象。
- _文档(str)-对象描述。
响应
响应类型也应该像模型那样表示。
classEmptyResponse(AbstractResponse):"""This is an empty response."""PROPERTIES=[]
字段
现在有5种类型的支持字段: 每个字段都具有以下属性:
classField(object):def__init__(self,name,type,description="",required=False,example=None,location="body",deprecated=False)
实例属性:
- name(str)-字段的名称。
- 必需(bool)-如果字段是必需的或不是必需的(默认值:false)。
- type(str)-表示字段类型的字符串。
- 描述(str)-字段的描述。
- 示例(对象)-字段的有效对象的示例。
- 位置(str)-传递字段的位置-可能性-[“body”,“query”,“header”,“path”,“cookie”]。
- 已弃用(bool)-字段是否已弃用。
如果要创建自己的字段类型,可以展开以下方法-
defdefault_example(self):"""Example in case field didn't specify a unique example."""returndefexamples(self,schema_bank,index):"""In case of complex types field - how should the example be generated."""returnExample(value=self.example)defschemas(self,schema_bank,index):"""In case of complex types field - how does the schema should be gennerated."""example_ref=get_schema(self,schema_bank,"examples")example=schema_bank[example_ref.type][example_ref.reference]returnSchema(title=self.name,type=self.type,description=self.description,example=example.value,deprecated=self.deprecated)
准备就绪字段类型:
ArrayField
,StringField
,BoolField
,NumberField
,ModelField
。
建立您的请求
classRequest(object):URI=NoneDEFAULT_MODEL=NoneDEFAULT_RESPONSES={}PARAMS_MODELS={"get":None,"post":None,"delete":None,"put":None,"head":None,"patch":None,"trace":None,}RESPONSES_MODELS={"get":None,"post":None,"delete":None,"put":None,"head":None,"patch":None,"trace":None,}TAGS={"get":[],"post":[],"delete":[],"put":[],"head":[],"patch":[],"trace":[],}
每个请求都应该指定每个方法的模型。 如果请求使用默认模型,则可以使用default类属性以方便使用。 标记-是一种将响应方法组合在一起的方法。
django积分
为此,有一个新定义的类-
classDjangoRequestView(View,Request)classResponse(JsonResponse)classBadRequest(Exception)classServerError(Exception)
- badrequest-将返回httplib.badrequest状态代码,其中插入异常详细信息。
raiseBadRequest({"details":"Invalid Request"})
- response-对于使用指定模型验证参数,应使用response而不是 Django的JsonResponse。
returnResponse({"properties":properties},status=httplib.OK)
- djnagorequestview-您的每个视图都应该继承自这个类。
这个类继承自上面指定的
Request
对象,所以到现在为止一切都是一样的, 如果实现了所需的模型,请确保填充它们。
classGetCats(DjangoRequestView):"""Get all the cats stored in the system that match the needed query."""URI="get_cats"DEFAULT_MODEL=CatsDescriptorModelDEFAULT_RESPONSES={httplib.OK:CatsModel,httplib.BadRequest:NoCatsFoundModel,}TAGS={"post":["Cats"]}# default params are taken because no specific model for this methoddefpost(self,request,*args,**kwargs):...returnResponse({...},httplib.OK)
- 服务器错误-在视图中发生异常时引发。
虚张声势的文件生成
现在,当一切就绪,我们可以生成我们的第一个招摇文件!
django
应用程序的urls.py
文件
fromswagapi.buildimportSwaggerfromswagapi.api.openapi.modelsimportInfo,License,Tagrequests=[GetCats]info=Info(title="Cats OpenAPI",version="0.1.0",description="Cats Swagger for cats management",license=License(name="MIT"))tags=[Tag(name="Cats",description="All requests for managing cats")]# don't forget to configure the mount_url - all the uri until the current fileswagger=Swagger(info,mount_url="api",requests=requests,tags=tags)defswagger_file(request,*args,**kwargs):"""We dynamically generate the swagger file."""swagger.configure_base_url(request)returnJsonResponse(swagger.api.json(),status=httplib.OK)defindex(request,*args,**kwargs):"""Here we use static deploy for Swagger UI."""returnrender(request,"swagger.html")urlpatterns=patterns("",url("^$",index),url("^swagger.json$",swagger_file),*swagger.get_django_urls()# here all requests uris are automatically built.)
客户使用
只需创建一个请求者-
requester=Requester(host=host,port=port,base_url=self.base_uri,# Where the api swagger is mounted.logger=self.logger)# optional
并按您的要求拨打电话-
request_data=CatsDescriptorModel({# request parameters"cats_ids":[1,2]})response=self.requester.request(GetCats,# rememebr the request class namedata=request_data,method="post")# type(response) == CatsModel if success, NoCatsFoundModel if failed!