There is a system called EVM (Ethereum Virtual Machine) which holds the state of the Ethereum network. If any participant request computation then other participants will verify and validate the request and if the request validates then it causes the state change in EVM and will propagate through the entire network. This request is called the transaction. Ether is the cryptocurrency of the market for computation, which will be provided to the participants as market incentives for verifying and executing it.
Prerequisites to create an API to interact with Ethereum
- Infura Account
- Very basic understanding of Blockchain
- Understanding of Node JS and Javascript
- NodeJS installed on your System
Steps to create an API
- Create Infura account
Users will need to create the Infura account to interact with the mainnet or testnet node of Ethereum Blockchain. It will provide the Socket URL to interact with the Ethereum network. It will provide the API key which will be integrated into later steps.
- Install Dependencies
Before starting the development of API users will need to install some dependencies for the project. Like web3, nodemon, etc. and initialize the node project.
npm init -y
npm install web3
npm install nodemon --save
- Create the API
The first step will require all the modules which are getting used in the project.
const web3 = require('web3');
const express = require('express');
const Tx = require('ethereumjs-tx');
Secondly, we will initiate our app and integrate the infura socket URL to interact with the Ethereum testnet.
const app = express();
web3js = new web3(new web3.providers.HttpProvider("https://rinkeby.infura.io/YOUR_API_KEY"));
Then we will set the route for our API to fetch the balance for the API.
app.get('/getBalance',function(req,res){
//contract abi is the array that you can get from the ethereum wallet or etherscan
var contractABI =YOUR_CONTRACT_ABI;
var contractAddress ="YOUR_CONTRACT_ADDRESS";
web3js.eth.getBalance("YOUR ACCOUNT ADDRESS", function(err, result) {
if (err) {
console.log(err)
res.status(400).send({success:false,Erroe:err})
} else {
let balance = web3js.utils.fromWei(result, "ether")
res.status(200).send({success:true,Balance:balance})
}
})
})
We use the getBalance function to fetch the ether balance of the ethereum address. We pass the address as the parameter and send an error in response if an error occurs or send a success response as the Balance of the address. web3js.utils.fromWei makes the output of the function in a human-readable form.
Conclusion
This blog will help you create an API to interact with Ethereum Blockchain.