python plus json

We’ll start a server to take JSON-RPC requests. It should respond to “ping” with “pong”.

We’ll use Python’s built-in http.server module, so no web framework is required - only jsonrpcserver to process the messages:

$ pip install jsonrpcserver

Create a server.py:

from http.server import BaseHTTPRequestHandler, HTTPServer
from jsonrpcserver import methods

@methods.add
def ping():
    return 'pong'

class TestHttpServer(BaseHTTPRequestHandler):
    def do_POST(self):
        # Process request
        request = self.rfile.read(int(self.headers['Content-Length'])).decode()
        response = methods.dispatch(request)
        # Return response
        self.send_response(response.http_status)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(str(response).encode())

if __name__ == '__main__':
    HTTPServer(('localhost', 5000), TestHttpServer).serve_forever()

Start the server:

$ python server.py

Client

Use jsonrpcclient to send requests:

$ pip install 'jsonrpcclient[requests]'
$ python
>>> import jsonrpcclient
>>> jsonrpcclient.request('http://localhost:5000/', 'ping')
--> {"jsonrpc": "2.0", "method": "ping", "id": 1}
<-- {"jsonrpc": "2.0", "result": "pong", "id": 1} (200 OK)
'pong'