BudiBadu Logo
Samplebadu

GraphQL by Example: Non-Null Modifier

June 2018 Specification

Enforcing required fields with this code example showing exclamation mark syntax for non-null types, error bubbling behavior when null returned, required arguments with non-null modifier, and schema validation guarantees.

Code

type User {
  # ID cannot be null
  id: ID!
  
  # Username is required
  username: String!
  
  # Bio is optional (can be null)
  bio: String
}

type Query {
  # Argument 'id' is required
  user(id: ID!): User
}

Explanation

By default, all GraphQL types are nullable, meaning fields can legitimately return null values. The non-null modifier, an exclamation mark ! appended to type names, explicitly declares that fields must always return values and cannot be null. If a resolver for a non-nullable field produces null, GraphQL triggers an execution error that bubbles up to the nearest nullable parent field, setting that parent to null.

When a field is marked as non-null like String!, and the server attempts to return null for it, GraphQL considers this a schema violation. This error propagation ensures clients never receive null values for fields they expect to be present, providing data integrity guarantees. The type system enforces these constraints at runtime, making null-handling explicit and predictable.

Arguments can also be non-null, as shown in user(id: ID!) where clients must provide the id argument. Omitting required arguments causes the server to reject queries before execution, providing clear validation errors. This compile-time validation prevents invalid queries from reaching resolvers, improving API reliability and developer experience.

Code Breakdown

3
id: ID! guarantees every User object will have an ID, cannot be null.
6
username: String! required field, resolver must return value or error bubbles up.
9
bio: String without exclamation mark is nullable, safe to return null.
14
user(id: ID!) required argument, clients must provide id or query rejected.