Please enable JavaScript.
Coggle requires JavaScript to display documents.
创建laravel的API (2.初步创建API接口 (2.2控制器操作 (2.2.3修改方法 (3.LessonsController初始化实现L…
创建laravel的API
2.初步创建API接口
2.1路由
创建路由群组
2.11 Route::group(['prefix'=>'v1'],function(){
});
创建路由
Route::resource('lessons','LessonsController');
2.2控制器操作
-
-
-
2.2.4创建ApiController
-
2.修改ApiController类
-
-
2.1 设置变量code,和getCode(),setCode()方法
2.4设置responseError()方法
private function responseError($message) {
return $this ->response([
'status' => 'failed',
'code' => $this ->getCode(),
'data' => $message,
]);
}
-
3.修改LessonsController
index()
$lessons = Lesson::all();
return $this ->responseSuccess($this ->lessonTransformer->transformCollection($lessons->toArray()));
show()
$lesson = Lesson::find($id);
if(!$lesson){
return $this->setCode(404) ->responseNotFound();
}
return $this ->responseSuccess($this ->lessonTransformer->transform($lesson));
2.3 post请求=>store()方法
2.重新创建验证机制
Dingo API和JWT
(输入用户名和密码,获取token,通过token获取数据)
composer.json
require:{
......
"dingo/api": "1.0.*@dev"
}
-
-
-
配置Jwt(config/app.php)
'providers' => [
Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class,
]
'aliases' => [
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
]
-
-
使用Dingo API
配置Kernel.php
protected $routeMiddleware = [
......
'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,
]
-
配置api.php
'auth' => [
'basic' => function($app){
return new \Dingo\Api\Auth\Provider\Basic($app['auth']);
}
'jwt' => function($app){
return new \Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']);
}
],
修改为:
'auth' => [
'jwt' => 'Dingo\Api\Auth\Provider\JWT',
]
案例操作
1.注册路由
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
$api->group(['namespace' => 'App\Api\Controllers'], function ($api) {
//路由名称
});
});
2.实现路由
1.在app文件夹下面创建api文件夹,并创建controller和 transformer
-
-
-
-
-
-
-
1.前期准备
-
1.2数据准备
-
-
-
-
-
1.2.6 添加测试数据
-
命令行代码,添加猜测书数据
factory(Lesson::class,60)->create()
-
-