restful api 介绍 以ThinkPHP5为例
restful api
- 面向资源
- http动词(get post put delete 等)来描述操作
- api数据格式一般为json
传统api
- 获取用户信息 get /api/user/read
- 更新用户信息 post /api/user/update
- 新增用户信息 post /api/user/add
- 删除用户信息 post /api/user/delete
restful api
- 获取用户信息 get /api/user/1
- 更新用户信息 put /api/user/1
- 新增用户信息 post /api/user
- 删除用户信息 delete /api/user/1
HTTP状态码
- 200 请求成功
- 201 创建成功
- 202 更新成功
- 400 无效请求
- 401 地址不存在
- 403 禁止访问
- 404 请求支援不存在
- 500 内部错误
API数据结构格式
- status 业务状态码
- message 提示信息
- data 数据层
TP5使用方式(调用Route类实现)
- Route::get
- Route::post
- Route::put
- Route::delete
- Route::resource
- 配置 ” default_return_type ” => ” json “
- 编写 route.php
- 使用postMan接口调试工具
TP5通用化API接口数据封装
/* * 通用api接口数据输出 * @param int $status 业务状态码 * @param string $msg 信息提示 * @param Array $data 数据 * @param int $httpCode http状态码 * @return Array */ function show($status,$msg,$data=[],httpCode=200){ $data = [ 'status' =>$status, 'message' => $msg, 'data' => $data ]; return json($data,$httpCode); //json() 是tp5内置函数 }
不可预知的内部异常api数据输出的解决方案
方案一 使用 try { } catch() { }
public function save(){ try{ }catch(\Exception $e){ return show(0,$e->getMessage(),400) } return show(1,'OK',input('post.'),201) }
方案二 覆盖重写 \think\exception\Handle|render 方法
<?php namespace app\common\lib\exception; use think\exception\Handle; class ApiHandleException extends Handle{ pulic function render(\Exception $e){ return show(0 ,$e->getMessage ,[] , 500); // show()是上面定义的api接口数据输出函数 } }
修改配置文件参数
“exception_handle” => ” \app\common\lib\exception\ApiHandleException ”
那么之后当程序运行错误时则返回一个友好的json格式的错误信息如下
[ "sattus":0, "message": "undefind variable: data", "data":[] ]