Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

graphql
constraints
non-null

What are non-null constraints in GraphQL?

Mian Basam Ahmad

Overview

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 to use

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.

How non-null works

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]
}
GraphQL schema

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
    }
  }
GraphQL query

We can get the following outcomes:

// no restaurants exist
{ hotels: null } 

// all data present
{
  hotels: [{
    hotelName: "pearl continental",
    hotelLocation: {
      address: "Street 85, San Francisco"
    }
  }]
}
Query result

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
  }]
}
Query result

To ensure the structure of the response, GraphQL may also ensure the presence of specific fields when queried.

RELATED TAGS

graphql
constraints
non-null

CONTRIBUTOR

Mian Basam Ahmad
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring