Skip to content

Repository files navigation

json-api-server

Pre ReleaseLicense

json-api-server is a JSON:API server implementation in PHP.

It allows you to build a feature-rich API by defining resource schema and connecting it to your application's database layer.

Based on your schema definition, the package will serve a complete API that conforms to the JSON:API specification, including support for:

  • Showing individual resources (GET /articles/1)
  • Listing resource collections (GET /articles)
  • Sorting, filtering, pagination, and sparse fieldsets
  • Compound documents with inclusion of related resources
  • Creating resources (POST /articles)
  • Updating resources (PATCH /articles/1)
  • Deleting resources (DELETE /articles/1)
  • Content negotiation
  • Error handling
  • Localization for customizing error messages
  • Extensions including Atomic Operations
  • Generating OpenAPI definitions

Documentation

Read the documentation

Example

The following example uses an Eloquent model in a Laravel application. However, json-api-server can be used with any framework that can deal in PSR-7 Requests and Responses. Custom behavior can be implemented to support other ORMs and data persistence layers.

useApp\Models\User;
useTobyz\JsonApiServer\Laravel;
useTobyz\JsonApiServer\Laravel\EloquentResource;
useTobyz\JsonApiServer\Laravel\Filter;
useTobyz\JsonApiServer\Endpoint;
useTobyz\JsonApiServer\Schema\Field;
useTobyz\JsonApiServer\Schema\Type;
useTobyz\JsonApiServer\JsonApi;
class UsersResource extends EloquentResource
{
publicfunctiontype(): string
{
return'users';
}
publicfunctionnewModel(Context$context): object
{
returnnewUser();
}
publicfunctionendpoints(): 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')),
];
}
publicfunctionfields(): array
{
return [
Field\Attribute::make('name')
->type(Type\Str::make())
->writable()
->required(),
Field\ToOne::make('address')->includable(),
Field\ToMany::make('friends')
->type('users')
->includable(),
];
}
publicfunctionfilters(): array
{
return [Filter\Where::make('id'), Filter\Where::make('name')];
}
}
$api = newJsonApi();
$api->resource(newUsersResource());
/** @var Psr\Http\Message\ServerRequestInterface $request *//** @var Psr\Http\Message\ResponseInterface $response */try {
$response = $api->handle($request);
} catch (Throwable$e) {
$response = $api->error($e);
}

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

License

MIT

About

A JSON:API server implementation in PHP.

Topics

Resources

Stars

70 stars

Watchers

5 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages