Skip to content

How to call a GraphQL API with JavaScript?

Once we have a working server with a GraphQL API, we need a way to access this information from our application. Next, I will show you different ways to query a GraphQL API using JavaScript.

We will be using backticks, that is (` `) instead of (" ") or (' ') for strings since they allow us to place multi-line strings in JavaScript.

Axios

Axios is a library to make ajax queries. It is popular for its simplicity and its use based on Promises in addition to having support for async and await.

javascript
// query for people aged 18
axios({
  url: 'http://localhost:4000/graphql',
  method: 'POST',
  data: {
    query: `
      query {
        people(age: 18) {
          id
          name
          surname
          age
          hobbies
        }
      }
    `,
  },
})
  .then((res) => console.log(res.data))
  .catch((err) => console.log(err));

Fetch

Fetch is a native JavaScript function for making ajax queries, however, it does not have support in older browsers.

javascript
fetch('http://localhost:4000/graphql', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    query: `
    query {
      person(id: 1) {
        id
        name
        surname
        hobbies
      }
    }
  `,
  }),
})
  .then((res) => res.json())
  .then((res) => console.log(res));

XMLHttpRequest

Like fetch, XMLHttpRequest is a native JavaScript function, except that, unlike fetch, it has much better support for older browsers.

javascript
let query = {
  query: `
    query {
      person(id: 1) {
        id
        name
        surname
        hobbies
      }
    }`,
};

let xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open('POST', 'http://localhost:4000/graphql');
xhr.setRequestHeader('Content-Type', 'application/json');

xhr.onload = function () {
  console.log(xhr.response);
};

xhr.send(JSON.stringify(query));

Miscellaneous

We can create functions around these query methods that allow us to shorten code and prevent us from repeating the same thing over and over again. I will show an example with axios.

javascript
// wrapper to query a graphql api with axios
function gql(query) {
  return new Promise((resolve, reject) => {
    axios({
      url: 'http://localhost:4000/graphql',
      method: 'POST',
      data: { query },
    })
      .then((res) => resolve(res.data['data']))
      .catch((err) => reject(err));
  });
}

Then we could use this function in the following way

javascript
gql(`
  query {
    person(id: 1) {
      id
      name
      surname
      hobbies
    }
  }
`)
  .then((data) => console.log(data))
  .catch((err) => console.log(err));

This way, we can consume our API with the method of our preference.

I hope this guide is helpful. Greetings!