Skip to the workspace
Pebellslearn by building
GraphQL Queries  ›  Lesson

Queries and Fields

What are Queries? 12 minA query is a read-only operation made of nested fields, where every field that returns an object needs its own selection set, every branch must end on a scalar, and list fields repeat their selection for each item.

graphql / Queries and Fields

Explore each scene at your own pace.

01 · The rule

The rule

Queries and Fields

The bookshop's "Browse" page needs every book's title and price. A query is how you ask, and fields are the words you ask with. Get the rules for fields right and most query errors disappear before you ever send a request.

The rule

Objects need braces, leaves need none; the answer copies the shape.

A query is a read-only operation. It starts with the keyword query and a selection set: fields inside braces.

query {
  books {
    title
    price
    author {
      name
    }
  }
}

Three rules cover almost every query:

  • Object fields need a sub-selection. author returns an Author, so you must say which of its fields you want: author { name }. Writing just author is an error.
  • Leaf fields take no braces. title is a String, price a Float. These are scalars, the ends of the walk, and title { ... } is an error.
  • Lists repeat the selection. books returns a list of books, so { title price author { name } } is applied to every book, and the response holds an array.
{
  "data": {
    "books": [
      { "title": "The Salt Road", "price": 499, "author": { "name": "Mira Kapoor" } },
      { "title": "The Quiet Ledger", "price": 350, "author": { "name": "Arjun Rao" } }
    ]
  }
}

When a document holds a single unnamed query, you may drop the keyword and write just { books { title } }. This is the query shorthand.

Every object type also has a built-in field, __typename, that returns the name of the object's type as a string, such as "Book". It becomes very useful once a field can return more than one type.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.