What is List Type in GraphQL: Explanation and Example
list type represents a collection of items of a specific type, similar to an array in programming. It is written by wrapping a type in square brackets, like [Type], and allows you to query multiple values in one field.How It Works
Think of the list type in GraphQL as a shopping basket that can hold many items of the same kind. Instead of asking for just one item, you ask for a whole group of items at once. For example, if you want to get a list of books, you use a list type to say "give me many books, not just one."
In GraphQL schema, you define a list type by putting the type inside square brackets, like [Book]. This tells GraphQL that the field will return multiple books, not a single book. Each item inside the list must be of the specified type.
This makes it easy to work with collections of data, such as lists of users, products, or comments, all in one query.
Example
This example shows a GraphQL schema with a list type for books and a query that returns multiple books.
type Book { id: ID! title: String! author: String! } type Query { books: [Book!]! }
Example Query and Result
Here is a query asking for all books and the expected result with multiple book items.
query {
books {
id
title
author
}
}When to Use
Use list types when you want to get multiple items of the same kind in one query. For example, if you want to fetch all users in a system, all comments on a post, or all products in a store, list types let you do this efficiently.
This helps reduce the number of queries you need to make and keeps your data organized. It is especially useful in real-world apps like social media feeds, product catalogs, or any place where you deal with groups of data.
Key Points
- A list type holds multiple items of the same GraphQL type.
- It is written with square brackets, like
[Type]. - Each item in the list must match the specified type.
- List types help fetch collections of data in one query.
- They improve efficiency and organization in your GraphQL API.