Queries and fields

GraphQL · Essentials · 10 min

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) or subscription (stream). The shorthand { ... } is an anonymous query.
  • Operation name: CurrentUser above. 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).
  • __typename can 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.

Check yourself

  1. Why does `query { me }` fail when `me` returns a User object?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: graphql.org/learn/queries/