tags

How to request a GraphQL API with Fetch or Axios

02 November, 2021 | 2 min read

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.

Close

Get Started with GraphQL Now

Hasura Cloud gives you a fully managed, production ready GraphQL API as a service to help you build modern apps faster.

Praveen Durairaju

Praveen Durairaju

Application Engineer. Tech Enthusiast. Follow on Twitter - https://twitter.com/@praveenweb

Read More

Ready to get started?
Start for free on Hasura Cloud or you could contact our sales team for a detailed walk-through on how Hasura may benefit your business.
Get monthly product updates
Sign up for full access to our community highlights, new features, and occasional baby animal gifs! Oh, and we have a strict no-spam rule. ✌️