User Tools

Site Tools


tanszek:oktatas:iss_t:json-rpc

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
tanszek:oktatas:iss_t:json-rpc [2026/03/01 17:02] – [1. Introduction] kneheztanszek:oktatas:iss_t:json-rpc [2026/03/01 17:27] (current) – [JSON-RPC Client (Python)] knehez
Line 1: Line 1:
 ===== JSON-RPC ===== ===== JSON-RPC =====
- 
-==== 1. Introduction ==== 
  
 JSON-RPC (JavaScript Object Notation – Remote Procedure Call) is a lightweight remote procedure call protocol that uses JSON for encoding messages. It allows a client to call functions (methods) on a remote server as if they were local functions. JSON-RPC (JavaScript Object Notation – Remote Procedure Call) is a lightweight remote procedure call protocol that uses JSON for encoding messages. It allows a client to call functions (methods) on a remote server as if they were local functions.
Line 22: Line 20:
 The current widely used version is JSON-RPC 2.0. https://www.jsonrpc.org/specification The current widely used version is JSON-RPC 2.0. https://www.jsonrpc.org/specification
  
 +==== JSON-RPC 2.0 Message Structure ====
 +
 +A JSON-RPC request is a JSON object with the following fields:
 +
 +  * **jsonrpc** – must be "2.0"
 +  * **method** – name of the remote method
 +  * **params** – parameters (optional)
 +  * **id** – request identifier (used to match response)
 +
 +Example request:
 +
 +<code json> { "jsonrpc": "2.0", "method": "add", "params": [5, 7], "id": 1 } </code>
 +
 +Successful response:
 +
 +<code json> { "jsonrpc": "2.0", "result": 12, "id": 1 } </code>
 +
 +Error response:
 +
 +<code json> { "jsonrpc": "2.0", "error": { "code": -32601, "message": "Method not found" }, "id": 1 } </code>
 +
 +==== Notifications ====
 +
 +If the client sends a request without an id, it becomes a notification.
 +
 +The server must NOT send a response.
 +
 +Example:
 +
 +<code json> { "jsonrpc": "2.0", "method": "logEvent", "params": {"event": "started"} } </code>
 +
 +==== Batch Requests ====
 +
 +JSON-RPC supports sending multiple requests in one array:
 +
 +<code json> [ {"jsonrpc": "2.0", "method": "add", "params": [1,2], "id": 1}, {"jsonrpc": "2.0", "method": "subtract", "params": [5,3], "id": 2} ] </code>
 +
 +==== 6. Practical Example in Python ====
 +
 +In this section, we implement a simple JSON-RPC server and client using Python.
 +
 +We will use:
 +
 +  * Flask (for HTTP server)
 +
 +  * requests (for client)
 +
 +Install dependencies:
 +
 +<code bash> pip install flask requests </code>
 +
 +===== JSON-RPC Server (Python + Flask) =====
 +
 +Create a file: //server.py//
 +
 +<sxh python> 
 +from flask import Flask, request, jsonify
 +
 +app = Flask(__name__)
 +
 +# available RPC methods
 +
 +def add(a, b):
 +    return a + b
 +
 +
 +def subtract(a, b):
 +    return a - b
 +
 +
 +methods = {
 +    "add": add,
 +    "subtract": subtract,
 +}
 +
 +
 +@app.route("/rpc", methods=["POST"])
 +def rpc():
 +    data = request.get_json()
 +
 +    if data.get("jsonrpc") != "2.0":
 +        return jsonify(
 +            {
 +                "jsonrpc": "2.0",
 +                "error": {"code": -32600, "message": "Invalid Request"},
 +                "id": data.get("id"),
 +            }
 +        )
 +
 +    method_name = data.get("method")
 +    params = data.get("params", [])
 +    request_id = data.get("id")
 +
 +    if method_name not in methods:
 +        return jsonify(
 +            {
 +                "jsonrpc": "2.0",
 +                "error": {"code": -32601, "message": "Method not found"},
 +                "id": request_id,
 +            }
 +        )
 +
 +    try:
 +        result = methods[method_name](*params)
 +        return jsonify(
 +            {
 +                "jsonrpc": "2.0",
 +                "result": result,
 +                "id": request_id,
 +            }
 +        )
 +    except Exception as e:
 +        return jsonify(
 +            {
 +                "jsonrpc": "2.0",
 +                "error": {"code": -32603, "message": str(e)},
 +                "id": request_id,
 +            }
 +        )
 +
 +
 +if __name__ == "__main__":
 +    app.run(port=5000)
 +
 +</sxh>
 +
 +Run:
 +
 +<code bash> python server.py </code>
 +
 +===== JSON-RPC Client (Python) =====
 +
 +Create a file: //client.py//
 +
 +<sxh python>
 +import requests import json
 +
 +url = "http://localhost:5000/rpc"
 +
 +payload = {
 +  "jsonrpc": "2.0",
 +  "method": "add",
 +  "params": [10, 15],
 +  "id": 1
 +}
 +
 +response = requests.post(url, json=payload)
 +
 +print("Status:", response.status_code)
 +print("Response:", response.json())
 +</sxh>
 +
 +Expected output:
 +
 +<code> Status: 200 Response: {'jsonrpc': '2.0', 'result': 25, 'id': 1} </code>
 +
 +==== Error Codes in JSON-RPC 2.0 ====
  
 +^ Code ^ Meaning ^
 +| -32700 | Parse error |
 +| -32600 | Invalid Request |
 +| -32601 | Method not found |
 +| -32602 | Invalid params |
 +| -32603 | Internal error |
tanszek/oktatas/iss_t/json-rpc.1772384532.txt.gz · Last modified: 2026/03/01 17:02 by knehez