How to use JSON-RPC with FastAPI?

fastapi json

We’ll use FastAPI to take JSON-RPC requests. It should respond to “ping” with “pong”.

Install FastAPI and Uvicorn to take requests and Jsonrpcserver to process them:

pip install fastapi uvicorn jsonrpcserver

Create a

from fastapi import FastAPI, Request, Response
from jsonrpcserver import Result, Success, dispatch, method
import uvicorn

app = FastAPI()

def ping() -> Result:
    return Success("pong")"/")
async def index(request: Request):
    return Response(dispatch(await request.body()))

if __name__ == "__main__":, port=5000)

Start the server:

$ python
INFO:     Started server process [5377]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on (Press CTRL+C to quit)

Test it

Use curl to send a request:

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