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, safe=False)
return HttpResponse('查询所有')
def find(request):
if request.GET.get('data') == 'find':
response = {'code': '200', 'msg': "查询成功"}
response = json.dumps(response)
return JsonResponse(response, safe=False)
return HttpResponse('查询单个')
def insert(request):
if request.method == 'POST':
response = {'code': '200', 'msg': "添加成功"}
return JsonResponse(response, safe=False)
return HttpResponse('新增一个')
def delete(request):
if request.method == 'POST':
response = {'code': '200', 'msg': "删除成功"}
return JsonResponse(response, safe=False)
return HttpResponse('删除一个')
def change(request):
if request.method == 'POST':
response = {'code': '200', 'msg': "修改成功"}
return JsonResponse(response, safe=False)
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, safe=False)
# 新增
def post(self,request):
response = {'code': '200', 'msg': "添加成功"}
return JsonResponse(response, safe=False)
class task_detail(View):
# 根据id获取
def get(self, request, u_id):
response = {'code': '200', 'msg': "获取成功"}
return JsonResponse(response, safe=False)
# 根据id删除
def delete(self, request, u_id):
response = {'code': '200', 'msg': "删除成功"}
return JsonResponse(response, safe=False)
# 根据id修改
def put(self, request, u_id):
response = {'code': '200', 'msg': "修改成功"}
return JsonResponse(response, safe=False)