Join us on Nov 7 for GraphQL Summit Virtual
Join API innovators, GraphQL experts, and AI trailblazers on Nov 7 at GraphQL Summit Virtual. Register for free →
Nullability describes whether or not a field is allowed to return null
, the programming value for nothing.
When we want to allow a field to return a null
value in GraphQL, we don't need to change anything about its definition. The field's name, along with the type of data it returns, is all the configuration we need to allow null
as a possible return value.
But when we want to express that a field should never return null
—that is, we want to require that we ALWAYS get a value back that matches the field's expected type—we can attach an exclamation point (!
).
This is the Non-Null
type, and like List
, it's considered a "wrapping type." This means that we attach it to a field's data type definition. Whatever comes directly before the exclamation point is the element that cannot be null
. This rule becomes essential when decoding more complex types where the List
and Non-Null
types are combined.
nutrients: [String!]!
Beginning from the outside and moving inward:
nutrients
field returns a List
type and, regardless of what's inside of the list, the list itself cannot be null
. At the very least, it can be empty, returning a value of []
.String
. None of the String
items contained in the list are permitted to return a value of null
.Putting the Non-Null
constraints in place ensures that an error will occur anytime a null
value is returned.
We can pick and choose which fields on a type should restrict null
values. Let's look at one implementation of the Fruit
type.
type Fruit {id: ID!name: String!quantity: Int!price: Int!averageWeight: FloathasEdibleSeeds: Booleannutrients: [String]}
The fields we've denoted as non-nullable include id
, name
, quantity
, and price
. From the perspective of a fruit stall selling its products, providing customers with accurate information about how many items are in stock (is there enough for me to make a purchase?) as well as how much each item costs (do I have enough money to buy this item?) are essential to the success of the business. Providing a name
for each fruit should also be required, as this field serves as the human-friendly label that customers use to make their fruit selection.
While id
also serves a role as an identifier, its specific designation as type ID
says that the GraphQL service is responsible for ensuring that this field's value is unique between different kinds of fruits. By preventing the id
field from returning null
for any fruit we might query, we can protect the integrity and completeness of our data, as well as avoid introducing errors.
About
GraphQL.com is maintained by the Apollo team. Our goal is to give developers and technical leaders the tools they need to understand and adopt GraphQL.
GraphQL.com 2024