Search code examples
clojurejson-rpc

How to a json-rpc call from Clojure?


I've got a local server running on port 8545 which listen to JSON-RPC requests. I can call it using curl like this:

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0xf54c19d9ef3873bfd1f7a622d02d86249a328f06", "latest"],"id":1}' http://localhost:8545

What would be the equivalent call from Clojure? Do I need to add some external libraries to the project.clj?


Solution

  • I think you should try http-kit. Also you will need some library for json (data.json or cheshire)

    So add to your project.clj following dependencies:

    • [http-kit "2.1.18"]
    • [org.clojure/data.json "0.2.6"]

    And try this

    (ns your-ns
      (:require [org.httpkit.client :as http]
                [clojure.data.json :as json]))
    
    (let [url "http://localhost:8545"
          body (json/write-str 
                 {:jsonrpc "2.0"
                  :method "eth_getBalance"
                  :params ["0xf54c19d9ef3873bfd1f7a622d02d86249a328f06" "latest"]
                  :id 1})
          options {:body body}
          result @(http/post url options)]
      (prn result))