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 {hotelNamehotelLocation {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"}}]}
// 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.
Unlock your potential: GraphQL series, all in one place!
To continue your exploration of GraphQL, check out our series of Answers below:
What is GraphQL?
Get an overview of GraphQL, its core principles, and how it enhances API interactions.
What are abstract types in GraphQL?
Understand abstract types like interfaces and unions, and how they provide flexibility in your GraphQL queries.
What are non-null constraints in GraphQL?
Discover the role of non-null constraints in ensuring data integrity within GraphQL schemas.
What are different ways to pass an argument in GraphQL?
Explore various methods for passing arguments in GraphQL to customize queries and mutations for specific needs.
GraphQL vs. REST
Compare GraphQL with REST, understanding the strengths and differences between the two approaches.
How to set up GraphQL in a React app
Learn how to integrate GraphQL into React apps to create dynamic, data-driven user interfaces.
Free Resources