aedart/athenaeum-http-api

基于Json的API实用工具

8.10.0 2024-09-23 07:54 UTC

README

意见性的实用工具,用于帮助你塑造和格式化API,使用Laravel的API资源

示例

以下示例展示了一个用于Eloquent User模型的“API资源”。

use Aedart\Http\Api\Resources\ApiResource;
use Illuminate\Http\Request;

class UserResource extends ApiResource
{
    public function formatPayload(Request $request): array
    {
        return $this->withTimestamps([
            'id' => $this->getResourceKey(),
            'name' => $this->name,
            'roles' => $this->belongsToManyReference('roles')
                ->withLabel('name')
                ->withSelfLink()
                ->withResourceType();
        ]);
    }

    public function type(): string
    {
        return 'user';
    }
}

当返回单个用户的响应时,将输出以下JSON

{
    "data": {
        "id": 34,
        "name": "Retta Altenwerth Jr.",
        "created_at": "2022-10-21T14:51:43+00:00",
        "updated_at": "2022-10-21T14:51:43+00:00",
        "roles": [
            {
                "id": 23,
                "name": "Machine Operator",
                "type": "role",
                "self": "https:///roles/23"
            },
            {
                "id": 56,
                "name": "File Clerk",
                "type": "role",
                "self": "https:///roles/56"
            }
        ]
    },
    "meta": {
        "type": "user",
        "self": "https:///users/34"
    }
}

文档

请阅读官方文档以获取更多信息。

仓库

单仓库位于github.com/aedart/athenaeum

版本控制

此包遵循语义版本控制2.0.0

许可证

BSD-3-Clause,请阅读此包中包含的LICENSE文件