0
0
GraphqlHow-ToBeginner · 3 min read

How to Query Array of Objects in GraphQL: Syntax and Examples

To query an array of objects in GraphQL, specify the field that returns the array and then list the subfields you want for each object inside curly braces. Use nested braces to access properties of each object in the array.
📐

Syntax

In GraphQL, to query an array of objects, you write the field name that returns the array, followed by curly braces containing the fields you want from each object. Each object in the array will return those fields.

For example, if you have a users field returning an array of user objects, you can query their id and name like this:

graphql
query {
  users {
    id
    name
  }
}
💻

Example

This example queries a list of books, each with an id, title, and an array of authors. For each author, it fetches the name and age. This shows how to query nested arrays of objects.

graphql
query {
  books {
    id
    title
    authors {
      name
      age
    }
  }
}
Output
{ "data": { "books": [ { "id": "1", "title": "GraphQL Basics", "authors": [ {"name": "Alice", "age": 30}, {"name": "Bob", "age": 45} ] }, { "id": "2", "title": "Advanced GraphQL", "authors": [ {"name": "Carol", "age": 40} ] } ] } }
⚠️

Common Pitfalls

One common mistake is forgetting to specify the subfields inside the array field, which results in an error because GraphQL requires you to specify exactly what data you want.

Another mistake is trying to query fields that do not exist on the objects inside the array.

graphql
query {
  books {
    authors
  }
}

# Wrong: 'authors' is an array of objects, so you must specify subfields like 'name' or 'age'.

query {
  books {
    authors {
      name
      age
    }
  }
}

# Correct: Specify subfields inside 'authors' array.
📊

Quick Reference

ConceptDescriptionExample
Array FieldField returning an array of objects`books` in `books { id title }`
SubfieldsFields requested inside each object in the array`id`, `title` inside `books { id title }`
Nested ArraysArrays inside objects can be queried with nested braces`authors { name age }` inside `books`
Required SubfieldsMust specify subfields for object arrays, not just the array name`authors { name }` not just `authors`

Key Takeaways

Always specify subfields inside array fields to get object properties.
Use nested braces to query arrays inside objects.
Query only fields that exist on the objects to avoid errors.
GraphQL requires explicit field selection for arrays of objects.
Nested arrays can be queried by nesting braces accordingly.