kraz / json-rpc-server
JSON-RPC 2.0 Server: transport-agnostic core, PSR-15 HTTP handler, attribute-driven methods, Service Mapping Description (SMD)
Requires
- php: >=8.4
- ext-json: *
- ext-mbstring: *
- psr/cache: ^3.0
- psr/container: ^2.0
- psr/http-factory: ^1.1
- psr/http-message: ^2.0
- psr/http-server-handler: ^1.0
- psr/log: ^3.0
Requires (Dev)
- doctrine/coding-standard: ^14.0
- nyholm/psr7: ^1.8
- phpstan/phpstan: ^2.1
- phpstan/phpstan-strict-rules: ^2.0
- phpunit/phpunit: ^11.5 || ^12.0 || ^13.0
- symfony/cache: ^7.4 || ^8.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
A complete JSON-RPC 2.0 server for PHP 8.4+.
- Transport-agnostic core — give it a JSON string, get a JSON string. HTTP is one transport among others.
- PSR-15 HTTP handler included, for any PSR-7/PSR-17 implementation.
- Methods are plain PHP methods marked with attributes; parameters are bound by position or by name and type-checked against the signature (scalars, arrays, enums, dates, nested objects).
- Service Mapping Description (SMD) generated from the signatures and doc blocks, served at
GET <endpoint>?smd. - Authentication and per-method authorization behind two small interfaces, so any framework can plug its own.
- Rate limiting, logging (PSR-3), caching (PSR-6), middleware, exception conversion.
- Batches, notifications and every error case of the specification.
The only dependencies are ext-json, ext-mbstring and PSR interfaces.
For Symfony there is a ready-made integration: kraz/json-rpc-server-bundle.
Installation
composer require kraz/json-rpc-server
Quick start
use Kraz\JsonRpcServer\Attribute\JsonRpcMethod; use Kraz\JsonRpcServer\Attribute\JsonRpcService; use Kraz\JsonRpcServer\Method\MethodRegistry; use Kraz\JsonRpcServer\Server; #[JsonRpcService('math')] final class MathService { /** * Subtracts one number from another. * * @param int $minuend the number to subtract from * @param int $subtrahend the number to subtract * * @return int the difference */ #[JsonRpcMethod] public function subtract(int $minuend, int $subtrahend): int { return $minuend - $subtrahend; } } $server = new Server(new MethodRegistry()->addService(new MathService())); echo $server->handle('{"jsonrpc": "2.0", "method": "math.subtract", "params": [42, 23], "id": 1}'); // {"jsonrpc":"2.0","result":19,"id":1}
Server::handle() never throws. It returns a ServerResult whose body is the JSON to send back, or null when
there is nothing to send (the payload carried notifications only).
Declaring methods
Only the methods carrying #[JsonRpcMethod] are exposed. Their name is <namespace>.<method>:
#[JsonRpcService('orders', description: 'Order management')] final class OrderService { #[JsonRpcMethod] // orders.find public function find(int $id): array { /* ... */ } #[JsonRpcMethod('cancel')] // orders.cancel public function cancelOrder(int $id, ?string $reason = null): bool { /* ... */ } }
A registry can also be filled with any callable:
$registry = new MethodRegistry() ->addService(new OrderService()) ->addCallable('echo', static fn (string $text): string => $text, 'Says it back.');
ContainerMethodRegistry does the same over a PSR-11 container: the services are instantiated only when one of
their methods is called, and the metadata can be kept in a PSR-6 cache pool.
Parameters
Parameters are accepted by position ("params": [42, 23]) or by name ("params": {"minuend": 42, "subtrahend": 23}).
An optional parameter may be left out; a variadic one collects the rest.
Values are never coerced between JSON types — the string "5" is not the integer 5 — with the one exception JSON
itself forces: an integer is accepted where a float is expected. Beyond the builtin types:
| PHP type | JSON value |
|---|---|
| backed enum | the value of a case |
| unit enum | the name of a case |
DateTimeImmutable, DateTime, ... |
a date and time string |
| any instantiable class | an object; its members are passed to the constructor by name (recursively), or set on public properties |
Anything that does not fit is answered with -32602 Invalid params, the message naming the offending parameter
("filter.createdAt" must be a date and time string), and data.parameter holding its path.
A parameter typed Context, Request, MethodDescriptor or IdentityInterface (or an implementation of it) is
supplied by the server and invisible to the caller:
#[JsonRpcMethod] public function whoami(IdentityInterface $identity, Context $context): array { return ['user' => $identity->getIdentifier(), 'ip' => $context->clientAddress]; }
Replace ValueConverterInterface (through new ArgumentResolver($converter)) to map values differently, and pass a
ResultNormalizerInterface to the server to return objects json_encode() does not understand.
Errors
Throw a JsonRpcException (or a subclass) to answer with an error of your own:
throw new JsonRpcException('Insufficient funds', 1001, ['balance' => 12.5]);
Any other exception is logged and answered with a bare -32603 Internal error — its message never reaches the
caller, unless the server runs with new ServerOptions(debug: true). To give domain exceptions a proper shape,
register an ExceptionConverterInterface.
| Code | Meaning | |
|---|---|---|
-32700 |
Parse error | the payload is not JSON |
-32600 |
Invalid Request | not a JSON-RPC 2.0 request; the batch is too large |
-32601 |
Method not found | |
-32602 |
Invalid params | |
-32603 |
Internal error | |
-32001 |
Authentication required | anonymous caller, or credentials which are not valid |
-32003 |
Access denied | the caller lacks a permission |
-32029 |
Rate limit exceeded | data.retryAfter holds the seconds to wait |
Authentication and authorization
The server does not authenticate anyone itself. It asks an AuthenticatorInterface who sent the payload:
interface AuthenticatorInterface { // null: no credentials were presented. Throws AuthenticationException: they are not valid. public function authenticate(Context $context): ?IdentityInterface; }
A framework integration typically reports the user its own security layer has already established (that is what
the Symfony bundle does for JWT, API keys, sessions, ...). Alternatively the transport may put the identity into the
Context it creates, and the authenticator is never asked. For standalone use the library ships
ApiKeyAuthenticator, CallbackAuthenticator and ChainAuthenticator:
$server = new Server( $registry, authenticator: new ApiKeyAuthenticator([ 'k-3f9a...' => new Identity('billing-service', ['orders.read']), 'k-77c1...' => new Identity('backoffice', ['orders.read', 'orders.cancel']), ]), );
ApiKeyAuthenticator reads the key from the X-API-Key header or from Authorization: Bearer <key>. For legacy
clients which cannot send a header it can also accept the key in the URI — new ApiKeyAuthenticator($identities, queryParameter: 'key') for /rpc?key=<key>. That is off by default: a key in a URI ends up in every log which
records URIs, so turn it on only where the network is trusted.
Who may call a method is declared on the method, or on the class for all of its methods:
#[JsonRpcService('orders')] #[RequiresPermission('orders.read')] // every method of the class final class OrderService { #[JsonRpcMethod] public function find(int $id): array { /* ... */ } #[JsonRpcMethod] #[RequiresPermission('orders.read', 'orders.cancel')] // all of them are required public function cancel(int $id): bool { /* ... */ } #[JsonRpcMethod] #[PublicAccess] // anyone public function statuses(): array { /* ... */ } }
#[PublicAccess]— anyone, authenticated or not.#[RequiresAuthentication]— any authenticated caller.#[RequiresPermission(...)]— an authenticated caller holding every listed permission. What a permission is, is up to theAuthorizationCheckerInterfaceof the server; the default one looks it up in the permissions of the identity.- No attribute — the default of the server (
ServerOptions::$defaultAccess): authenticated callers when the server has an authenticator, anyone otherwise.
Access is decided per call, so a batch may mix answered and refused calls. Credentials which are not valid fail the whole payload: nothing is called.
Service Mapping Description
$smd = new SmdGenerator()->generate($server, $context, 'https://example.com/rpc');
{
"transport": "POST",
"envelope": "JSON-RPC-2.0",
"contentType": "application/json",
"SMDVersion": "2.0",
"target": "https://example.com/rpc",
"services": {
"math.subtract": {
"description": "Subtracts one number from another.",
"parameters": [
{"name": "minuend", "type": "integer", "description": "the number to subtract from"},
{"name": "subtrahend", "type": "integer", "description": "the number to subtract"}
],
"returns": {"type": "integer", "description": "the difference"}
}
}
}
The description is made for the caller described by the context: it lists the methods that caller may call, and nothing else. Enums are published with their values, classes with their properties, optional parameters with their defaults.
HTTP
HttpHandler is a PSR-15 request handler:
use Kraz\JsonRpcServer\Http\HttpHandler; use Nyholm\Psr7\Factory\Psr17Factory; $factory = new Psr17Factory(); $handler = new HttpHandler($server, $factory, $factory); $response = $handler->handle($request); // any PSR-7 server request
| Request | Answer |
|---|---|
POST <endpoint> |
the JSON-RPC answer to the payload of the body |
GET <endpoint>?smd |
the service mapping description (can be turned off) |
A JSON-RPC answer is sent with the status 200 — errors included, they are part of the protocol — or 204 when
there is nothing to answer. The exceptions are the cases in which nothing was called at all: 401 (the credentials
are not valid) and 429 (rate limited, with Retry-After); 405, 413 and 415 reject what is not a JSON-RPC
POST. All of them still carry a JSON-RPC error body.
HttpOptions holds the body size limit (1 MiB by default) and the SMD switch. Pass a context factory to trust a
proxy header for the client address, or to hand over an identity a PSR-15 middleware has already established.
Rate limiting
$server = new Server($registry, rateLimiter: new CacheRateLimiter($psr6Pool, limit: 120, interval: 60));
Every call of a payload consumes a token — a batch of 50 costs 50 — counted per authenticated caller, or per
network address for anonymous ones (ServerOptions::$rateLimitKey changes that). A payload which does not fit in
the budget is refused as a whole. Implement RateLimiterInterface to use another limiter.
Middleware
A middleware wraps every call, once the method is known and before access is checked and the parameters are bound:
final class Transactional implements MiddlewareInterface { public function process(Invocation $invocation, callable $next): mixed { return $this->connection->transactional(static fn () => $next($invocation)); } } $server = new Server($registry, middleware: [new Transactional($connection)]);
Options
new ServerOptions( name: 'default', // #[JsonRpcService(servers: [...])] refers to it description: null, // published in the SMD debug: false, // expose exception details in "Internal error" maxBatchSize: 100, // 0: unlimited maxDepth: 64, // nesting limit of the JSON payload defaultAccess: null, // AccessPolicy::public() / ::authenticated() rateLimitKey: null, // fn (Context): ?string );
License
This library is licensed under the MIT License. See the LICENSE file for details.