Why GraphQl force you to match the variables requirements on the queries?

Viewed 1663

Let's say my GraphQl server have a query defined like this

query getUser(name: String!)

then I make a query like this

query getUser(name: String) {
  getUser(name: $name)
...

I get an error like this

Variable type 'String' doesn't match expected type 'String!

Why he is trying to match that instead of check if the value was already passed? The way I see it this is unnecessary and forces the client app to change for stupid reasons. Maybe I am missing something here.

1 Answers

The ! indicates a type as non-nullable. A non-nullable argument cannot be omitted or be passed a value of null. If the argument is passed a variable, the type of that variable must also be non-nullable. If the variable type was nullable, it would mean null would be a valid value for the variable, but null is not a valid value for the argument.

On the other hand, an argument whose type is nullable may accept variables that are either nullable or non-nullable because there is no incompatibility in the ranges of possible values.

This is all outlines in the Validation section of the spec.

Related