How to use Bitquery APIs with NodeJS

sayon
Wed, 28 Jul 2021 07:52:26 +0000
GraphQL Tutorials

NodeJS is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser. NodeJS or Node.js is extensively used in order to make scalable and dynamic web applications.

ExpressJS, is one of the most popular microservice framework for NodeJS web applications.

However, connecting Bitquery’s GraphQL API with a NodeJS web application is not a big deal. In this tutorial, we will connect a simple NodeJS web app and query the total counts of all the blocks in the Bitcoin DEX using Bitquery GraphQL API.

Sign up to Bitquery.io

If you are new to Bitquery’s interface, go to GraphQL IDE.

From here, sign up with your credentials. You might get a confirmation email on your registered email address.

After you are signed up, you would be redirected to GraphQL IDE from where you can get your unique API key.

Initializing your NodeJS web application

Using the following command in the terminal, you can initialize a NodeJS web application considering the fact that you already have npm installed in your system.

npm init

Go through the setup process via the command line and when done, you’ll notice a package.json file appearing in the root directory of your project.

Installing Dependencies

For our simple NodeJS web application, we have used EJS as the main templating library in order to display dynamic content on our web pages of our application.

npm install ejs

Also, in order to use the fetch API method in our Node.js application, to make calls to Bitquery APIs, we need to install node-fetch module as well.

npm install node-fetch

Alas, in order to use ExpressJS, we need to install it too via npm.

npm install express

Getting Started with EJS (optional)

If you are familiar with the EJS templating library requirements, then you can skip to the next part. But if you are not then, you would need to create a folder with the name ‘views’ in the root folder of your NodeJS project.
This is where all your templates would be kept and the file format would be .ejs. For example, index.ejs instead of index.html.

Importing Libraries & View Engine Setup

First, in the index.js file we’ll import all the necessary libraries and initialize the ‘EJS’ as the view engine.

const express = require('express')
const fetch = require('node-fetch')
const app = express()
app.set('view engine', 'ejs')

We will be using express as the main library for running servers. In the above code, we have used app.set('view engine', 'ejs') in order to initialize “EJS” as the view engine.

Declaring the Bitquery API endpoint and the GraphQL query

https://graphql.bitquery.io/ is the Bitquery API endpoint. In the index.js file, below the imported libraries, declare the API endpoint and the GraphQL query as shown below.

const endpoint = "https://graphql.bitquery.io/"
const query = `
{
	bitcoin{
    	blocks{
      		count
    	}
   	}
}`

Making the API call

In this tutorial, we have created a function named BitqueryAPICall which uses the fetch method to make the API call. The function definition is shown below.

let countValue = 0
function BitqueryAPICall(){
	const data =  fetch(endpoint, {
	    method: "POST",
	    headers: {
	    	"Content-Type": "application/json",
	      	"X-API-KEY": "BQYUGuoO6tZKM20I0lfBNCTEC4ouBCT1"
	    },
	    body: JSON.stringify({
	        query
	    })
	}).then(res => res.json()).then(data => {
		countValue = data.data.bitcoin.blocks[0].count
		console.log(countValue)
	})

}

After that, we will save the value returned by the function in a variable called countValue as the value returned is the count of the blocks in the Bitcoin DEX.

Sending the countValue to the template and running the NodeJS server

app.get('/', (req, res)=>{
	console.log(countValue+" is the returned value!")
	res.render('home', {result: countValue})
})

const PORT = 3000 || process.env.PORT

app.listen(PORT, ()=>{console.log(`Server starting in port ${PORT}. `)})

In the above code snippet, countValue gets referenced under the alias result in the template (home.ejs) which would load when the server runs in the port 3000.

views/home.ejs

The below is the home template which would load when the NodeJS server starts running.










NodeJS with Bitquery API




		header{
			background-color: mediumslateblue;
			color: white;
			font-family: 'Lucida Sans';
			text-align: center;
			margin: 5px;
		}
		body {
			background: linear-gradient(to bottom right, #DBFBF3, #F5FEFC)
		}
		h2{
			text-align: center;
			margin: 10px;
			padding: 10px;
			font-family: 'Lucida Sans' ;
		}


Using Bitquery GraphQL API with NodeJS

The count of all the blocks in the Bitcoin DEX is <%= result %>



Notice

The count of all the blocks in the Bitcoin DEX is <%= result %>

the tag is formatted in such a way that the aliased variable result would show the data returned by the query.

Run the NodeJS application

node index

Github Repository

https://github.com/sayon-bitquery/bitquery-nodejs

1 post - 1 participant

Read full topic