Every GraphQL interaction starts with reading and writing query documents.
A query is a tree of selection sets: braces listing the fields you want. Scalar fields (strings, numbers, booleans, IDs, enums) are leaves; object fields must have their own selection set, because GraphQL never returns "the whole object" implicitly.
query CurrentUser {
me {
name
avatarUrl
team { name }
}
}Pieces of a document:
- Operation type:
query(read),mutation(write) orsubscription(stream). The shorthand{ ... }is an anonymous query. - Operation name:
CurrentUserabove. Always name operations in real code; servers log them, and clients use them for caching and tracing. - Fields can take arguments, e.g.
posts(first: 5). __typenamecan be requested on any object to learn its concrete type.
A document may contain several operations; the request then says which one to run via operationName.
Requesting an object field without a selection set, or a field that does not exist, is a validation error: the server rejects the whole operation before running any code. This is one of GraphQL's best features: typos are caught immediately, and tools like GraphiQL autocomplete fields from the schema.
Example
query DashboardHeader {
me {
__typename # "User"
name
unreadCount
team {
name # team is an object, so it needs a selection set
}
}
}
# Invalid: object field without a selection set
# query { me }
# -> "Field \"me\" of type \"User\" must have a selection of subfields."Remember
- Object fields need a selection set; scalars are leaves
- Name every operation for logging, caching and tracing
- Unknown fields fail validation before execution
Watch out for
- Expecting
{ me }to return the entire user object.