scripthoodie / json-rpc
Transport agnostic JSON-RPC 2.0 request and response components.
Requires
- php: ^8.4
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.75
- phpstan/phpstan: ^2.1
- phpstan/phpstan-phpunit: ^2.0
- phpunit/phpunit: ^11.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
json-rpc provides JSON-RPC 2.0 request and response components. It parses raw request bodies into value objects and encodes responses into the 2.0 wire format, so you are free to pick your own transport.
Installation
Install the latest version with:
composer require scripthoodie/json-rpc
json-rpc requires PHP 8.4 or above. The JSON API is part of PHP core since PHP 8.0, so the package has zero runtime dependencies.
Basic usage
use ScriptHoodie\JsonRpc\Exceptions\RpcRequestException;
use ScriptHoodie\JsonRpc\RpcErrorCode;
use ScriptHoodie\JsonRpc\RpcRequest;
use ScriptHoodie\JsonRpc\RpcResponse;
function handle(string $rawBody): ?string
{
try {
$request = RpcRequest::fromJson($rawBody);
} catch (RpcRequestException $exception) {
return RpcResponse::createError(
$exception->getRpcErrorCode(),
$exception->getRpcId(),
)->toJson();
}
if ($request->isNotification()) {
return null;
}
$response = match ($request->method) {
'ping' => RpcResponse::createSuccess('pong', $request->id),
default => RpcResponse::createError(
RpcErrorCode::MethodNotFound,
$request->id,
),
};
return $response->toJson();
}
Wire this into any transport — an HTTP controller, a CLI command, a queue
consumer. Notifications (isNotification()) are never answered.
Documentation
The full documentation lives in the docs directory:
- API — request, response and exception value objects
- Error handling — standardized error codes and parser behavior
Batch requests
Batch requests are not supported at the moment. RpcRequest::fromJson()
expects a single request object and rejects a JSON array body with an
InvalidRequest (-32600) error.
Submitting bugs and feature requests
Bugs and feature requests are tracked on Codeberg; see https://codeberg.org/scripthoodie/json-rpc/issues for the issue tracker.
Contributing
See CONTRIBUTING.md for the development environment and coding conventions.
License
json-rpc is licensed under the GPL-3.0-or-later License — see the LICENSE file for details.