34
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WEB Apiの話 (JSON RPC)

Posted at

#WEB Apiの話 (JSON RPC)

前回の**Restの話があったように、
Rset Api作るために、CRUD操作
(GET, POST, PUT, DELETEDB)の設計、URIの設計、仕様作成しながら、決めていかないといけない、以外と面倒です。
今回、json-prc 2.0の話をします。

##json-prc 2.0
RPC (Remote Procedure Call リモート関数コール)の略です。
json-rpcは、json形式のRPCと考えればよいです。

話の前に、まずjson-rpc2.0の簡単な例で見てみましょう。

--> {"jsonrpc":"2.0", "method": "subtract", "params":[42, 23], "id": 1}
<-- {"jsonrpc": "2.0", "result": 19,"id": 1}
 --> は、リクエスト。 <-- は、レスポンス。
 jsonrpcにはJSON-RPCのバージョンを設定します。
 methodにはサーバに実行してもらうメソッド名を設定します。
 paramsにはメソッドの引数を設定します。
 idは、クライアントによって確立された識別子。なくでもよいです。レスポンスは、受け取った値をそのまま設定して返します。

##メリット
Restは、GET, POST, PUT, DELETEDBとは、考えるのは大変で、
json-rpcは、すべてpostになります。
データはすべてjson形式。
URLも、このように、楽勝 https://domain.com/xxx_api
主な設計は、Methodぐらいですね。

開発も楽、機能より、関数の実装を注力、テストも関数のテストになります。

##json-rpc2.0新機能

  • Notification
  • Batch
Notification(通知)

クライアントからサーバー側に情報を通知です。サーバにレスポンスの内容を返すことを要求しません。例えば、PVのカウントとか。
リスエストの「id」の要素を省略すると、自動的にNotificationとなります。

Batch

複数のリクエストを束ねたバッチリクエスト

--> [
{"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"},
{"jsonrpc": "2.0", "method": "notify_hello", "params": [7]},
{"jsonrpc": "2.0", "method": "subtract", "params": [42,23], "id": "2"},
{"foo": "boo"},
{"jsonrpc": "2.0", "method": "foo.get", "params": {"name": "myself"}, "id": "5"},
{"jsonrpc": "2.0", "method": "get_data", "id": "9"}
]
<-- [
{"jsonrpc": "2.0", "result": 7, "id": "1"},
{"jsonrpc": "2.0", "result": 19, "id": "2"},
{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null},
{"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": "5"},
{"jsonrpc": "2.0", "result": ["hello", 5], "id": "9"}
]

34
30
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?