All types in the GraphQL system are nullable by default. This means that a type like integer can not only take a number, including 1, 2, 3,...
, as its value but also take null
, which means no values. At the same time, GraphQL also allows us to make any type non-null. This means that the types we make non-null will never return null
. We always provide some values to the non-null types in GraphQL.
When we want to ensure that a particular field always exists, we use non-null constraints. It is important to remember that using a non-null field may make it more difficult to extend our GraphQL schema.
Let’s look at an example. In the following schema, we have a Hotel
type with a hotelLocation
field that refers to a Location
type:
type Hotel { hotelName: String! rating: Int! hotelLocation: Location! } type Location { address: String! } type Query { hotel(query: String): [Hotel] }
Non-null
fields are those that have an exclamation mark (!
) next to their type. When we query these fields, they will not return a null value. Here’s a query:
hotel { hotelName hotelLocation { address } }
We can get the following outcomes:
// no restaurants exist { hotels: null } // all data present { hotels: [{ hotelName: "pearl continental", hotelLocation: { address: "Street 85, San Francisco" } }] }
However, we will not be able to obtain the following outcomes:
// hotelName or hotelLocation not be null // this result would be incorrect { hotel: [{ hotelName: null, hotelLocation: null }] }
To ensure the structure of the response, GraphQL may also ensure the presence of specific fields when queried.
RELATED TAGS
CONTRIBUTOR
View all Courses