SyntaxStudy
Sign Up
JavaScript Intermediate 4 min read

Fetching GraphQL APIs

Fetch + GraphQL

GraphQL APIs accept POST requests with a JSON body containing a query string and optional variables.

Example
async function gql(query, variables = {}) {
  const res = await fetch("/graphql", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ query, variables }),
  });
  const { data, errors } = await res.json();
  if (errors) throw new Error(errors[0].message);
  return data;
}
const { user } = await gql(`query($id:ID!){user(id:$id){name email}}`, { id: "1" });
Pro Tip

GraphQL always returns 200 OK — check the errors array in the response body, not the status code.