Making GraphQL Queries with Fetch

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

It is possible to query a GraphQL API using JavaScript's built-in fetch API, without any libraries or dependencies.

It is important to keep in mind that, while it is technically possible, you do not want to directly call any GraphQL API from the client in any scenario where you need to pass an API key as that will expose the API key to the client. This includes making 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.

What is the Fetch API?

The Fetch API provides an interface for fetching resources (including 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.

Query a GraphQL API Using Fetch

The fetch() method has only one mandatory argument, the path to the resource you want to fetch. In the following example, we are calling the public Rick and Morty API.

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

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

Init Options Object

You can also optionally pass in an init options object as the second argument. Some typical options passed are 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 (:), then by 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 that you can send API keys via the Authorization header, but it is highly recommended that you do not do this as your keys are thereby exposed to anyone who uses your

Body

The Body mixin of the Fetch API represents the body of the response/request. It allows you to declare what its content type is and how it should be handled. We will include the characters query in the body and stringify 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 the results of a Fetch API call is a JavaScript Promise, you'll need to using either then() to handle the asynchronous results.

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 could 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()

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.