Published on

How to use Axios or any HTTP client with GraphQL API

Authors

At the end of the day GraphQL is just an API end point in which we send the API request in a structured format and we the response accordingly.

So we can use any HTTP client like axios to consume the API. In this blog post let’s see how to use GraphQL with Axios.

Dependency

# Installing axios http client
npm install axios

Fetching Data

const axios = require('axios');
 
const query = `
query {
    hn{
      topStories{
        title
        url
      }
    }
  }
`;
 
const url = 'https://www.graphqlhub.com/graphql';
 
const body = {
    query: query
};
 
const config = {
    headers: {
        'Content-Type': 'application/json'
    }
};
axios.default
    .post(url, body, config)
    .then(res => console.log(JSON.stringify(res.data, null, 2)))
    .catch(err => console.log(err.message));