What is Non Null Type in GraphQL: Explanation and Example
Non-Null type means a field must always have a value and cannot be null. It is denoted by adding an exclamation mark ! after the type, like String!, ensuring the server always returns a value for that field.How It Works
Think of a Non-Null type in GraphQL like a promise that a value will always be there, just like when you order a coffee and expect it to arrive. If the server cannot provide a value for a Non-Null field, it will return an error instead of sending null.
This helps clients trust the data they receive without checking for missing values all the time. It is like having a safety net that guarantees certain fields are never empty.
Example
This example shows a GraphQL schema where the name field is String!, meaning it cannot be null, while nickname can be null.
type User { id: ID! name: String! nickname: String } query { user(id: "1") { id name nickname } }
When to Use
Use Non-Null types when you want to make sure certain data is always present, like a user's ID or name. This is important for fields that your app logic depends on and cannot work without.
For example, in a social media app, a post's id and content might be Non-Null because they are essential, while an optional image URL could be nullable.
Key Points
- Non-Null types guarantee a value is always returned, never
null. - They are marked with an exclamation mark
!after the type. - If a
Non-Nullfield cannot be resolved, GraphQL returns an error. - Use them to enforce required data in your API schema.