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.