Calling a StepZen API in JavaScript Using Node.js

How to query your GraphQL API using JavaScript in Node.js

When connecting to StepZen via JavaScript, we recommend that you connect to StepZen via server-side code or via a serverless function so as to protect your API key from being exposed. The following examples will show various options for calling a StepZen API via server-side or serverless JavaScript.

Using Plain JavaScript

We can send queries via Node.js without any special libraries, leveraging the standard Node https library to form a POST request. Let's look at a simple example that uses a .env to store the API key. A .env file is useful for when you need to store protected keys (be sure it is added to your .gitignore so as not to check it into your source control).

(NOTE: The endpoint URL listed here does not exist and is for example purposes only. To test, replace path with the path to an API you've deployed to StepZen.)

const https = require('https');
require('dotenv').config();

const data = JSON.stringify({
  query: `{
    myQuery {
      id
      name
    }
  }`,
});

const options = {
  hostname: '[ACCOUNT_NAME].stepzen.net',
  path: '/api/example/__graphql',
  port: 443,
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length,
    Authorization: 'Apikey ' + process.env.STEPZEN_API_KEY,
    'User-Agent': 'Node',
  },
};

const req = https.request(options, (res) => {
  let data = '';
  console.log(`statusCode: ${res.statusCode}`);

  res.on('data', (d) => {
    data += d;
  });
  res.on('end', () => {
    console.log(JSON.parse(data).data);
  });
});

req.on('error', (error) => {
  console.error(error);
});

req.write(data);
req.end();

For a more detailed walkthrough, check this blog post.

In addition, you may want to use one of the many GraphQL client libraries to connect to your StepZen API. In Exploring JavaScript Client Libraries for GraphQL, we explore how to use several popular libraries and show how to connect to StepZen using them.

GraphQL Request

GraphQL Request is a library created and maintained by Prisma Labs. It is intentionally designed to be the "minimal", meaning it doesn't include a lot of extra functionality that you'll find in some of the other clients. It gives you only what you need to easily send and receive GraphQL queries and mutations in the browser or in Node and intentionally little more. This does make GraphQL Request very lightweight and perhaps all you need in many cases.

Let's look how you can use GraphQL Request to call a StepZen API. First, you need to do is npm install and then import graphql-request into your project:

import { request, gql } from 'graphql-request';

You'll need to pass authorization headers to the GraphQL API by instantiating the GraphQLClient with the endpoint URL and header variables. Once this is done, you can call the request() method on that client.

const graphQLClient = new GraphQLClient('https://account-name.stepzen.net/folder-name/api-name/__graphql', {
headers: {
    authorization: 'Apikey ' + process.env.STEPZEN_API_KEY,
},
});
const query = gql`
{
  myQuery {
    id
    name
  }
}
`;
const results = await graphQLClient.request(query);

Apollo Client

Apollo Client is created by Apollo and includes all of the basics like querying, mutations, variables and more, but also doubles as a state management library. You can use Apollo Client to manage local state irrespective of whether you have a GraphQL API to connect to or not. It also offers the ability to cache the state that you retrieve from the remote API and combine that with additional local application state. All of this is built with React in mind, so, while you don't have to use React, Apollo Client integrates easily with it.

Once you have npm installed Apollo Client, you'll need to import three modules in order to make a basic query.

import { gql, ApolloClient, InMemoryCache } from '@apollo/client';

The InMemoryCache allows you to configure and control Apollo Client's caching strategies. This is particularly useful if you are pulling data on the client. Apollo Client will use the cache wherever it finds that a query has not changed, meaning you will be able to serve responses much faster than re-retrieving results over the network.

const client = new ApolloClient({
  uri: 'https://account-name.stepzen.net/folder-name/api-name/__graphql',
  cache: new InMemoryCache(),
  headers: {
    authorization: 'Apikey ' + process.env.STEPZEN_API_KEY,
  },
});
const results = await client.query({
  query: gql`
    {
      continents {
        name
        code
      }
    }
  `,
});

Apollo Client also allows for a lot of fine-grained control over the HTTP calls you make using Apollo Link, including adding authorization via a Context Link.

To get the full scope of capabilities of Apollo Client, check out the Apollo Client documentation.

Urql

Urql has more features and capabilities than GraphQL Request but fewer than Apollo Client, making it much more lightweight. For example, it does include a highly-configurable caching layer similar to Apollo Client, but it does not include local state management. It also has integrations for the React, Svelte and Vue frameworks built-in (there's also a package for Next.js). If you're looking for a feature-by-feature comparison with Apollo Client, they have one here.

First, we need to import the proper modules.

import { createClient } from 'urql';

Next, we create the client and the query and then pass that to the client's query() method.

const client = createClient({
  url: 'https://account-name.stepzen.net/folder-name/api-name/__graphql',
  fetchOptions: {
    headers: { authorization: 'Apikey ' + process.env.STEPZEN_API_KEY },
  },
});
const query = `
  {
    continents {
      name
      code
    }
  }
`;
const results = await client.query(query).toPromise();

You'll note that because we are using async/await, we need to convert the stream that query returns into a JavaScript promise.

To learn more check the Urql documentation.

This site uses cookies: By using this website, you consent to our use of cookies in accordance with our Website Terms of Use and Cookie Policy.