How to request a GraphQL API with Fetch or Axios
What constitutes a GraphQL request?
- GraphQL Endpoint - There is only one endpoint for a GraphQL server.
- Headers - The relevant 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 request / responses.
{
"operationName": "",
"query": ``,
"variables": {}
}
operationName
: This is an optional string and can be used to denote the name of the GraphQL operation being performed. This will be useful for logging and debugging later.query
: This is the actual GraphQL query. The query language syntax that we speak of about GraphQL comes in here. This is a string which contains the GraphQL syntax. It can be enclosed in backticks (`) since the query is usually multi-line.variables
: This is an optional object and should only be used if a variable is being used within a query. Think of it as passing an argument to a function. The values will be substituted directly. It is hard to construct a string with dynamic values and hence while making thequery
part, you can make use of variables objects for anything dynamic.
query fetchAuthor {
author {
id
name
}
}
GraphQL Example Request using Fetch
const endpoint = "https://sweeping-reindeer-45.hasura.app/v1/graphql";
const headers = {
"content-type": "application/json",
"Authorization": "<token>"
};
const graphqlQuery = {
"operationName": "fetchAuthor",
"query": `query fetchAuthor { author { id name } }`,
"variables": {}
};
const options = {
"method": "POST",
"headers": headers,
"body": JSON.stringify(graphqlQuery)
};
const response = await fetch(endpoint, options);
const data = await response.json();
console.log(data.data); // data
console.log(data.errors); //
GraphQL API Request with Axios
const axios = require("axios");
const endpoint = "https://sweeping-reindeer-45.hasura.app/v1/graphql";
const headers = {
"content-type": "application/json",
"Authorization": "<token>"
};
const graphqlQuery = {
"operationName": "fetchAuthor",
"query": `query fetchAuthor { author { id name } }`,
"variables": {}
};
const response = axios({
url: endpoint,
method: 'post',
headers: headers,
data: graphqlQuery
});
console.log(response.data); // data
console.log(response.errors); // errors if any
Handling Errors
Related reading