GraphQL by Example: List Types
Returning collections of values with this sample code demonstrating list type syntax using square brackets, combining lists with non-null modifiers, nullability control at different levels, and querying list fields with selection sets.
Code
type Query {
# Returns a list of Strings
tags: [String]
# Returns a list of User objects
users: [User]
# Returns a list that cannot be null,
# but can contain nulls: [Int]!
luckyNumbers: [Int]!
}
# Querying a list
query {
users {
name
}
}Explanation
List types in GraphQL represent collections or arrays of specific types, denoted by enclosing the type in square brackets like [String] or [User]. If a field returns null, the entire array is null; if it returns an empty list, the result is []. Lists can be combined with non-null modifiers to enforce stricter guarantees about nullability at different levels.
List type nullability combinations include:
[String]nullable list of nullable strings, list and elements can be null[String!]nullable list of non-null strings, list can be null but elements cannot[String]!non-null list of nullable strings, list cannot be null but elements can[String!]!non-null list of non-null strings, neither list nor elements can be null
When querying fields returning lists of objects like users, a selection set must be provided for the object type. The server executes the resolver for each item in the list, returning an array of objects where each object contains the selected fields. These modifiers can be arbitrarily nested to create complex type definitions, providing precise control over expected data structure and nullability constraints.
Code Breakdown
tags: [String] list of strings, result is JSON array like ["tech", "news"].users: [User] list of objects, requires selection set when querying.[Int]! non-null list, always returns array never null, elements can be null.
