API 系列教程(三):使用 API Resource 来创建自定义 JSON 格式的 API

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lamp_yang_3533/article/details/85041133

上一篇教程中我们通过 jwt-auth 实现了 Laravel 的 API 认证。

用户请求登录接口 http://apidemo.test/api/auth/login 登录成功后,获取到 JSON 响应,响应头会带有 token 信息。

Authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjE1LCJpc3MiOiJodHRwOi8vYXBpZGVtby50ZXN0L2FwaS9hdXRoL2xvZ2luIiwiaWF0IjoxNTIyOTQ3NjgyLCJleHAiOjE1MjI5NTEyODIsIm5iZiI6MTUyMjk0NzY4MiwianRpIjoidnhCeU10bVFnbGFBdm14WSJ9.iJc1LCbkK-2HIydp6cZ_a191ZYNT7GSfy6y9D9LTq9E

Authorization 对应的值就是 token(令牌)。

然后,用户就可以通过访问 http://apidemo.test/api/auth/user 获取当前登录用户的信息。

必须传递请求头:

Authorization:Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjE1LCJpc3MiOiJodHRwOi8vYXBpZGVtby50ZXN0L2FwaS9hdXRoL2xvZ2luIiwiaWF0IjoxNTIyOTQ3NjgyLCJleHAiOjE1MjI5NTEyODIsIm5iZiI6MTUyMjk0NzY4MiwianRpIjoidnhCeU10bVFnbGFBdm14WSJ9.iJc1LCbkK-2HIydp6cZ_a191ZYNT7GSfy6y9D9LTq9E

形式为:

Authorization:Bearer $token

如果 token 正确且有效,就会获取到该用户的信息:

{
    "status": "success",
    "data": {
        "id": 15,
        "name": "user02",
        "email": "[email protected]",
        "created_at": "2018-04-05 21:13:16",
        "updated_at": "2018-04-05 21:13:16",
        "api_token": null
    }
}

可以发现,上面的返回数据以原生格式返回,没有经过任何处理,甚至有可能包含敏感信息。

我们可以处理之后再返回,一二个接口还好,如果现实业务中面对成百上千个接口呢?这种处理方式显然不合适,不仅耗费大量时间和精力,复用性差,且难以维护。

好在 Laravel 5.5 开始,内置了 API Resource 功能,可帮助我们快速建立起模型和返回的 JSON 数据之间的桥梁。

在此之前,很多人是通过第三方扩展包基于 Fractal 实现数据格式转化的,API Resource 有点类似把 Fractal 扩展包收编为官方特性的味道,为了更好的引入 API Resource ,我们先来看看 Fractal 怎么用。

Laravel Fractal 扩展包

这里,在之前项目的基础上进行开发,避免重复劳动。

首先,通过 Composer 安装对应扩展包

composer require spatie/laravel-fractal

安装完成后,发布配置文件以便定制 Fractal:

php artisan vendor:publish --provider="Spatie\Fractal\FractalServiceProvider"

还是以 User 模型为例,我们为它创建一个格式转化器:

php artisan make:transformer UserTransformer

编辑生成的 app/Transformers/UserTransformer 文件内容如下:

<?php
namespace App\Transformers;

use App\User;
use League\Fractal\TransformerAbstract;

class UserTransformer extends TransformerAbstract
{
    /**
     * A Fractal transformer.
     * @param User $user
     * @return array
     */
    public function transform(User $user)
    {
        return [
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email
        ];
    }
}

接下来,通过 Fractal 替换 AuthController 控制器的 user() 方法实现:

use App\Transformers\UserTransformer;
public function user(Request $request)
{
    $user = auth()->user();
    $user = fractal($user, new UserTransformer())->toArray();
    return response()->json($user);
}

再次访问 http://apidemo.test/api/auth/user 接口,会返回经过转化的数据格式:

{
    "data": {
        "id": 15,
        "name": "user02",
        "email": "[email protected]"
    }
}

或者,使用 respond() 方法简化代码。

public function user(Request $request)
{
    $user = auth()->user();
    return fractal($user, new UserTransformer())->respond();
}

返回结果和上面一致。

还可以添加响应状态码和响应头:

public function user(Request $request)
{
    $user = auth()->user();
    return fractal($user, new UserTransformer())->respond(200, [
        'a-header'         => 'a value',
        'another-header'   => 'another value',
    ]);
}

甚至,通过回调实现更复杂的功能:

use Illuminate\Http\JsonResponse;
public function user(Request $request)
{
    $user = auth()->user();
    return fractal($user, new UserTransformer())->respond(function(JsonResponse $response) {
        $response
            ->setStatusCode(200)
            ->header('a-header', 'a value')
            ->withHeaders([
                'another-header' => 'another value',
                'yet-another-header' => 'yet another value',
            ]);
    });
}

以上就是 Laravel Fractal 扩展包的一个基本使用,更多使用方法可查看其 Github 项目。

Laravel 5.5 新增的 API Resource 功能与上述实现思路基本一致,不过由于有官方加持,所以与 Laravel Eloquent 模型的各种功能结合可能更加紧密。

API Resource

这里,通过 Article 模型类来演示 API Resource 的使用。

在使用 API Resource 之前,访问 http://apidemo.test/api/articles/1 接口,返回的数据格式如下:

{
    "id": 1,
    "title": "Ea quibusdam occaecati ut voluptas ipsam error molestiae.",
    "body": "Dolores vitae inventore sapiente esse aut. Dolorum eaque facilis aperiam fugit. Mollitia voluptatem molestiae dolor.",
    "created_at": "2018-04-04 18:23:48",
    "updated_at": "2018-04-04 18:23:48"
}

同样也是原生数据。下面我们通过如下 Artisan 命令来创建一个资源转化器:

php artisan make:resource ArticleResource

生成的文件位于 app\Http\Resources 目录下,编辑 ArticleResource 类代码如下:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

class ArticleResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'type' => 'article',
            'id'   => (string)$this->id,
            'attributes' => [
                'title' => $this->title,
                'content' => $this->body,
            ],
        ];
    }
}

然后修改 ArticleController 控制器的 show() 方法实现:

use App\Http\Resources\ArticleResource;
/**
 *  获取文章的单条记录
 */
public function show(Article $article)
{
    return new ArticleResource($article);
}

再来访问 http://apidemo.test/api/articles/1 ,返回的数据格式如下:

{
    "data": {
        "type": "article",
        "id": "1",
        "attributes": {
            "title": "Ea quibusdam occaecati ut voluptas ipsam error molestiae.",
            "content": "Dolores vitae inventore sapiente esse aut. Dolorum eaque facilis aperiam fugit. Mollitia voluptatem molestiae dolor."
        }
    }
}

兼容 JSON:API

默认数据结构被包裹到 data 里面,如果你不想要这个数据结构,可以通过下面的代码去除:

public function show(Article $article)
{
    ArticleResource::withoutWrapping();
    return new ArticleResource($article);
}

这样,返回的数据格式如下:

{
    "type": "article",
    "id": "1",
    "attributes": {
        "title": "Ea quibusdam occaecati ut voluptas ipsam error molestiae.",
        "content": "Dolores vitae inventore sapiente esse aut. Dolorum eaque facilis aperiam fugit. Mollitia voluptatem molestiae dolor."
    }
}

额外的数据信息

有时,你想要返回数据库记录以外的其他相关数据,如:分页信息或者页面 URL。

可以在 ArticleResource 控制器中新增 with 方法来实现:

public function with($request)
{
    return [
        'links'    => [
            'self' => url('api/articles/' . $this->id),
        ],
    ];
}

再来访问 http://apidemo.test/api/articles/1 ,返回的数据是:

{
    "data": {
        "type": "article",
        "id": "1",
        "attributes": {
            "title": "Ea quibusdam occaecati ut voluptas ipsam error molestiae.",
            "content": "Dolores vitae inventore sapiente esse aut. Dolorum eaque facilis aperiam fugit. Mollitia voluptatem molestiae dolor."
        }
    },
    "links": {
        "self": "http://apidemo.test/api/articles/1"
    }
}

关联关系

除此之外,返回与文章模型关联的其他模型数据如评论、作者信息等也是很常见的需求,API Resource 也可以对此提供良好的支持。

为了演示此功能,首先我们创建一个 Comment 评论模型类和对应的迁移文件。

php artisan make:model Comment -m

编辑生成的迁移文件类 CreateCommentsTable 的 up 方法:

public function up()
{
    Schema::create('comments', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('post_id');
        $table->integer('user_id');
        $table->string('content');
        $table->tinyInteger('status');
        $table->timestamps();
    });
}

然后运行如下命令将变更同步到数据库:

php artisan migrate

再生成一个填充器类为数据表 comments 填充一些测试数据:

php artisan make:seeder CommentsTableSeeder

编辑生成的 database/seeds/CommentsTableSeeder.php 类代码:

<?php

use Illuminate\Database\Seeder;

use App\Comment;

class CommentsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // Let's truncate our existing records to start from scratch.
        Comment::truncate();

        $faker = \Faker\Factory::create();

        // And now, let's create a few articles in our database:
        for ($i = 0; $i < 100; $i++) {
            Comment::create([
                'post_id' => random_int(1, 50),
                'user_id' => random_int(1, 14),
                'status' => random_int(0, 1),
                'content' => $faker->sentence,
            ]);
        }
    }
}

运行以下 Artisan 命令将测试数据插入数据表:

php artisan db:seed --class=CommentsTableSeeder

在 App\Article 模型类中定义关联关系:

public function comments()
{
    return $this->hasMany(Comment::class, 'post_id', 'id');
}

为这个关联关系创建资源转化器:

php artisan make:resource --collection ArticleCommentsResource

然后修改 ArticleResource 类的 toArray() 方法:

public function toArray($request)
{
    return [
        'type' => 'article',
        'id'   => (string)$this->id,
        'attributes' => [
            'title' => $this->title,
            'content' => $this->body,
        ],
        'comments' => new ArticleCommentsResource($this->comments),
    ];
}

再来访问 http://apidemo.test/api/articles/1 ,返回的数据是:

{
    "data": {
        "type": "article",
        "id": "1",
        "attributes": {
            "title": "Ea quibusdam occaecati ut voluptas ipsam error molestiae.",
            "content": "Dolores vitae inventore sapiente esse aut. Dolorum eaque facilis aperiam fugit. Mollitia voluptatem molestiae dolor."
        },
        "comments": [
            {
                "id": 75,
                "post_id": 1,
                "user_id": 2,
                "content": "Eos esse rerum asperiores ut deleniti.",
                "status": 1,
                "created_at": "2018-04-06 13:13:44",
                "updated_at": "2018-04-06 13:13:44"
            }
        ]
    },
    "links": {
        "self": "http://apidemo.test/api/articles/1"
    }
}

如果想要自定义 comments 的返回字段可以去修改 ArticleCommentsResource 类。

API Resource 最大的优点是解耦了数据格式与业务代码的耦合,提高了代码的复用性和可维护性,更多功能可以参考官方文档。

总结

这三篇教程都是围绕功能角度讲 API,后面将围绕限流、开关降级以及性能优化等来阐述 API 的构建。

猜你喜欢

转载自blog.csdn.net/lamp_yang_3533/article/details/85041133
API