How to request a GraphQL API with Axios using query and mutation in React

surbhi soni
2 min readNov 14, 2022

--

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data.

GRAPHQL is an alternative to REST and popular implementations on the client and server leverage existing JSON standards for requests and responses over HTTP.

we will look at constructing a GraphQL request in this post with a working example.

Is a GraphQL request any different from a REST API request?

Not really. At least with current server implementations that mainly deal with HTTP and JSON.

  • GraphQL Endpoint — There is only one endpoint for a GraphQL server.
  • Headers — Authorization headers if any will be applicable here.
  • Request Body — This is where you will be sending a JSON body to the GraphQL server. Most server implementations use JSON for requests/responses.

The query or mutation can be passed as an object, This is a string that contains the GraphQL syntax

Here’s a query you can use to get started. Paste this into the Operations window and click the button to run the query.

query fetchAllBuildingInfo{
Buildings{
name,
id,
}
}

GraphQL API Request with Axios

import axios from "axios";

const endPoint = "https://smart-meeting.herokuapp.com/graphql";
const token = "g56789thyuhihj6576";
const headers = {
"Content-Type": "application/json",
token: token,
Host: "https://codesandbox.io" // Host header to identify domain, most likely without header request will throw 400 error
};

const AllBuildingQuery = `{
Buildings{
name,
id
}
}`; // graphQl Query

const graphqlQuery = {
operationName: "fetchAllBuildingInfo",
query: `query fetchAllBuildingInfo ${AllBuildingQuery}`,
variables: {}
};

export const fetchAllBuildingInfo = () => {
const response = axios({
url: endPoint,
method: "post",
data: graphqlQuery,
headers: headers
});
return response;
};

fetchAllBuildingInfo()
.then((res) => console.log("response", res.data)) // will return data object
.catch((err) => console.log("err", err)) // err while fetching details

By Axios, you can get HTTP results with promises without the stringified body.

Happy Coding …..

--

--