Http Hobo

Another blog with web-development tips’n’tricks. | About me

1 post tagged

json-rpc

JSON-RPC implementation for Yii2

Hi there!

I’m currently working on a mobile application, and initially I used REST approach for client-server communication. However, it quickly started to drive me nuts as REST has a lot of flaws and in my opinion is not nice at all. In short – because it’s too hard to have transactions for operations. So I decided to move to JSON-RPC protocol. I considered GraphQL (seems a little bit overkill for my current needs), gRPC (you can’t have gRPC server written on PHP, so porting my existing Yii2-based server solution would take too much time), but JSON-RPC is the simplest and quickest way to go.

However, I haven’t found any Yii2 extension for this which I would like. Main thing I didn’t like is that existing extensions don’t use Yii2 power and features. That doesn’t make sense because why not go with standalone JSON-RPC server then?

So I wrote my own extension which translates “method” string to a route and then executes an action. Therefore Yii2 is used as usually, just with different entry point.

Let’s say we have the following controller:

<?php
namespace app\modules\api1\controllers;

class ExampleController extends \yii\web\Controller {

    public function actionTry() {
        return "You've got it!";
    }

    public function actionTryWithParams($foo) {
        return "Params received: \$foo = $foo.";
    }

}

Calls and responses would look like the following:

-> {"jsonrpc": "2.0", "method": "api1.example.try", "id": 1}
<- {"jsonrpc": "2.0", "result": "You've got it!", "id": 1}

-> {"jsonrpc": "2.0", "method": "api1.example.try-with-params", "params": {"foo": "bar"}, "id": 2}
<- {"jsonrpc": "2.0", "result": "Params received: $foo = bar.", "id": 2}

-> {"jsonrpc": "2.0", "method": "api1.example.garbage", "id": 3}
<- {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found."}, "id": 3}

-> [
	{"jsonrpc": "2.0", "method": "api1.example.try", "id": 1},
   	{"jsonrpc": "2.0", "method": "api1.example.try-with-params", "params": {"foo": "bar"}, "id": 2},
	{"jsonrpc": "2.0", "method": "api1.example.garbage", "id": 3}
   ]
<- [
	{"jsonrpc": "2.0", "result": "You've got it!", "id": 1},
   	{"jsonrpc": "2.0", "result": "Params received: $foo = bar.", "id": 2},
	{"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found."}, "id": 3}
   ]

Check it on GitHub or use with Composer (note that it’s only alpha available now as I’m still working on the extension and testing it):

"repositories": [
        {
            "type": "git",
            "url": "https://github.com/georgique/yii2-jsonrpc/"
        }
    ],
    "require": {
        "georgique/world-geojson": "*@dev"
    }
]

P.S.: Couldn’t post extension to official Yii2 site because rules are just insanely stupid there, which I will write another post about.

2018   json-rpc   json-rpc server   my releases   yii2   yii2 extensions