GraphQL Formatter & Schema Viewer · Tutorial

How to fix GraphQL variable and fragment errors

6 min readintermediateUpdated

Your GraphQL request fails with a validation error before the server even runs it. This tutorial formats the document so you can read it, then works through each problem the checker reports, from an undeclared variable to an unused fragment, until the document is valid.

What you need

Steps

  1. Paste and format the document

    Paste the query into the left box. The right box shows it formatted with one field per line, which makes the structure clear. The summary says there are 5 problems to check below.

  2. Give each operation a unique name

    The first problem says Two operations are named "ShopOrders". Servers need unique names to know which one to run. Rename the second one, for example to CurrentUser.

  3. Declare the missing variable

    Variable $region in ShopOrders is used but not declared. Every variable passed to a field must appear in the operation's list in brackets. Add it with its type.

    query ShopOrders($first: Int!, $status: OrderStatus, $region: String) {
  4. Remove the unused variable

    $after is declared but never used, and servers reject that too. Either pass it to the field, for example orders(first: $first, after: $after, ...) for paging, or remove it from the list.

  5. Fix the fragments

    The query spreads ...OrderCustomer, which is not defined, while CustomerFields is defined but never used. In this case the spread has the wrong name: change it to ...CustomerFields, and both problems disappear at once.

  6. Check the result

    When the summary turns green and lists the operations and fragment with no problems, copy the formatted query. Choose Minified (one line) if you need it inside a JSON request body.

Try it yourself

Opens the GraphQL Formatter & Schema Viewer with this tutorial's sample loaded.

Try it now

Common mistakes

Declaring a variable without its type
Every variable needs a type, such as $region: String. Add ! only if the variable is required, for example Int!.
Defining a fragment in a different request
A fragment must be in the same document as the query that uses it. Paste the fragment definition into the same request.
Leaving an unnamed query next to named ones
An anonymous { ... } query is allowed only when it is the only operation. Give it a name as soon as you add a second one.

Next steps

Go back to the GraphQL Formatter & Schema Viewer, or keep going with one of these:

FAQ

Does it check that fields like orders exist?

No. That needs your server's schema. Run the query against your server or an introspected schema for field checks.

Why does the server reject unused variables at all?

The GraphQL specification requires every declared variable to be used, which helps catch typos in variable names.