涛哥使用环境为thinkphp5.0.10,来开发app后端接口
一、RESTFUL API HTTP状态码
200 请求成功
201 创建成功
202 更新成功
400 无效请求
401 地址不存在
403 禁止访问
404 请求资源不存在
500 内部错误
二、API数据结构格式
status 业务状态码(业务状态码自行约定)
message 提示信息
data 数据层
三、ThinkPHP5 restful api使用方法
通过Route.php资源路由类完成restful
1 2 3 4 5 |
Route::resource('user','api/user'); //涛哥实际项目中使用https://www.phpnote.cc use think\Route; Route::domain('api','api'); Route::resource(':ver/user', ':ver.user'); |
四、ThinkPHP5通用API接口数据输出
1 2 3 4 5 6 7 8 9 |
function show($status, $message, $data=[], $httpCode=200) { $data = [ 'status' => $status, 'message' => $message, 'data' => $data ]; return json($data,$httpCode); } |
五、不可预知的内部异常api数据输出解决方案
http状态码和业务码异常处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php namespace app\common\exception; use think\Exception; class ApiException extends Exception{ public $message = ''; public $httpCode = 500; public $code = 0; public function __construct($message = "", $httpCode = 0, $code = 0) { $this->message = $message; $this->httpCode = $httpCode; $this->code = $code; } } |
异常
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php namespace app\common\exception; use think\exception\Handle; class ApiHandleException extends Handle{ /** * http状态码 * @var int */ public $httpCode = 500; public function render(\Exception $e) { if(config('app_debug') == true){ return parent::render($e); } if($e instanceof ApiException){ $this->httpCode = $e->httpCode; } return show(0, $e->getMessage(),[],$this->httpCode); } } |
更多待涛哥总结
转载请注明:PHP笔记 » ThinkPHP接口开发restful api使用总结