0
0
GraphQLquery~5 mins

Required fields with non-null (!) in GraphQL

Choose your learning style9 modes available
Introduction

We use required fields with non-null (!) to make sure some data is always given. This helps keep data complete and reliable.

When you want to make sure a user's name is always provided in a form.
When an email address must be given to create an account.
When a product's price should never be missing in a store database.
When a post must always have a title before saving.
When a required setting must be set before running a program.
Syntax
GraphQL
type TypeName {
  fieldName: FieldType!
}

The exclamation mark ! after the type means the field is required and cannot be null.

If you omit !, the field can be empty or missing.

Examples
id and name must always have values. email can be empty.
GraphQL
type User {
  id: ID!
  name: String!
  email: String
}
name and price are required fields. description is optional.
GraphQL
type Product {
  name: String!
  price: Float!
  description: String
}
Sample Program

This defines a Book type where title and author must always be provided. publishedYear is optional.

GraphQL
type Book {
  title: String!
  author: String!
  publishedYear: Int
}
OutputSuccess
Important Notes

Using ! helps catch errors early by forcing required data.

Be careful not to mark too many fields as required, or it can make data input hard.

Summary

Adding ! after a field type makes it required and non-null.

Required fields help keep your data complete and trustworthy.

Optional fields can be left empty or missing.