How to send JSON-RPC API calls with JavaScript

In this tutorial, we are going to learn how to send a JSON RPC API call with vanilla JavaScript or Node.js using the fetch library.

In this tutorial, we are going to learn how to send a JSON RPC API call with vanilla JavaScript or Node.js using the fetch library.

If you are using Node.js, you first need to install the node-fetch library as it is not available by default in Node:

npm install node-fetch

Note: If you run into issues, install the version 2 instead of 3 with npm install node-fetch@2.6.7 .

With vanilla JavaScript or React, you won't need to install that.

With Node.js, you will then need to import the library:

const fetch = require('node-fetch');

You can now use the fetch library.

In this example, we are going to query the Solana RPC API to get information about a transaction.

Here is how to do that:

const URL = "https://api.mainnet-beta.solana.com"
const signature = "PLACE AN EXAMPLE TRANSACTION SIGNATURE HERE"

const response = await fetch(URL, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({
      jsonrpc: '2.0',
      id: 'get-transaction',
      method: 'getTransaction',
      params: [signature],
    }),
  });
  
  const data = await response.json()
  console.log(data)

For JSON-RPC APIs, the body of the request is where you put all the information required to process your query:

  • jsonrpc is the version you're using (here we use 2.0)
  • id is the identifier of your transaction. This is a reference for you to identify your API call and it will be sent back in the response.
  • method is the name of the method you want to execute in the API. You will find it in the documentation of the API you're using.
  • params is an array of values containing (in the right order) all the parameters you want to send to the API method you're using. You will find information about it in the documentation of the API you're using.

Once you get the response back, you need to call the .json() function on the response to convert the response to JSON and be able to process it. That function returns a promise so you need to await it.

Then, in the response in a JSON format, the returned data will be in the result property. If the result property is empty and error is true, then it means the API call failed.

What is inside the JSON response will depend on the API and you need to read through your API's documentation to learn more about it.

And that's it! 👏

Thanks for reading this article!