使用 API Resource 来创建自己的 {JSON:API} 格式 API
在Laravel API中返回数据经常需要经过处理之后再返回,之前我们使用了第三方扩展 Fractal
实现数据格式转化,参照【扩展 API开发】DingoApi(二)
。
从Laravel 5.5开始,内置了 API Resource 功能帮助我们快速建立起模型和 JSON返回数据之间的桥梁。
API Resource
这里以 推荐资源 接口为例,http://larabbs_api1/api/links
,返回数据如下:1
2
3
4
5
6
7
8
9
10
11
12
13{
"data": [
{
"id": 1,
"title": "Lela Ryan",
"link": "https://www.powlowski.com/consequatur-est-dolorem-vitae-ab"
},
{
"id": 2,
"title": "Maria Abbott",
"link": "http://www.kozey.com/"
},
}
创建资源转化器1
php artisan make:resource ItemResourceCollection
生成的文件位于 app\Http\Resources 目录下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
26
27
28
29namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class ItemResourceCollection extends ResourceCollection
{
public function __construct($resource = null)
{
parent::__construct($resource);
}
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
*
* @return array
*/
public function toArray($request)
{
return $this->collection->map(function ($item) use ($request) {
return [
'id' => $item->id,
'title' => $item->title,
'link' => $item->link,
];
});
}
}
在控制器中的使用:1
2
3
4
5
6
7class LinksController extends Controller
{
public function index(Link $links)
{
return new ItemResourceCollection($links->getAllCached());
}
}
注意:这里的推荐资源获取的是一个集合,所以继承的是ResourceCollection
,还需要遍历这个集合设置格式。如果不是集合,只需继承Resource
即可。
兼容 JSON:API
默认数据结构被包裹到 data 里面,如果你不想有这个数据结构,可以通过下面的代码去除:1
2
3ItemResourceCollection::withoutWrapping();
return new ItemResourceCollection($links->getAllCached());
添加额外信息
在 ItemResourceCollection 类中添加with
函数,如:1
2
3
4
5
6
7
8public function with($request)
{
return [
'links' => [
'self' => url('api/articles/'),
],
];
}
返回的数据格式如下:1
2
3
4
5
6
7
8
9
10
11
12{
"data": [
{
"id": 1,
"title": "Lela Ryan",
"link": "https://www.powlowski.com/consequatur-est-dolorem-vitae-ab"
}
],
"links": {
"self": "http://larabbs_api1.test/api/articles"
}
}