How to use Bitquery APIs with NodeJS

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.

Screenshot (188)

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.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- Bitquery Logo -->
    <link rel="icon" href="https://test.bitquery.io/wp-content/uploads/2020/08/favicon.png" />
    <link rel="apple-touch-icon" href="https://test.bitquery.io/wp-content/uploads/2020/08/favicon.png" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NodeJS with Bitquery API</title>
    <script src="../index.js"></script> 
</head>
<body>
	<style>
		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' ;
		}
	</style>
	<header>
		<h1>Using Bitquery GraphQL API with NodeJS</h1>
	</header>
	<h2>The count of all the blocks in the Bitcoin DEX is <%= result %></h2>
</body>
</html>

Notice

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

the <h2> 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