How to Use Exclamation Mark in GraphQL: Non-Null Syntax Explained
In GraphQL, the
! (exclamation mark) is used to mark a type as non-nullable, meaning the field or argument must always have a value and cannot be null. For example, String! means the value must be a string and cannot be null. This helps enforce required fields in your schema and queries.Syntax
The exclamation mark ! is placed immediately after a type to indicate it cannot be null. This applies to fields, arguments, and input types.
- Type!: The value must be of the specified type and cannot be null.
- [Type]!: The list itself cannot be null, but items inside can be null.
- [Type!]!: Neither the list nor any item inside can be null.
graphql
type User {
id: ID!
name: String!
email: String
friends: [User!]!
}Example
This example shows a GraphQL schema where id and name are required fields (non-nullable), while email is optional. The friends field is a non-null list of non-null User objects.
graphql
type User { id: ID! name: String! email: String friends: [User!]! } type Query { getUser(id: ID!): User! }
Common Pitfalls
Common mistakes when using ! include:
- Marking a field as non-nullable but returning
nullin the resolver, which causes errors. - Confusing
Type!(non-nullable type) with[Type]!(non-nullable list but nullable items). - Not using
!on required arguments, leading to unexpectednullvalues.
graphql
type Query {
# Wrong: id argument is nullable but should be required
getUser(id: ID): User!
# Right: id argument is non-nullable
getUserById(id: ID!): User!
}Quick Reference
| Syntax | Meaning |
|---|---|
| Type | Nullable type, value can be null |
| Type! | Non-nullable type, value cannot be null |
| [Type] | Nullable list, list or items can be null |
| [Type]! | Non-nullable list, list cannot be null but items can be |
| [Type!] | Nullable list, items cannot be null but list can be |
| [Type!]! | Non-nullable list and items, neither can be null |
Key Takeaways
Use
! after a type to make it non-nullable and required.Non-nullable fields must always return a value; returning null causes errors.
Use
! on arguments to enforce required inputs in queries.Understand the difference between non-nullable lists and non-nullable items inside lists.
Proper use of
! improves schema reliability and client expectations.