Skip to content

How to make Graphql request using fetch API?

Published: at 02:19 AM

Graphql is an open-source data query and mutating language for APIs.

It is best for requesting required data from the client-side alone and the updating of data is handled through mutation. But when we try to set up or try to add graphql to our project it becomes somewhat tedious. So in this post, I’ll explain how to make a Graphql request using fetch API.

How do Graphql request works?

Graphql works by setting an HTTP request to the graphql endpoint with some parameters.

The components of the Graphql request are the following,

How to use it with fetch?

Our query will be,

// This query request a array of photos.
query MyQuery {
  photos {
    id
    title
    image {
      ... on Asset {
        id
        url
      }
    }
  }
}

Our variables will be,

// For this request, we are not using any variables.⁠
{}

Our fetch query function will look like this,

const query = async (query, variables) => {
  const response = await fetch('https://api.spacex.land/graphql/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ query, variables }),
  })
  const json = await response.json()
  return json
}

This function accepts two parameters. The first one is the query of Graphl query or mutation and the second one is the variables that are used in the query.

So in our code, we can use this function to make Graphql queries and mutations.