tobscure / json-api-server
v1.0.0-beta.3
2023-12-08 23:22 UTC
Requires
- php: >=8.1
- ext-json: *
- asispts/http-accept: ^1.0
- doctrine/inflector: ^2.0
- nyholm/psr7: ^1.8
- psr/http-message: ^1.0
- psr/http-server-handler: ^1.0
Requires (Dev)
- dms/phpunit-arraysubset-asserts: ^0.5.0
- phpbench/phpbench: ^1.2
- phpunit/phpunit: ^10.2.2
This package is auto-updated.
Last update: 2024-09-13 09:05:31 UTC
README
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); }
贡献
欢迎提交拉取请求。对于重大更改,请首先打开一个问题以讨论您想要更改的内容。