Schema
GraphQL Non-Null Types
Non-Null Types
GraphQL non-null types enforce required fields with !.
What Are GraphQL Non-Null Types?
In GraphQL, non-null types are used to ensure that a field, argument, or variable cannot be null
. This is indicated by appending an exclamation mark !
to the type name. By using non-null types, you can enforce that a particular field must always be provided with a value, thus preventing potential issues related to null values in your data.
Why Use Non-Null Types?
Non-null types are crucial in scenarios where certain fields are mandatory for the operation of your application. They help to:
- Reduce the need for null checks in your application code.
- Ensure data integrity by enforcing required fields in your schema.
- Improve the reliability of your GraphQL API by avoiding unexpected null values.
Defining Non-Null Types in Schema
To define a non-null type in your GraphQL schema, simply append an exclamation mark !
to the type you want to make non-null. Here's an example:
In this example, the id
and name
fields are marked as non-null, meaning they must always contain a value. The email
field, however, is nullable and can be null
.
Non-Null Types in Operation Arguments
Non-null types are not limited to fields alone. They can also be used in operation arguments to enforce that certain inputs are mandatory. Consider the following example:
Here, the createUser
mutation requires both name
and email
arguments to be non-null, ensuring that these values must be provided when the mutation is executed.
Handling Non-Null Types in Client Requests
When making requests to a GraphQL API, clients must adhere to the non-null constraints defined in the schema. Failing to provide a value for a non-null field or argument will result in a validation error. Therefore, it's important to ensure that your client-side code handles these requirements correctly.
This mutation request will succeed because it provides values for both non-null arguments name
and email
. If either of these were omitted, the request would fail with an error.
GraphQL Schema
- Previous
- Lists
- Next
- Schema Definition