StepZen is now part of IBM. For the most recent product information and updates go to
https://www.ibm.com/products/stepzen

Consume a GraphQL API Using Node

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 show options for calling a StepZen API via server-side or serverless JavaScript:

Plain JavaScript

You can send queries via Node.js without any special libraries, leveraging the standard Node HTTPS library to form a POST request.

The example below uses a .env file to store the API key. A .env file is useful when you need to store protected keys. Ensure it is added to your .gitignore file so that it does not become committed to your source control repository.

Note: The endpoint URL used in the example code below is for demonstration purposes only, and does not actually exist. To test this example, configure the path parameter with the path to the API that you've deployed to StepZen.

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

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

const options = {
  hostname: '{ACCOUNT}.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 walk through, see this blog post.

You may want to use one of the many GraphQL client libraries to connect to your StepZen API. Exploring JavaScript Client Libraries for GraphQL shows how to connect to StepZen using several popular libraries.

GraphQL Request

GraphQL Request is a library created and maintained by Prisma Labs. It's a lightweight, minimal library that provides only what you need to send and receive GraphQL queries and mutations in the browser or via Node.js.

Follow the steps below to call a StepZen API using GraphQL Request:

  1. Invoke npm install and import graphql-request into your project:

    import { request, gql, GraphQLClient } from 'graphql-request';
  2. Instantiate the GraphQLClient with the endpoint URL and headers by passing them to the GraphQL API. After this is complete, call the request() method on that client to invoke a query:

    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 library created by Apollo that includes functionality for querying, mutations, variables, etc., and also doubles as a state management library. You can use Apollo Client to manage local state irrespective of whether or not you have a GraphQL API to connect. It can also cache the state retrieved from the remote API and combine that with additional local application state.

While not required, Apollo Client integrates easily with React.

Follow the steps below to use Apollo Client:

  1. Ensure you have installed Apollo Client using npm.

  2. Import the modules: gql, ApolloClient, and InMemoryCache; these are required to perform a basic query:

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

InMemoryCache enables you to configure and control Apollo Client's caching strategies which are useful for pulling data on the client. Apollo Client will use the cache whenever it finds that a query hasn't changed, enabling you to serve responses much faster than re-retrieving results over the network.

The following example shows how to instantiate an ApolloClient object and run a query with it:

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 provides fine-grained control over the HTTP calls you make using Apollo Link, including adding authorization via a Context Link.

See the Apollo Client documentation to learn more about the full scope of capabilities of Apollo Client.

Urql

Urql has more features and capabilities than GraphQL Request but fewer than Apollo Client, making it much more lightweight. For example, it includes a highly-configurable caching layer similar to Apollo Client, but doesn't include local state management. It also has built-in integrations for the React, Svelte, and Vue frameworks, as well as a package for Next.js. See here for a feature-by-feature comparison with Apollo Client.

Follow the steps below to use Urql:

  1. Import the proper modules:

    import { createClient } from 'urql';
  2. 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();

    Note: Since the example uses await, the stream returned by the query is converted into a JavaScript Promise.

See the Urql documentation to learn more.