What is an exclamation point in GraphQL?

In GraphQL, an exclamation point (!) is used to indicate that a field or argument is “non-null.” This means that the field or argument must always have a value; it cannot be null.

When defining a GraphQL schema, you can specify whether a field in a type is nullable or non-null by adding the exclamation point after the field’s type definition. For example:

type User {
  id: ID!       # "!" indicates that the "id" field is non-null.
  name: String  # "name" field is nullable (may return null).
  age: Int!     # "!" indicates that the "age" field is non-null.

In this example, the “id” field of the “User” type is non-null, meaning every user must have an ID, and it cannot be returned as null in the API response. The “name” field, however, is nullable, so it may or may not have a value in the response. The “age” field is also non-null, ensuring that every user must have a valid integer age value.

When querying data with GraphQL, the exclamation point can also be used to indicate that a particular field in the response must be included. For example:

query {
  user(id: "123") {
    id     # Since "id" is non-null in the schema, it must be included in the response.
    name   # "name" is nullable, so it might or might not be included in the response.
    age    # Since "age" is non-null, it must be included in the response.

If the server returns null for a non-null field, it would be considered a schema violation, and the GraphQL response would be marked as an error.

The use of exclamation points helps ensure that the API clients can expect certain fields to always be present and not have to worry about handling null values for those fields, making the API more predictable and robust.

error: Content is protected !!