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.
Prerequisite
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.
Requests
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(e.data))
13 .catch(reject);
14 });
15}
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.
Usage
1graph`{
2 all {
3 title
4 }
5}`.then(console.log);
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 }
5}`;
6console.log(data);