Making Requests to a GraphQL API

Interfacing with a GraphQL API can be done with dedicated libraries, or with custom helper functions you create. We will only be covering the custom method here.


This tutorial is based on the previous three tutorials in this series, all examples here will be based on the last GraphQL server we made.


GraphQL is a POST-based API that takes a JSON object as the request's body with your query inside. The best way to make this request is to use the fetch API. Here is the function I use to make requests

 1function graph(request) {
 2  return new Promise((resolve, reject) => {
 3    fetch("/graphql", {
 4      method: "POST",
 5      headers: {
 6        "Content-Type": "application/json",
 7        Accept: "application/json",
 8      },
 9      body: JSON.stringify({ query: request[0] }),
10    })
11      .then((r) => r.json())
12      .then((e) => resolve(
13      .catch(reject);
14  });

This function takes the query as the request parameter the returns a Promise that makes a fetch request with the payload. This function is hard coded with the API route built-in, if you are not using /graphql as the API endpoint then change it to what you are using.


2    all {
3        title
4    }

Here we are using a tagged template to pass the query to the graph function. This function is asynchronous, so we handle the returned value just like you normally would with a Promise. If you are not calling this function from the top level, you can use the async/await syntax like below.

1let data = await graph`{
2    all {
3        title
4    }