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.
authorreturns anAuthor, so you must say which of its fields you want:author { name }. Writing justauthoris an error. - Leaf fields take no braces.
titleis aString,priceaFloat. These are scalars, the ends of the walk, andtitle { ... }is an error. - Lists repeat the selection.
booksreturns 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.
The shortcut
Before sending a query, run the leaf check: follow every branch to its end and make sure it stops on a scalar.
Start at the root
booksreturns[Book!]!, an object list, so it needs braces. It has them.
The classic mistake is writing author alone because "I want the whole author". GraphQL has no "select everything"; you always list the fields you need.
Drills
Answer fast — trust the rule.
Why is { book(id: "b1") { author } } rejected?
Which query is valid?
What is the shape of data.books for { books { title } }?
What does { book(id: "b1") { __typename } } return inside book?
Remember
- Objects need braces, leaves need none; the answer copies the shape.
- Leaf check: every branch must end on a scalar.
- Trap: there is no "select all"; list every field you want.
