/

hasura-header-illustration

How to request a GraphQL API with Fetch or Axios

If you are new to GraphQL, all you need to understand is this - GraphQL is just a query language and popular implementations on the client and server leverage existing JSON standards for requests and responses over HTTP.

Now with that basic understanding, we can look at how to construct a GraphQL request in this post. If you have ever done any REST API calls from your frontend using fetch or axios in the past, this should be very quick to grok.

What constitutes a GraphQL request?

Lets start with the basics. Is a GraphQL request any different from a REST API request? Not really. At least with current server implementations that mostly deals with HTTP and JSON.

  • 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.

Lets now look at what the request body JSON looks like:

{
  "operationName": "",
  "query": ``,
  "variables": {}
}

The JSON body has 3 objects.

  • 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 the query part, you can make use of variables objects for anything dynamic.

Alright, lets look at an example for a basic GraphQL query:

query fetchAuthor {
  author {
    id
    name
  }
}

Now lets say the GraphQL server is hosted at https://sweeping-reindeer-45.hasura.app/v1/graphql and it has some Authorization token to access the server.

The GraphQL request for the above query in JavaScript Fetch will look like the following:

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); //

Sounds familiar? Yes! This is very similar to how you make REST API calls. The only part which you need to worry about is constructing the query object of the GraphQL Query.

Now let us look at the same example with Axios.

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

With axios, you don't need to stringify the JSON when you are passing the request body to the data key.

Handling Errors

Once the response is available, you can handle errors with the response object. If you find the errors object in the response, then you can parse that for errors.

If you are completely new to GraphQL, I would recommend you check out our open source tutorial on Introduction to GraphQL which goes over the core concepts through examples.

Blog
02 Nov, 2021
Email
Subscribe to stay up-to-date on all things Hasura. One newsletter, once a month.
Loading...
v3-pattern
Accelerate development and data access with radically reduced complexity.