0
0
GraphqlConceptBeginner · 3 min read

What is Non Null Type in GraphQL: Explanation and Example

In GraphQL, a 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.

graphql
type User {
  id: ID!
  name: String!
  nickname: String
}

query {
  user(id: "1") {
    id
    name
    nickname
  }
}
Output
{ "data": { "user": { "id": "1", "name": "Alice", "nickname": null } } }
🎯

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-Null field cannot be resolved, GraphQL returns an error.
  • Use them to enforce required data in your API schema.

Key Takeaways

Non-Null types in GraphQL ensure fields always have a value and never return null.
They are declared by adding an exclamation mark (!) after the type name.
If a Non-Null field is missing, the server returns an error instead of null.
Use Non-Null types for essential data your app depends on.
Nullable types are for optional data that can be missing or unknown.