Search by

scripthoodie / json-rpc

scripthoodie

Transport agnostic JSON-RPC 2.0 request and response components.

Package info

codeberg.org/scripthoodie/json-rpc

Issues

pkg:composer/scripthoodie/json-rpc

Statistics

Installs: 16

Dependents: 1

Suggesters: 0

v2.0.1 2026-10-27 14:08 UTC

This package is auto-updated.

Last update: 2026-10-27 08:39:42 UTC


README

PHP PHPStan Packagist version Codeberg License

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.