Calling GraphQL with fetch

Beginner · 7 min

A GraphQL request is one HTTP POST with a JSON body. Send queries and variables with plain fetch, read the errors array, and see what a client adds.

Before thisGraphQL over HTTPVariables and operation names

dcode · 7 min

Calling GraphQL with fetch

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by dcodeReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A GraphQL call is a POST to a single URL with a JSON body holding query, variables and optionally operationName.
  • Variables travel next to the query string, never interpolated into it.
  • A GraphQL server usually answers 200 even when the operation failed, so check the errors array as well as response.ok.
  • A client library is optional; it earns its place with caching, deduplication and typed hooks, not with the transport itself.

The transport is boring on purpose

By now you have sent queries from GraphiQL, which hides the wire. Underneath, a GraphQL client does almost nothing exotic. It takes a document, a few variables, and POSTs them as JSON to one endpoint. The server returns JSON. Everything else a client library offers is built on top of that exchange, so it is worth doing it once by hand before reaching for one.

The shape is the one described in GraphQL over HTTP:

{
  "query": "query Book($id: ID!) { book(id: $id) { id title } }",
  "variables": { "id": "1" },
  "operationName": "Book"
}

query is required. variables and operationName are optional, and operationName only matters when the document holds several operations.

A small helper

This is the whole client, in about fifteen lines of browser or Node code:

async function gql(query, variables = {}, signal) {
  const response = await fetch("http://localhost:4000/graphql", {
    method: "POST",
    headers: { "content-type": "application/json", accept: "application/json" },
    body: JSON.stringify({ query, variables }),
    signal,
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  const { data, errors } = await response.json();
  if (errors?.length) throw Object.assign(new Error(errors[0].message), { errors, data });
  return data;
}

const data = await gql(
  `query Book($id: ID!) { book(id: $id) { id title author { name } } }`,
  { id: "1" },
);

Two details deserve attention. The query string is a constant and the id goes in variables. If you glue the id into the string with a template literal, you have rebuilt the injection problem that parameterised SQL exists to prevent, and you have also made every request a different document, which hurts any cache keyed on the query text.

The second detail is the error check. I ran this helper against a local GraphQL Yoga server (graphql-yoga 6.1.0, graphql 16.15.0). A resolver that threw came back as HTTP 200 with {"data":null,"errors":[...]}. So did a query for a field that does not exist, because the helper sends accept: application/json; a client that asks for application/graphql-response+json opts into the stricter status codes from the GraphQL over HTTP spec instead. Either way, response.ok tells you the server spoke and errors tells you whether the operation worked. A field with a partial failure can return both data and errors, which is why the helper attaches data to the thrown error instead of discarding it. Note also that Yoga masked the resolver’s message as “Unexpected error.” by default; production servers hide internals on purpose. Errors and partial responses covers what a caller should do with all of this.

GET for queries, POST for everything else

Servers also accept queries over GET, with query and variables in the URL. Mutations must not be sent that way, and Yoga enforces it: a mutation over GET returned 405 with “Can only perform a mutation operation from a POST request.” GET matters because browsers and CDNs cache GET responses, which is the hook that persisted queries and caching GraphQL build on. For a first client, POST is the default and the safe choice.

Cancellation and headers

fetch gives you two things worth wiring up straight away. An AbortSignal cancels a request that is no longer needed, such as a search box that fired for every keystroke. And headers carry credentials: put the token in authorization and the server reads it into the context, the pattern the authentication lesson relies on.

What a library adds

Having written the helper, you can see what it does not do. It does not remember that you already asked for book(id: "1"), so every component that wants the book makes its own request. It does not know that a mutation just changed that book. It does not turn the response into a type. It does not retry, deduplicate in-flight identical requests, or batch.

That list is the job description of a client. Apollo Client adds a normalised cache, urql and Relay make different trade-offs, and code generation fixes the typing gap. If you are in React and only need server state, a general data library also works with a helper like this: see TanStack Query, which can wrap the gql function as its fetcher. Plenty of small apps and server-side scripts never need more than the helper above.

What the video covers

dcode’s video, from June 2021, is a seven-minute walkthrough on sending GraphQL requests with the Fetch API. Its chapters are: writing out a GraphQL query, using the Fetch API, the network tab, an overview, passing variables, and GraphQL variables. It shows the request in the browser’s network tab, which is the single most useful habit to take from it: when something is wrong, look at the actual request body and response before blaming a library. I could not read a transcript, so the lesson sticks to the chapter titles. The transport has not changed since 2021, so its age matters little. It does not discuss error handling, which the helper above covers.

Where this fits

This opens the clients group by stripping the client down to its transport. Next, Apollo Client basics shows what a full client wraps around the same POST.

Check yourself

  1. 01Why must you check the errors array even when response.ok is true?

    GraphQL reports resolver and validation failures inside a 200 response body, so HTTP success only means the server answered.

  2. 02Why pass variables separately instead of building the query string with template literals?

    The query text stays constant, which avoids injection through string building and lets the server and tools reuse the parsed document.

  3. 03What does operationName do?

    It tells the server which operation to run when the document contains more than one.

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark