tobyz / json-api-server

一个完全自动化的PHP实现的JSON:API服务器。

v1.0.0-beta.3 2023-12-08 23:22 UTC

README

Pre Release License

json-api-server是一个PHP实现的JSON:API服务器。

它允许你通过定义资源模式并将其连接到应用程序的数据库层来构建功能丰富的API。

根据您的模式定义,该包将提供符合JSON:API规范的完整API,包括以下支持:

  • 显示单个资源(GET /articles/1
  • 列出资源集合(GET /articles
  • 排序过滤分页稀疏字段集
  • 复合文档,包括相关资源
  • 创建资源(POST /articles
  • 更新资源(PATCH /articles/1
  • 删除资源(DELETE /articles/1
  • 内容协商
  • 错误处理
  • 扩展包括原子操作
  • 生成OpenAPI定义

文档

阅读文档

示例

以下示例使用Laravel应用程序中的Eloquent模型。然而,json-api-server可以与任何可以处理PSR-7请求和响应的框架一起使用。可以实施自定义行为以支持其他ORM和数据持久层。

use App\Models\User;
use Tobyz\JsonApiServer\Laravel;
use Tobyz\JsonApiServer\Laravel\EloquentResource;
use Tobyz\JsonApiServer\Laravel\Filter;
use Tobyz\JsonApiServer\Endpoint;
use Tobyz\JsonApiServer\Schema\Field;
use Tobyz\JsonApiServer\Schema\Type;
use Tobyz\JsonApiServer\JsonApi;

class UsersResource extends EloquentResource
{
    public function type(): string
    {
        return 'users';
    }

    public function newModel(Context $context): object
    {
        return new User();
    }

    public function endpoints(): array
    {
        return [
            Endpoint\Show::make(),
            Endpoint\Index::make()->paginate(),
            Endpoint\Create::make()->visible(Laravel\can('create')),
            Endpoint\Update::make()->visible(Laravel\can('update')),
            Endpoint\Delete::make()->visible(Laravel\can('delete')),
        ];
    }

    public function fields(): array
    {
        return [
            Field\Attribute::make('name')
                ->type(Type\Str::make())
                ->writable()
                ->required(),

            Field\ToOne::make('address')->includable(),

            Field\ToMany::make('friends')
                ->type('users')
                ->includable(),
        ];
    }

    public function filters(): array
    {
        return [Filter\Where::make('id'), Filter\Where::make('name')];
    }
}

$api = new JsonApi();

$api->resource(new UsersResource());

/** @var Psr\Http\Message\ServerRequestInterface $request */
/** @var Psr\Http\Message\ResponseInterface $response */
try {
    $response = $api->handle($request);
} catch (Throwable $e) {
    $response = $api->error($e);
}

贡献

欢迎提交拉取请求。对于重大更改,请首先提交问题以讨论您想要更改的内容。

许可

MIT