How to use JSON-RPC with Python's HTTPServer?

python 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

from http.server import BaseHTTPRequestHandler, HTTPServer

from jsonrpcserver import method, Result, Success, dispatch

def ping() -> Result:
    return Success("pong")

class TestHttpServer(BaseHTTPRequestHandler):
    def do_POST(self):
        # Process request
        request =["Content-Length"])).decode()
        response = dispatch(request)
        # Return response
        self.send_header("Content-type", "application/json")

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

Start the server:

$ python

Test it

$ curl -X POST http://localhost:5000 -d '{"jsonrpc": "2.0", "method": "ping", "id": 1}'
{"jsonrpc": "2.0", "result": "pong", "id": 1}