PHPackages                             makedo/jsonrpc - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. makedo/jsonrpc

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

makedo/jsonrpc
==============

Json RPC server implementation for php with PSR-7 and PSR-11 support

0.0.2(4y ago)04MITPHPPHP ^8.0

Since Jul 24Pushed 4y ago1 watchersCompare

[ Source](https://github.com/makedo/jsonrpc)[ Packagist](https://packagist.org/packages/makedo/jsonrpc)[ RSS](/packages/makedo-jsonrpc/feed)WikiDiscussions master Synced 5d ago

READMEChangelog (2)Dependencies (6)Versions (3)Used By (0)

Json RPC server
===============

[](#json-rpc-server)

Built according to json rpc standard 2.0 described in with batch requests support

Requirements
------------

[](#requirements)

- PHP &gt;= 8.0
- ext-json
- any implementation of PSR-7 RequestInterface, ResponseInterface and ResponseFactoryInterface

Installation
------------

[](#installation)

`composer install makedo/json-rpc`

Usage
-----

[](#usage)

### Basic Example

[](#basic-example)

```
use Makedo\JsonRpc\Handler\Request\CallbackHandler;
use Makedo\JsonRpc\Request;
use Makedo\JsonRpc\Response;
use Makedo\JsonRpc\Handler\HandlerBuilder;

//Creating a json rpc request handler, implementation of RequestHandler
$requestHandler = new CallbackHandler(function (Request $request): Response {
    return Response\JsonRpcResponse::success('Hello world');
});

$responseFactory = new Psr7HttpResponseFactory();

//If set to true in case of error response will have stack trace and debug information.
//Set to true in development environment
$debug = false;

$httpRequestHandler = (new HandlerBuilder())->buildHttpRequestHandler(
    $requestHandler,
    $responseFactory,
    $debug
);

$httpRequest = new Psr7HttpRequest(
'{"jsonrpc":"2.0", "method":"hello", "params": {"world": true}, "id": 1}'
);
$httpResponse = $httpRequestHandler->handle($httpRequest);

echo $httpResponse->getBody()->getContents();
//{"jsonrpc":"2.0", "result":"Hello world", "id": "1"}
```

### Error example with debug

[](#error-example-with-debug)

```
use Makedo\JsonRpc\Exception\JsonRpcError;
use Makedo\JsonRpc\Handler\Request\CallbackHandler;
use Makedo\JsonRpc\Request;
use Makedo\JsonRpc\Response;
use Makedo\JsonRpc\Handler\HandlerBuilder;

$requestHandler = new CallbackHandler(function (Request $request): Response {
    throw JsonRpcError::methodNotFound('An error occurred');
});
$responseFactory = new Psr7HttpResponseFactory();
$debug = true;

$httpRequestHandler = (new HandlerBuilder())->buildHttpRequestHandler(
    $requestHandler,
    $responseFactory,
    $debug
);

$httpRequest = new Psr7HttpRequest(
'{"jsonrpc":"2.0", "method":"hello", "params": {"world": true}, "id": 1}'
);
$httpResponse = $httpRequestHandler->handle($httpRequest);

echo $httpResponse->getBody()->getContents();
//{"jsonrpc":"2.0", "error":{"code":-32601, "message":"Method not found", "data": {"debug":{"debugMessage":"An error occurred", "previousMessage":null, "trace":[...]}}}, "id": "1"}
```

### Advanced Usage

[](#advanced-usage)

#### Custom Json Encoder

[](#custom-json-encoder)

```
use Makedo\JsonRpc\Handler\HandlerBuilder;
use Makedo\JsonRpc\Json\DefaultEncoder;

//These params will be used in json_encode($options, $depth).
//Defaults are kept, only difference is JSON_THROW_ON_ERROR is always set.
$options = JSON_PRETTY_PRINT;
$depth = 1024;
$builder = (new HandlerBuilder())
    ->setJsonEncoder(new DefaultEncoder($options, $depth))
;
```

#### Custom Json Decoder

[](#custom-json-decoder)

```
use Makedo\JsonRpc\Handler\HandlerBuilder;
use Makedo\JsonRpc\Json\DefaultDecoder;

//Param $assoc is always set to true, so decoder should always decode to array

//These params will be used in json_decoe($options,true,$depth).
//Defaults are kept, only difference is JSON_THROW_ON_ERROR is always set.
$options = JSON_PRESERVE_ZERO_FRACTION;
$depth = 1024;
$builder = (new HandlerBuilder())
    ->setJsonDecoder(new DefaultDecoder($options, $depth))
;
```

#### Json rpc request extra validation and Invalid params error (Analogue of 401 in REST)

[](#json-rpc-request-extra-validation-and-invalid-params-error-analogue-of-401-in-rest)

```
use Makedo\JsonRpc\Exception\JsonRpcError;
use Makedo\JsonRpc\Handler\HandlerBuilder;
use Makedo\JsonRpc\Request\Factory\JsonRpcRequestFactory;

class MyRequestFactory extends JsonRpcRequestFactory {
    protected function getValidParams(array $requestData) : array
    {
        $params = parent::getValidParams($requestData);
        if (!isset($params['param1'])) {
            throw JsonRpcError::invalidParams('Invalid param1', ['param1' => 'Not present']);
        }
        return $params;
    }
}
$builder = (new HandlerBuilder())
    ->setRequestFactory(new MyRequestFactory())
;
```

#### Json rpc response result serialization

[](#json-rpc-response-result-serialization)

```
use Makedo\JsonRpc\Handler\HandlerBuilder;
use Makedo\JsonRpc\Response\Serializer\Result\ResultSerializer;

class MyResultSerializer implements ResultSerializer {
    public function serialize($result)
    {
        return [];
    }
}
$builder = (new HandlerBuilder())
    ->setResultSerializer(new MyResultSerializer())
;
```

#### Customising error response data in debug mode

[](#customising-error-response-data-in-debug-mode)

```
use Makedo\JsonRpc\Exception\JsonRpcError;
use Makedo\JsonRpc\Exception\Serializer\ErrorSerializer;
use Makedo\JsonRpc\Handler\HandlerBuilder;

class MyErrorSerializer implements ErrorSerializer {
    public function serialize(JsonRpcError $e): array
    {
        return [
            'traceAsString' => $e->getTraceAsString(),
        ];
    }
}
$builder = (new HandlerBuilder())
    ->setErrorSerializer(new MyErrorSerializer())
;
```

#### Procedure handling Using PSR-11 container

[](#procedure-handling-using-psr-11-container)

```
use Makedo\JsonRpc\Exception\JsonRpcError;
use Makedo\JsonRpc\Handler\HandlerBuilder;
use Makedo\JsonRpc\Handler\Request\ContainerHandler;
use Makedo\JsonRpc\Handler\Request\RequestHandler;
use Makedo\JsonRpc\Request;
use Makedo\JsonRpc\Response;

class GetUserHandler implements RequestHandler {

    private $userRepository;

    public function __construct($userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function handle(Request $request) : Response
    {
        $params = $request->getParams();
        $userId = $params['userId'] ?? null;
        if (!$userId) {
            throw JsonRpcError::invalidParams('No userId in request');
        }

        $user = $this->userRepository->findById($userId);

        return Response\JsonRpcResponse::success(['user' => $user]);
    }
}

$container = new Psr11Container();
$container->set('user.get', function() {
    return new GetUserHandler($userRepository);
});

$requestHandler = new ContainerHandler($container);
$builder = (new HandlerBuilder())->buildHttpRequestHandler(
    $requestHandler,
    new Psr7ResponseFactory()
);
```

### Plans and TODOS

[](#plans-and-todos)

- Async handling of batch requests

###  Health Score

21

—

LowBetter than 19% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity3

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

2

Last Release

1756d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e2714584eec1b2ae416a03df9b9323cb07a14de2580aa8e49b505d45856590bc?d=identicon)[makedo](/maintainers/makedo)

---

Top Contributors

[![makedo](https://avatars.githubusercontent.com/u/3338923?v=4)](https://github.com/makedo "makedo (9 commits)")

---

Tags

jsonjsonrpc

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/makedo-jsonrpc/health.svg)

```
[![Health](https://phpackages.com/badges/makedo-jsonrpc/health.svg)](https://phpackages.com/packages/makedo-jsonrpc)
```

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.8k18.5M1.6k](/packages/cakephp-cakephp)[thecodingmachine/graphqlite

Write your GraphQL queries in simple to write controllers (using webonyx/graphql-php).

5723.1M30](/packages/thecodingmachine-graphqlite)[neos/flow

Flow Application Framework

862.0M451](/packages/neos-flow)[datto/json-rpc

Fully unit-tested JSON-RPC 2.0 for PHP

1951.3M14](/packages/datto-json-rpc)[neos/flow-development-collection

Flow packages in a joined repository for pull requests.

144179.3k3](/packages/neos-flow-development-collection)[windwalker/framework

The next generation PHP framework.

25639.1k1](/packages/windwalker-framework)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
