StepZen is now part of IBM. For the most recent product information and updates visit our
IBM product page.

Making GraphQL Queries with Fetch

How to query a GraphQL API using JavaScript's Fetch API

You can query a GraphQL API using JavaScript's built-in fetch API, without any libraries or dependencies.

What is the Fetch API?

The Fetch API provides an interface for fetching resources (including those across the network). Fetch provides a generic definition of Request and Response objects (and other things involved with network requests).

Fetch is a client-side API attached to the window and thus not available directly within Node.js. However you can use libraries like Node Fetch to bring the Fetch API into Node.js server-side code.

Note: While technically possible, it's not recommended that you directly call any GraphQL API from the client where you need to pass an API key, as that will expose the API key to the client. This includes StepZen GraphQL API calls, which require your API key for security.

If you need to make a call to a StepZen API, it is highly recommended that you do so on the server-side or via a serverless function to protect your API key.

Query a GraphQL API Using Fetch

The fetch() method has only one mandatory argument, the path to the resource to fetch. The following example shows how to call the public Rick and Morty API using fetch():

fetch('https://rickandmortyapi.com/graphql')

This returns a Promise that resolves to the Response for that request. This happens as soon as the server responds with headers, even if the server response is an HTTP error status.

Init Options Object

You can optionally pass in an init options object as the second argument (e.g., to pass the HTTP request method and headers).

HTTP Request Methods

In most cases, GraphQL queries are performed as a POST request:

fetch('https://rickandmortyapi.com/graphql', {
  method: 'POST',
})

Headers

HTTP headers let the client and the server pass additional information with an HTTP request or response. An HTTP header consists of its case-insensitive name followed by a colon (:) and its value.

For example, the type of the body of the request is indicated by the Content-Type header. The Content-Type for GraphQL requests is application/json:

fetch('https://rickandmortyapi.com/graphql', {
  method: 'POST',

  headers: {
    "Content-Type": "application/json"
  },
})

Note: You can send API keys via the Authorization header, but this is not recommended because your keys are then exposed to anyone who can view that header.

Body

The Body mixin of the Fetch API represents the body of the response/request. It enables you to declare its content type and how it should be handled.

The example below includes the characters query in the body and stringifies it:

fetch('https://rickandmortyapi.com/graphql', {
  method: 'POST',

  headers: {
    "Content-Type": "application/json"
  },

  body: JSON.stringify({
    query: `{
      characters {
        results {
          name
        }
      }
    }`
  })
})

Accessing the Query Results

Since a Fetch API call results in a JavaScript Promise, you must use then() or await to handle the asynchronous results.

This example shows the use of then():

fetch('https://rickandmortyapi.com/graphql', {
  method: 'POST',

  headers: {
    "Content-Type": "application/json"
  },

  body: JSON.stringify({
    query: `{
      characters {
        results {
          name
        }
      }
    }`
  })
})
.then(res => res.json())
.then(res => console.log(res.data.characters.results))

You can achieve the same result using JavaScript's await to wait for the promise to resolve:

async function getCharacters() {
  let results = await fetch('https://rickandmortyapi.com/graphql', {
    method: 'POST',

    headers: {
      "Content-Type": "application/json"
    },

    body: JSON.stringify({
      query: `{
        characters {
          results {
            name
          }
        }
      }`
    })
  })
  let characters = await results.json();
  console.log(characters.data)
}

getCharacters()