# Getting data in the form of a CSV file from Bitquery GraphQL API using NodeJS

**URL:** <https://community.bitquery.io/t/getting-data-in-the-form-of-a-csv-file-from-bitquery-graphql-api-using-nodejs/259>\
**Category:** GraphQL Tutorials\
**Tags:** nodejs, closed\
**Created:** [June 30, 2021, 7:28am UTC](https://community.bitquery.io/t/getting-data-in-the-form-of-a-csv-file-from-bitquery-graphql-api-using-nodejs/259 "2021-06-30T07:28:28Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![sayon](https://avatars.discourse-cdn.com/v4/letter/s/b2d939/32.png) [@sayon](https://community.bitquery.io/u/sayon)\
**Post date:** [June 30, 2021, 7:28am UTC](https://community.bitquery.io/t/getting-data-in-the-form-of-a-csv-file-from-bitquery-graphql-api-using-nodejs/259/1 "2021-06-30T07:28:28Z")

</div>

**Getting data in the form of a CSV file from Bitquery GraphQL API using NodeJS**

> The data which we often get in return from Bitquery GraphQL API is in the form of a GraphQL query. However, we can even generate the GraphQL returned data in the form of a CSV file and JSON. In this article we will be discussing the basic idea of getting data in JSON format using NodeJS and then later converting the JSON formatted data into a CSV file.

**Initializing a NodeJS project**  
Install the following dependencies in the root folder of your NodeJS project

```auto
npm init

```

In the above code snippet, we have installed **node-fetch** and **fs** using the NPM (Node Package Manager). **Node-fetch** is used in order to use the fetch API functionalities within NodeJS environment and fs is used in order to make changes with filesystem within our NodeJS environment.

**Installing Dependencies**

```auto
npm install node-fetch fs

```

**Getting Started**

Inside the NodeJS project folder create an **index.js** file.

> _Importing Libraries_

The following NodeJS libraries must be imported into **index.js**

```auto
const FileSystem = require('fs')
const { writeFile } = require('fs').promises;
const fetch = require('node-fetch')

```

> _Making a POST request to Bitquery GraphQL API_

Before, we make the POST request to the GraphQL API, we need to setup the endpoints and declare our GraphQL query and both of them inside an asynchronous function called **generateCSV( )**.

```auto
// endpoint url
const url = "https://graphql.bitquery.io/"; 

// GraphQL query 
const query = `
{
  ethereum(network: ethereum) {
    dexTrades(
      date: {is:"2020-11-01"}
      exchangeName: {is: "Uniswap"}, 
      baseCurrency: {is: "0xdac17f958d2ee523a2206206994597c13d831ec7"}, 
      quoteCurrency: {is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"}) {
      baseCurrency {
        symbol
        address
      }
      baseAmount
      quoteCurrency {
        symbol
        address
      }
      quoteAmount

      trades: count
      quotePrice

      side

    }
  }
}
`;

```

After wrapping the two inside an asynchronous function, the code would look similar to this

```auto
async function generateCSV(){
	const query = `
	{
	  ethereum(network: ethereum) {
	    dexTrades(
	      date: {is:"2020-11-01"}
	      exchangeName: {is: "Uniswap"}, 
	      baseCurrency: {is: "0xdac17f958d2ee523a2206206994597c13d831ec7"}, 
	      quoteCurrency: {is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"}) {
	      baseCurrency {
	        symbol
	        address
	      }
	      baseAmount
	      quoteCurrency {
	        symbol
	        address
	      }
	      quoteAmount
	      
	      trades: count
	      quotePrice
	      
	      side
	  
	    }
	  }
	}
	`;
	const url = "https://graphql.bitquery.io/";
}

```

Now, we would be using the **fetch API** (using the node-fetch for NodeJS) to make the **POST request** to the Bitquery GraphQL API.

```auto
const opts = {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "X-API-KEY": "YOUR UNIQUE API KEY"
    },
    body: JSON.stringify({
        query
    })
};
const results = await fetch(url, opts).then(res => res.json())

```

In the above code, the fetch function requires two arguments; the endpoint of the API and the opts object which makes the POST request to the API specifying the unique API key of the user while doing so.

The result of the POST request to the GraphQL API is stored in the results variable.

> _Defining a function which would convert JSON formatted data into a CSV file format_

```auto
function convertJSONTOCSV(objArray){
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';
    for (var i = 0; i < array.length; i++) {
        var line = '';
        for (var index in array[i]) {
            if (line != '') {line += ','}
            line += array[i][index];
        }
        str += line + '\r\n';
    }
    return str;
}

```

The above function **convertJSONTOCSV** , moves through the JSON formatted result and returns a string variable which is of CSV format.

> _Defining a function which would create a CSV file and store the data passed onto it as an argument/parameter_

```auto
async function writeCSV (fileName, data) {
  try {
  	await writeFile(fileName, data, 'utf8'); 
  } catch (err) {
    console.log(err);
  }
}

```

In the above code snippet, **writeCSV** function has been declared which takes two arguments; name of the CSV file and the data. It then uses the **writeFile** component of the fs library to create a CSV file of the said name and store the data in it.

> _Completing the generateCSV( )_

We will first create a variable which would store the value of the array representing the JSON formatted data, returned from the Bitquery GraphQL API

```auto
const objectArray = results.data.ethereum.dexTrades

```

And then, JSON.stringify the same using the code shown below

```auto
const jsonObject = JSON.stringify(objectArray)

```

> _Calling the convertJSONTOCSV function along with the writeCSV function_

Right after the above code snippet, use the below code snippet to first, convert the JSON formatted data into CSV format and then inserting the values of the same into a CSV file.

```auto
const data = convertJSONTOCSV(jsonObject)
writeCSV('results.csv', data)

```

Alas, the function call and you are about done

```auto
generateCSV()

```

**Run the NodeJS application**

```auto
node index.js

```

A CSV file would be created in the root folder of your NodeJS project.

 ![Screenshot (137)](https://us1.discourse-cdn.com/flex016/uploads/bitquery/original/1X/1c374ce5a69c94153f332946bbd871541807c043.png)

> **Resources**  
> [Link to the Github Repository](https://github.com/sayon-bitquery/CSVfromBitqueryAPI)  
> [Link to all the gists](https://gist.github.com/sayon-bitquery)

---

<div class="post-metadata">

**Author:** ![sayon](https://avatars.discourse-cdn.com/v4/letter/s/b2d939/32.png) [@sayon](https://community.bitquery.io/u/sayon)\
**Post date:** [July 9, 2021, 7:04am UTC](https://community.bitquery.io/t/getting-data-in-the-form-of-a-csv-file-from-bitquery-graphql-api-using-nodejs/259/2 "2021-07-09T07:04:19Z")

</div>



---

<div class="post-metadata">

**Author:** ![sayon](https://avatars.discourse-cdn.com/v4/letter/s/b2d939/32.png) [@sayon](https://community.bitquery.io/u/sayon)\
**Post date:** [July 10, 2021, 7:19am UTC](https://community.bitquery.io/t/getting-data-in-the-form-of-a-csv-file-from-bitquery-graphql-api-using-nodejs/259/3 "2021-07-10T07:19:35Z")

</div>


