Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 39 ยท Beyond Fetch

GraphQL Requests with fetch

Call a GraphQL API from the browser with plain fetch - query, variables and operationName, the data and errors response shape, mutations, partial results and REST comparison.

With a REST API you usually have many URLs: /users/1, /users/1/posts, /posts/7/comments. Each one returns a fixed shape chosen by the server. A screen that needs a user's name, their three latest posts and the like count of each post might need three round trips, and it receives dozens of fields it never shows.

GraphQL takes a different approach. There is normally one URL, and the client sends a query describing exactly the fields it wants, even across related objects. The server answers with JSON in exactly that shape. For the browser, a GraphQL call is nothing exotic: it is an ordinary fetch() with a POST and a JSON body. In this lesson you will build those requests, send variables safely, read the data and errors response, run a mutation, and compare GraphQL with REST so you know when to choose it.

The shape of a GraphQL request

A request is a JSON object with up to three fields:

JavaScript
// Read-only: the real network version
const response = await fetch("https://api.example.com/graphql", {
  method: "POST",
  headers: { "Content-Type": "application/json", Accept: "application/json" },
  body: JSON.stringify({
    query: `query GetUser($id: ID!) {
      user(id: $id) {
        name
        posts { title likes }
      }
    }`,
    variables: { id: "1" },
    operationName: "GetUser",
  }),
});
const { data, errors } = await response.json();
  • query is the GraphQL text. It is a string, not JSON. It can hold a query (read), a mutation (write) or a subscription (live updates, usually over WebSockets).
  • variables is a JSON object with the values for $id and friends.
  • operationName chooses which operation to run when the document contains several. It is optional otherwise.

The response is JSON with two possible keys: data (shaped exactly like your query) and errors (a list of problems). Both can appear together, which is the biggest difference from REST error handling and gets its own section below.

Try it against a stand-in server

The editors on this site cannot reach a real GraphQL server, so the next example includes a small stand-in: a hand-written function that understands just enough GraphQL (fields, nested fields, arguments, variables, aliases, mutations) to answer queries about two users and their posts. It is not a real GraphQL implementation, but the requests and responses you see have the real format, and fakeFetch has the same call shape as fetch(), so your client code is the real thing. Read the client part at the bottom of the program; the stand-in at the top is only scaffolding.

JS Queries, variables, aliases, errors and a mutation

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the output with these ideas in mind:

  1. You choose the fields. The query asked for name and city, so that is all that came back.
  2. Variables keep the query constant. The text of postsQuery never changes, only { id: "2" } does.
  3. Aliases (first:, second:) let you ask for the same field twice with different arguments in a single round trip.
  4. A missing user is null, not a 404. The request succeeded; the answer is "nothing".
  5. Partial success is normal. The second user's email is forbidden, so that one field is null with an entry in errors, while everything else arrives.
  6. Invalid queries fail before running, so there is no data at all.
  7. Mutations use the same transport; they just start with the word mutation.

Always send variables, never glue strings

It is tempting to build a query with a template literal:

JavaScript
// Read-only: avoid this
const query = `{ user(id: "${userInput}") { name } }`;

If userInput contains a quote and extra GraphQL (1") { name } secret: users { email), the attacker has rewritten your query: a GraphQL cousin of SQL injection. It also gives the server a different query string for every value, which defeats caching and logging. Always put values in variables. If you like a tidy way to write queries, use a tagged template to keep the text constant; see Tagged Template Literals for how such helpers are built.

Two layers of errors

GraphQL separates problems into layers, and a good client checks each one:

Layer What it looks like How to handle it
Network fetch() rejects (offline, DNS, CORS) try/catch, show a connection message, retry
HTTP response.ok is false (401, 403, 429, 500) Treat auth failures and rate limits like any API (see headers and auth)
GraphQL status 200 but the body has errors Read errors[].message and path; decide whether data is still usable

The first two behave exactly as in fetch error handling. The third is the trap: a 200 OK response can still be a failure. Many servers answer 200 even when every field failed, so checking response.ok alone is not enough. Always look at the errors key. Each error has a message, usually a path that points at the failing field, and often an extensions object with a machine-readable code such as "UNAUTHENTICATED".

GraphQL or REST?

flowchart TD
  Q{"What does the client need?"} -->|"Many related objects, differing fields per screen"| G["GraphQL: one request, exact fields"]
  Q -->|"Simple resources, strong HTTP caching, public CDN"| R["REST: one URL per resource"]
  G --> GN["Costs: query complexity limits, server N+1 risk, harder HTTP caching"]
  R --> RN["Costs: over-fetching, several round trips, many endpoints"]

Neither is better everywhere. They solve different pain points.

GraphQL shines when many different clients (a web app, a phone app, a partner) need different slices of the same data, and when screens combine several related objects. REST shines for simple resource APIs, file downloads, and anything that benefits from HTTP caching, because GET URLs are easy for browsers and CDNs to cache. With GraphQL, queries usually travel as POST to one URL, so caching moves into the client (libraries such as Apollo Client and urql keep a normalized cache) or uses persisted queries, where the client sends a short ID instead of the full text and the server looks it up.

Practical notes

  • Fragments (fragment UserBits on User { name city }) let several queries share a field list. They are part of the query text, so they work through plain fetch() too.
  • Authentication uses the usual Authorization header; see OAuth, Tokens and Sessions for API Calls.
  • Do not trust the client for authorization. Hiding a field in your UI does not protect it. The server must check who may read each field, as the stand-in did for the email.
  • Explore the schema. Most servers support introspection and tools such as GraphiQL, which list every type and field; many production servers disable introspection for public APIs.
  • Limit depth and cost on your own server, because a client can ask for deeply nested data.
  • Use AbortController to cancel a stale GraphQL request, exactly as in Aborting and Timeouts.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a typical browser GraphQL call look like?

    GraphQL runs over ordinary HTTP. The usual form is POST with a JSON body {query, variables, operationName}.
  2. 2. A GraphQL response has status 200 and a body with an errors array. What should the client do?

    GraphQL reports many failures inside a 200 response. Always check the errors key, and decide whether the partial data is usable.
  3. 3. Why should values be sent in variables rather than placed inside the query string?

    String-gluing lets input rewrite the query. Variables are passed as data, and the query text stays identical for every request.
  4. 4. What does an alias, such as first: user(id: 1), allow?

    An alias renames the key in the response, so two user(...) fields can coexist in one query.
  5. 5. In the lesson's stand-in server, why is a lookup for a user that does not exist not an error?

    Absence of data is a valid result, so the field is null. The errors list is for failures such as bad queries or forbidden fields.

Summary

  • GraphQL is a query language served over HTTP, usually from one endpoint; the browser calls it with fetch() and POST.
  • A request body has query, variables and optionally operationName; a response has data and/or errors.
  • Always pass values as variables, never by concatenating strings into the query.
  • Check three error layers: network failure, HTTP status and the GraphQL errors array (a 200 can still contain errors, and data can be partial).
  • Mutations use the same transport and return the changed data; aliases and multiple root fields reduce round trips.
  • Choose GraphQL for many related objects and varied clients; choose REST for simple resources and easy HTTP caching.

Next, learn how API requests prove who is calling: OAuth, Tokens and Sessions for API Calls.