Chuyển đến nội dung

Bài 6 · Writing Queries

Fields, Arguments and Nested Selections

Learn how GraphQL fields work: scalar and object fields, nested selections through relationships, arguments on any field and default values.

Everything you ask for in GraphQL is a field. A field is a named piece of data on an object, and an object's fields can themselves be objects with more fields. By nesting selections you walk through your data graph in a single request. By adding arguments you tell a field which data to return: which book, which genre, how many results.

This lesson covers both ideas and then extends the stand-in executor from Your First Query to understand arguments. As always, the executor is a teaching stand-in; real GraphQL servers are shown read-only.

Scalar fields and object fields

Fields come in two kinds, and the difference decides how you write them.

A scalar field holds a single value: a string, number, boolean or ID. You select it by name and stop:

GRAPHQL
{
  book(id: "b1") {
    title
    year
  }
}

An object field returns another object (or a list of them). You must open a selection set and pick fields from that inner object:

GRAPHQL
{
  book(id: "b1") {
    title
    author {
      name
      born
    }
  }
}

Here author is an object field on Book. Its selection set { name born } picks fields from Author. You may keep going as deep as the schema allows, because Author can have a books field returning Book objects, whose author field returns an Author again:

GRAPHQL
{
  book(id: "b1") {
    title
    author {
      name
      books {
        title
      }
    }
  }
}

That works because GraphQL data is a graph, not a tree: the types can point at each other in loops. The query itself is always finite, since you decide how deep to write it. (Servers also limit depth to protect themselves; see Query Depth, Complexity and Other Attacks.)

Two kinds of field

Scalar One value. No braces after it.
Object Needs braces to pick inner fields.

A missing selection set on an object field is a validation error.

1 / 2

Arguments

Any field can take arguments, written in parentheses after the field name as name: value pairs, separated by spaces or commas:

GRAPHQL
{
  book(id: "b1") {
    title
  }
  books(genre: FANTASY, limit: 2) {
    title
    year
  }
}

Several things are worth noticing:

  • Arguments are named, not positional, so order does not matter and a field can have many optional ones.
  • Values can be strings ("b1"), numbers (2, 3.5), booleans (true), null, enum values written bare (FANTASY), lists ([1, 2]) and objects ({ min: 1, max: 5 }).
  • Arguments work on nested fields too, not just at the top. author { books(limit: 1) { title } } asks for only one book per author.
  • The server's schema defines which arguments each field accepts, their types, and whether they are required.

Default values and required arguments

In the schema (SDL) an argument may have a default, and it may be marked required with !. This is read-only SDL; the next section shows it in action with a stand-in:

GRAPHQL
type Query {
  book(id: ID!): Book
  books(genre: Genre, limit: Int = 10): [Book!]!
}

id: ID! is required: the query { book { title } } fails validation. limit: Int = 10 is optional: if the client omits it, the server behaves as if limit: 10 had been sent. genre has no default and is nullable, so leaving it out means "no filter". You will meet the ! marker properly in Lists and Non-Null Types.

A stand-in executor with arguments

Here we extend the parser to read (name: value) pairs and let the executor call function fields. In our stand-in a field whose value is a JavaScript function receives its arguments object. That is a simplified version of what resolvers do in a real server, explained in Resolvers. The default for limit lives in the function's parameter list, playing the role of SDL's = 3.

JS Arguments and nested selections

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check how each query behaves. books { title } with no arguments used the default limit of 3. books(limit: 1) inside author returned a single book for that author. The last query loops from author to books and back to author, which is legal in a graph, and shows that the nested author field can be resolved separately for every book.

Aliases in a sentence

If you need the same field twice with different arguments, for example the first fantasy book and the first sci-fi book, a plain query would clash, because both results would be keyed books. The solution is an alias, covered in Aliases and Fragments.

Common mistakes

  • Forgetting the selection set. { book(id: "b1") } is invalid: book is an object field, so you must choose fields from it.
  • Selecting on a scalar. title { x } is invalid for the same reason, mirrored.
  • Quoting enum values. Write genre: FANTASY, not genre: "FANTASY". A quoted value is a string, and an enum argument rejects strings.
  • Assuming defaults on the client. If a field has limit: Int = 10, omitting limit gives you 10 results. Do not rely on a default that the schema does not state; check the schema.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which query is valid if author is an object field with a name scalar?

    Object fields need a selection set of inner fields. Dot syntax does not exist in GraphQL, and arguments need a name: value form.
  2. 2. What does the query { books(limit: 5, genre: FANTASY) { title } } demonstrate about argument order?

    Arguments are matched by name, which also makes optional arguments easy.
  3. 3. A field is declared as books(limit: Int = 10). What happens if the client omits limit?

    A default value in the schema applies whenever the client does not supply that argument.
  4. 4. Can arguments be used on nested fields?

    Every field can declare arguments, so author { books(limit: 1) { title } } is fine.

Summary

  • Scalar fields are leaves; object fields need a selection set.
  • Nested selections follow relationships, so one query can reach authors, books and reviews together.
  • Arguments are named key: value pairs on any field, including nested ones, with strings, numbers, booleans, null, enums, lists and objects as values.
  • Schemas can mark arguments required (!) or give them defaults (= 10).
  • The stand-in executor passes parsed arguments to function-valued fields, like resolvers do in a real server.

Next: Aliases and Fragments

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.