scripthoodie / swoole-json-rpc
A Swoole request handler for JSON-RPC API.
Requires
- php: ^8.4
- scripthoodie/json-rpc: ^2.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.75
- phpstan/phpstan: ^2.1
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
swoole-json-rpc lets a Swoole HTTP server speak JSON-RPC 2.0. Methods are ordinary callables; the handler takes care of everything else — routing, CORS, malformed requests, notifications, and error envelopes.
Installation
Install the latest version with:
composer require scripthoodie/swoole-json-rpc
swoole-json-rpc requires PHP 8.4 or above, plus the Swoole extension.
Usage
Create a handler, hook it to the server's request event, and dispatch methods from a match:
use Swoole\Http\Server;
use ScriptHoodie\Swoole\JsonRpc\Handler;
use ScriptHoodie\Swoole\JsonRpc\Exceptions\NotFoundException;
$server = new Server('0.0.0.0', 9501);
$server->on('request', new Handler(
function (string $method, array $params, string|int|null $id): mixed {
return match ($method) {
'ping' => 'pong',
'sum' => array_sum($params),
default => throw new NotFoundException(),
};
},
basePath: '/v1',
allowedOrigins: ['http://app.localhost'],
allowedHeaders: ['Authorization'],
));
$server->start();
The method handler receives the method name, its params, and the request id; whatever it returns is sent back to the client as the result.
How requests are handled
- A
POSTto the base path is served with JSON-RPC 2.0 envelopes; every other route gets a plain 404. OPTIONSrequests are answered as CORS preflights. An origin gets CORS headers only when it is listed inallowedOrigins, and the reply advertisesPOSTalong withContent-Typeand any extraallowedHeaders.- Anything besides a
POSTwith anapplication/jsoncontent type is rejected with a plain 405 or 415. - A body the parser cannot accept is answered with a JSON-RPC error envelope and a 400 status.
- Notifications (requests without an id) get an empty 204, even when the method handler fails.
Errors
Errors from the method handler are mapped onto JSON-RPC errors:
NotFoundException— 404, method not foundValidationException— 422, validation error, carrying the exception's dataBadRequestException(and any otherInvalidArgumentException) — 400, invalid params- Any other uncaught error — 500, internal error; the exception message is never leaked
Batch requests
Batch requests are not supported at the moment. A JSON array body is answered with an invalid-request error.
Submitting bugs and feature requests
Bugs and feature requests are tracked on Codeberg; see https://codeberg.org/scripthoodie/swoole-json-rpc/issues for the issue tracker.
Contributing
See CONTRIBUTING.md for the development environment and coding conventions.
License
swoole-json-rpc is licensed under the GPL-3.0-or-later License — see the LICENSE file for details.