Fetching GraphQL Data Using Fetch API

Let’s look at how we can fetch the GraphQL data using the fetch API.

Step 1: Creating GraphQL Query

In this step, we will create the GraphQL query to fetch only the specified pokemon data from the server, and we will keep the limit as 10, and offset as 0.

Javascript




const graphqlEndpoint = 'https://graphql-pokeapi.graphcdn.app/';
  
const graphqlQuery = `
  query getPokemons {
    pokemons(limit: 10, offset: 0) {
      count
      next
      previous
      status
      message
      results {
        id
        name
        image
      }
    }
  }
`;


Step 2: Defining fetch options, changing the HTTP verb to POST, and passing the GraphQL query in the request body.

In this step, we will create the fetchOptions object and assign the method to be POST, headers as Content=Type of application/json, and in the body we will pass the graphQL Query

Javascript




const fetchOptions = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ query: graphqlQuery }),
};


Step 3: Hitting the Query using the Fetch API

In this step, we will hit the query endpoint using the fetch API and log the data into the console. The whole code should look like below

Javascript




const graphqlEndpoint = 'https://graphql-pokeapi.graphcdn.app/';
  
const graphqlQuery = `
  query getPokemons {
    pokemons(limit: 10, offset: 0) {
      count
      next
      previous
      status
      message
      results {
        id
        name
        image
      }
    }
  }
`;
  
const fetchOptions = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ query: graphqlQuery }),
};
  
fetch(graphqlEndpoint, fetchOptions)
  .then(response => response.json())
  .then(data => {
    console.log('GraphQL Data:', data);
  })
  .catch(error => {
    console.error('Error:', error);
  });


Output:

The output for the above code will look like below

Data Fetching with GraphQL

GraphQL is an open-source technology that allows us to query only the data that we require, unlike the traditional REST architecture which returns us the entire resources and data with specific endpoints configured for the same. Using GraphQL, we specify using the query the data that we want, and it returns the specified data in the specified format. It helps reduce the amount of data transfer over the network and saves network bandwidth.

This article will teach us how to fetch data using GraphQL, with React as our front-end UI library.

Similar Reads

Fetching GraphQL Data with React as a UI Library

Step 1: Create an open-source application...

Fetching GraphQL Data Using Fetch API

...

Fetching Data with GraphiQL

...

Conclusion

...

Contact Us