南昌做网站kaiu,工业产品设计与创客实践赛题库,手机主页,甘肃省建设工程安全质量监督管理局网站官网Restful API接口规范(以Django为例)
Restful API的接口架构风格中制定了一些规范#xff0c;极大的简化了前后端对接的时间#xff0c;以及增加了开发效率
安全性保证–使用https路径中带 api标识路径中带版本号数据即资源#xff0c;通常使用名词操作请求方式决定操作资源…Restful API接口规范(以Django为例)
Restful API的接口架构风格中制定了一些规范极大的简化了前后端对接的时间以及增加了开发效率
安全性保证–使用https路径中带 api标识路径中带版本号数据即资源通常使用名词操作请求方式决定操作资源的方式 get 获取数据post 增加数据put 修改数据delete 删除数据 响应状态码 http响应状态码1 2 3 4 5自己定制的状态码 响应中带提示 msg 请求地址中带查询参数–》只针对于查询所有响应中带链接地址操作符合如下规范 查所有 数组 列表查单条 对象新增 返回新增的对象删除空文档修改返回修改后的对象
Restful API与传统设计的区别
在之前的url设计中我们通常会这么写 http://localhost:8000/get查询用户 http://localhost:8000/add新增用户 http://localhost:8000/update更新用户 http://localhost:8000/detele删除用户 即所有交互全部在后端执行request请求的方法全部为get或post方法 因此需要在后端进行各种校验和if判断非常繁琐 根据Restful API接口规范修改 http://localhost:8000/api/查询用户 request请求方法GET http://localhost:8000/api/新增用户 request请求方法POST http://localhost:8000/api/id/更新用户 request请求方法PUT http://localhost:8000/api/id/删除用户 request请求方法DELETE 根据请求方式在后端执行不同的代码块后端无需再对数据类型再次校验 示例
以Django框架为示例
根据不同路由执行方法
# urls.py
urlpatterns [path(admin/, admin.site.urls),path(find_all/, app.views.find_all),path(find/, app.views.find),path(insert/, app.views.insert),path(delete/, app.views.delete),path(change/, app.views.change),
]# views.py
def find_all(request):if request.GET.get(data) find_all:response {code: 200, msg: 查询成功, results: results}response json.dumps(response)return JsonResponse(response, safeFalse)return HttpResponse(查询所有)def find(request):if request.GET.get(data) find:response {code: 200, msg: 查询成功}response json.dumps(response)return JsonResponse(response, safeFalse)return HttpResponse(查询单个)def insert(request):if request.method POST:response {code: 200, msg: 添加成功}return JsonResponse(response, safeFalse)return HttpResponse(新增一个)def delete(request):if request.method POST:response {code: 200, msg: 删除成功}return JsonResponse(response, safeFalse)return HttpResponse(删除一个)def change(request):if request.method POST:response {code: 200, msg: 修改成功}return JsonResponse(response, safeFalse)return HttpResponse(修改一个)根据Restful API规范修改后的示例
# urls.py
urlpatterns [path(admin/, admin.site.urls),path(app/, app.views.task.as_view()),path(app/str:u_id/, app.views.task_detail.as_view()),
]# views.py
class task(View):# 获取所有def get(self, request):response {code: 200, msg: 查询成功}return JsonResponse(response, safeFalse)# 新增def post(self,request):response {code: 200, msg: 添加成功}return JsonResponse(response, safeFalse)class task_detail(View):# 根据id获取def get(self, request, u_id):response {code: 200, msg: 获取成功}return JsonResponse(response, safeFalse)# 根据id删除def delete(self, request, u_id):response {code: 200, msg: 删除成功}return JsonResponse(response, safeFalse)# 根据id修改def put(self, request, u_id):response {code: 200, msg: 修改成功}return JsonResponse(response, safeFalse)