paint-brush
Understanding Blockchain APIs and RPC Nodes. by@etimfon
199 reads

Understanding Blockchain APIs and RPC Nodes.

by EtiSeptember 17th, 2024
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

This article covers beginners basics on everything you need to know about RPCs and APIs and how dRPCs APIs work.
featured image - Understanding Blockchain APIs and RPC Nodes.
Eti HackerNoon profile picture

This article covers the concept of APIs and RPCs, how they work, overview on protocols which offers RPCs and API as a service but for a proper understanding of what RPCs are, understanding how blockchains work is very important.


In every transaction, two parties are always involved. A transaction can be sending and receiving or crypto, it could be contract calling another contract. Data and resources are exchanged between the blockchain and the application in this process. This data as well could be queried to get the token balance or number of transactions. For proper fetching of data to enhance communication and update user/platform’s data across between accounts and decentralized applications (Dapps), etc., a point of contact is required.


To give you a better mental model of this point of contact; imagine a tunnel (which of course has two ends), at one end is party A who sends encoded information (information in a certain format) to party B, and party B receives this information and sends back a response. Since this information is encoded and probably in its raw form, without decoding the information, the receiving party (which is B in this context) lacks understanding of the encoded data sent. You can look at this tunnel as a pipeline which both parties use to communicate and the pipeline passes the information sent before delivery can be made to the receiving end.


With this structure, you can infer that between both ends, reading and can relaying of information is done between both parties making delivering the information to both parties possible. This is similar to the architecture and experience to which APIs and RPCs brings to users and decentralized applications. Look at one end as the Dapp and the other end as the blockchain and the tunnel as the API and RPC.

In this article, more mental models will be shared as we delve deep into different APIs.

Technically, what is a Blockchain API?

An API stands for Application Programming Interface which acts as an intermediary or you can say middleman to enable communication between two parties. It could be a client and a server. In blockchain context, you at the API/Dapp as the client and blockchain network as the server.


Different needs for communication can exist it could be querying on-chain data related to either decentralized exchanges (DEXs), getting count of fungible token balances in a particular wallet, wallet data, number of transactions ,or metadata of a non-fungible token . As stated about communications in the second paragraph of the last section, transactions can be a good case study; a decentralized applications may require price of a liquidity pool let’s say a user wants to make sales which may be selling of tokens or even buying, these APIs aids the functionality of the Dapp to be able to fetch the exact price pair to give to the user.


Let me assume you’re reading without a slight knowledge of web3. As a web2 user, with your mobile phone you want to get the forecasted weather temperature for the next day, asides other automation that has been made, upon clicking on your weather application to check, an API requests the data from an offline server. This request is first triggered on the frontend interface and then the service on your phone sends a request to the client which in return sends back a feedback and displays the temperature.


This action and process doesn’t seem to take this route as it all happens within seconds although this isn’t the concern of a regular user, it is mostly the concern of developers as users just make their intents with the applications and their off to their daily work. In essence, These APIs help developers to set up a communication pipeline to fetch data to save cost of having to build a whole different pipeline to facilitate transactions. In essence, it enhances communication, helps in the running of smart contracts, and monitoring network performance in the scope of blockchain.


Despite these APIs designed for the functionality to enhance and aid communication between services and applications, APIs can serve various purposes hence why different APIs are built but in blockchains,

Types of APIs

  • Simple Access Object Protocol APIs (SAOP APIs)
  • Representational state transfer APIs (REST APIs)
  • Remote Procedure Call APIs (RPC APIs)
  • WebSocket APIs


Simple Access Object Protocol APIs

Like every other APIs which I will be explaining next. All APIs have specific designs which gives it different purposes and hence utility. The differences in their designs gives you preference on how you can use them, how they interact with endpoints and and how they relay message. SOAP API is an API which utilizes XML files to allow for the exchange of structured information in distributed environments.


Designing a SAOP API allows for communication between applications on different operating systems written in different programming languages.


Having that it uses XML for data format, this gives it four (4) distinct dimensions for communicating of data across services. These endpoints include:

  • Envelope
  • Encoding
  • Requests
  • Response


An example of an XML request can be:


POST /WebServiceEndpoint HTTP/1.1 Host: www.example.com Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "http://www.example.com/CheckUser"


Representational state transfer APIs - REST APIs


REST APIs are APIs in which data is formatted just like that of SOAP APIs with difference that REST APIs aren’t format-specific. REST APIs format data in XML and JSON to make server-side data readily available.


REST APIs are cache-friendly and as well and they are also useful for building straightforward, resource-based applications that don’t require a high degree of query flexibility.


As mentioned earlier different APIs, different architectures, REST APIs are designed to follow and adhere to the following architectural constraints:


  • Native caching
  • A layered system
  • Uniformity in its interface
  • Completely statelessness. This means that the server handling the API requests does not retain any information or session data about the client's previous requests giving flexibility between the clients and servers.
  • The ability to provide executable code to the client unlike other forms of API, this adds to the ability for the server to offload certain responsibilities to the client by sending executable logic creating more interactive or dynamically adjustable clients. This makes REST more versatile, as it can seamlessly support dynamic behavior in web apps.


Remote Procedure Calls APIs - RPC APIs


RPC APIs are regarded as the simplest forms of APIs as it uses two main HTTP functions for the relays of message where it uses GET to fetch information and POST for everything else.


WebSockets APIs

This type of API provides communication over a single TCP connection and with this APIs, you can send messages to a server and receive event-driven responses without needing to poll the server for a reply.


Despite these APIs being listed, some APIs work best for some RPCs and some doesn’t.


In a case for the communication of transactions done on a blockchain, a REST API can be created to get the data of a a particular block on a blockchain. A protocol just like Infura uses a REST API to interact with the Ethereum blockchain, enabling actions such as querying smart contracts or sending transactions in the same vein its important to note that most communications in blockchains may need a node while some might not.


Just like in getting the transactions data of a block, a node will be needed since it requires on-chain computation, but in a case where off-chain computation runs, a node isn’t needed.

What then is a node? Is an RPC Node the same as a Node?

Nice try, but there is a concept conflation that needs to be solved here. A node is entirely different from an RPC node but in functionality of providing resources to Dapps.


What is a node? A blockchain node is a program installed and set up on hardware which runs and stores the data of transactions, number of blocks on a network and many more(could be anything that can possibly requested for from the blockchain network). There are over 100 blockchain networks. These networks include: Ethereum, Solana, Polygon, Avalanche. Irrespective of the network, nodes exist to store these data and there are connected across to every other network to store these data making every network decentralized most importantly, these nodes interact via APIs not directly but through RPC nodes.



An RPC node is a node that implements the RPC protocol making it possible to receive RPC Calls from APIs, RPC requests, and read RPC methods and as well send information from the blockchain. A node can be a node without implementing the rules of an RPC protocol but since blockchain state is even and the same across, data stored across RPC nodes and ordinary nodes remain the same. These nodes may exists across networks as Solana Network has its own RPC nodes, Ethereum as well.



These nodes communicate with the APIs through the RPC requests sent from their endpoints. In this communication process, the following parameters are put into consideration:


  1. RPC and API Methods and;
  2. RPC endpoints and API endpoints

Parameters in Dapp-client communication in blockchain

RPC and API METHODS

Like HTTP methods, where short words are used to get resources or request a certain action from the server, these same methods exist but with different structures for RPCs. HTTP methods include: GET, POST, PUT, and DELETE where the following read data without modifying it, create resources, replace resources, or delete a resource.


These resources are pieces of data that points to the data a client is interacting with which is mostly represented as URL. This is different for RPC methods.


For example, in a traditional API-Client interaction, an example of a client (a mobile application) might want to get the data of a user with an ID: 224 (remember that some APIs store data in XML format, hence pattern of arrangement is the same). To read this data without modifying it, the GET method is used and can be represented in the form:


GET https://api.data.com/users/123


Let’s say: api.data.com is the resource of the user


But in the context of blockchain, let’s say an RPC reads from the request after mapping is done by the API which wants to count the number of transactions in an Ethereum block. This RPC relays the request to an Ethereum RPC node, the method is typically represented in the form:

method:"eth_getBlockTransactionCountByNumber"


In essence, RPCs execute specific data requests directed from the decentralized applications' APIs. In a typical communication between these two parameters, APIs are mostly used for resource manipulation, so let’s say an API sends a request to the RPC through the GET method to get the balance of an ETH account, this GET method is translated to a specific RPC method, which then communicates to the node in the format: ethgetbalance


An RPC method is important as its format is most understood by the RPC Nodes. Other RPC Methods may include: getNFTMetadata_v3, eth_getFilterLogs, getNFTSales



RPC Endpoints and API endpoints


Data or requests aren’t attended to at a go, when a request is made through a method call, there’s a cluster point where these requests are sent to. This cluster point is regarded as an endpoint on the network serves as a form of service which the RPC nodes interacts with to give you the exact data that was requested. These endpoints may be public, private, or alternative. Public endpoints are provided and developed by the blockchains but lack infrastructure maintenance, for a better Dapp experience, developers can be created to service for your Dapp alone and hence runs on your own request.


Most times. network congestion may occur as so many Dapps may be trying to request for blockchain’s data. This hassle gives rise to the inclusion of alternative Dapp where if either your private or public endpoint fails, an alternative endpoint can be used.

Alchemy provides endpoints for Ethereum and other chains like Polygon and Optimism. Check it out here: https://www.alchemy.com/chain-connect/chain/ethereum


For API endpoints, these endpoints are the clusters where the client sends its requests and the API picks up the data request from there, and sends it to the RPC where its final point on the RPC is its endpoint which then receives the request to access the blockchain’s data.


Here’s an example of API requests and the responses let’s say you want to count the number of transactions in an Ethereum block using dRPC’s API. You start by utilizing the eth_getBlockTransactionCountByHash and eth_getBlockTransactionCountByNumber methods.

Full dive using dRPC's API

1. Counting Transactions by Block Hash

The Request


To get the transaction count for a specific block by its hash, you can use the eth_getBlockTransactionCountByHash method.


Using cURL:



curl https://ethereum.drpc.io -X POST -H "Content-Type: application/json" -d '{ "jsonrpc":"2.0", "method":"eth_getBlockTransactionCountByHash", "params":["0x1234567890123456789012345678901234567890123456789012345678901234"], "id":1 }'


The response which you get:


{ "jsonrpc": "2.0", "id": 1, "result": "0x3" // Hexadecimal for 3 transactions }


2. Count Transactions by Block Number


Request


To retrieve the transaction count for a block using its block number, you can use the eth_getBlockTransactionCountByNumber method.





curl https://ethereum.drpc.io 
-X POST -H "Content-Type: application/json" 
-d '{ "jsonrpc":"2.0", "method":"eth_getBlockTransactionCountByNumber", "params":["0xA"], // Block number in hex (0xA = Block 10) "id":1 }'

Response

The response from dRPC's API will also be in JSON format.


An example response could look like this:


{ "jsonrpc": "2.0", "id": 1, "result": "0x5" // Hexadecimal for 5 transactions }



It is crucial to understand that in fetching data and making requests, two state of a blockchain can be attained. A blockchain can run in its Testnet mode, Devnet mode and also in its Mainnet mode and as well both states can exists for other reasons such as testing out transactions work, how transactions per second (TPS) is attained and many more.


In the process of setting up an RPC, an RPC URL is unique for the state of the blockchain which you want to query data from. These URLs connect the RPC to the Dapp and these RPC nodes can be provided by platforms regarded as node-as-a-service.

Examples of API and RPCF Providers

  • dRPCs
  • Alchemy
  • Infura
  • QuickNode


dRPC


DRPC is a web3 infrastructure that offers developers, and consumer applications third-party services and serving clients like Instadapp, SushiSwap, Lido, Curve, and 500+ other web3 protocols by providing the possibility of getting blockchain’s data. dRPC makes it possible as a developer to expand your model as your dapp users tend to increase and as database increases your pay to access their services increase.


As a developer, to access data and resources from the chain, dRPC provides a pipeline of APIs to the following networks: Ethereum, Optimism, Arbitrum, Solana, and Cosmos. Decentralized applications built on either of these blockchains can use the APIs provided by dRPC. To get full guide on how set these APIs, you can visit their docs.


Alchemy



Alchemy is regarded as the largest infrastructure platform that provides services to decentralized applications and tools as a whole which depends on blockchain’s data for full functionality. Alchemy provides RPCs for both Ethereum, Optimism, and Solana. Their API references cover Ethereum, Optimism, Polygon, Solana, Base, Arbitrum, Starknet, Linea, Fantom, OPBnB, etc. The list of various multiple blockchains makes it the largest. You can check out their docs on the different blockchains here and check their network


Infura



Infura is another API/node service provider which covers 16 chains including some which Alchemy provides. Difference in utilizing these platforms for choice of preference depends on the pricing model or if a certain API is much preferred.


Some APIs might follow a certain protocol like JSON format or another XML format as well. As a developer, checking all of these matters before opting to use a particular service. You can read more on Infura’s API here

Quicknode



Quicknode can be regarded as the second largest API providing service as its outreach covers over 20 blockchains. It mostly utilizes REST APIs for its interaction with RPC calls. Just like Alchemy, quicknode offers services for NFT APIs to get metadata across Ethereum and Solana NFTs.


These metadata can be similar to trace addresses in Ethereum transactions. It’s the unique properties of the different NFT collections. You can check out Quicknode’s docs to get started with using their products and REST APIs.

Helius



Helius as another infrastructure protocol offers API services and RPC node services only to the Solana Network, where a wide range of APIs can work it. With Helius, you can request token metadata, token balances and every other request any RPC node on another blockchain can give you.

Final Thoughts

From understanding what APIs, the types of API are then to understanding their relations with RPCs. Asides building your own RPC node for your own DApp uses which of course will cost resources, a certain API that you use has to be carefully considered before opting for the type of RPC service is necessary as some RPC node providers support JSON-RPC protocol while others XML-RPC protocol.


The protocols listed above aren’t the only protocols that provides infra services, others includ: Moralis, MongoDB, Chainstack, Ankr, etc. You can go through them and explore their pricing models and every other feature that you think will work better with your Dapp.