What is an exclamation point in GraphQL?
Solution 1:
That means that the field is non-nullable.
See more info in Graphql - Schemas and Types
Solution 2:
From the spec:
By default, all types in GraphQL are nullable; the null value is a valid response for all of the above types. To declare a type that disallows null, the GraphQL Non‐Null type can be used. This type wraps an underlying type, and this type acts identically to that wrapped type, with the exception that null is not a valid response for the wrapping type. A trailing exclamation mark is used to denote a field that uses a Non‐Null type like this: name: String!.
In other words, types in GraphQL are nullable by default. An exclamation point after a type specifically designates that type as non-nullable.
This has different implications depending on where the type is used.
Output
When non-null is applied to the type of a field, it means that if the server resolves that field to null
, the response will fail validation. You may still receive a partial response, as long as the error does not propagate all the way up to the root.
For example, given a schema like:
type Query {
user: User
}
type User {
id: ID!
}
Here the id
field is non-null. By marking the field as non-null, we are effectively guaranteeing we will never return null for this field. If the server does return null, then it's an indication that something went terribly wrong and we want to throw a validation error.
Input
When non-null is applied to the type of an input, like an argument, input object field or a variable, it makes that input required. For example:
type Query {
getUser(id: ID!, status: Status): User
}
Here, the id
argument is non-null. If we request the getUser
field, we will always have to provide the id
argument for it. On the other hand, because the status
argument is nullable, it's optional and can be omitted. This applies to variables as well:
query MyQuery ($foo: ID!) {
getUser(id: $foo)
}
Because the $foo
variable is non-null, when you send the query, it cannot be omitted and it's value cannot equal null
.
A special note on variable types
Because the id
field is a non-null ID
(i.e. ID!
) type in our example, any variable we pass it must also be a non-null ID
. If our $foo
variable was a nullable ID
, we could not pass it to the id
argument. The opposite, however, is not true. If an argument is nullable, you can pass it a non-null variable.
In other words:
+----------+----------+--------+
| Argument | Variable | Valid? |
+----------+----------+--------+
| String | String | ✅ |
| String | String! | ✅ |
| String! | String | ❌ |
| String! | String! | ✅ |
+----------+----------+--------+