Skip to main content

Working with Node.js

It's easy to call your API from within your Node.js application.

The first thing you'll want to do is create a .env file in your project that includes the secrets GRAPHQL_ENDPOINT and GRAPHQL_API_KEY:

.env
GRAPHQL_ENDPOINT=xxxxx
GRAPHQL_API_KEY=xxxxx

From your project's admin UI, you can find your API endpoint. Copy the endpoint into your .env file.

You can also create an API Key from within the API tab. Pick the dev permission for your key, then save it. After saving, you'll be presented with a one-time secret string. Copy it into your .env file.

Once you've got your secrets, install some libraries to help make your request:

npm i --save node-fetch dotenv

Now, querying your API is as simple as making an asynchronous network request:

example.client.js
// Use `dotenv` to load your environment variables
require('dotenv').config();
const fetch = require('node-fetch');

async function query(query, variables) {
// Every request to GraphQL uses the `POST` method
const res = await fetch(process.env.GRAPHQL_ENDPOINT, {
headers: {
Authorization: `Bearer ${process.env.GRAPHQL_API_KEY}`
},
method: 'POST',
body: JSON.stringify({query, variables})
});
return res.json();
}

// Write GraphQL queries as strings
const COUNTRY_QUERY = `
query Country($code: ID.) {
Countries_country(code: $code) {
name
emoji
currency
capital
}
}
`;

// Make the request, then log out the resolved data
// Here, we'll query for data about Japan using its country code, `JP`
query(COUNTRY_QUERY, {code: 'JP'}).then(data => console.log(data));

Run this file with node example.client.js and you'll see it return your data.

{
"data": {
"Countries_country": {"name": "Japan", "emoji": "🇯🇵", "currency": "JPY", "capital": "Tokyo"}
}
}