Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL mutation variables

I'm trying to do a simple mutation using GraphQL with the GraphiQL interface. My mutation looks like this:

mutation M($name: String) {
  addGroup(name:$name) {
    id,
    name
  }
}

with variables:

{
  "name": "ben"
}

But it gives me the error: Variable $name of type "String" used in position expecting type "String!"

If I change my mutation to mutation M($name: String = "default") it works as expected. This looks like it's related to the type system, but I can't seem to figure out what the problem is.

like image 912
bento Avatar asked Sep 18 '15 17:09

bento


People also ask

How do you use variables in a GraphQL mutation?

Variables simplify GraphQL queries and mutations by letting you pass data separately. A GraphQL request can be split into two sections: one for the query or mutation, and another for variables. Variables can be declared after the query or mutation and are passed like arguments to a function and begin with $ .

What is mutation type in GraphQL?

Mutations allow you to modify server-side data, and it also returns an object based on the operation performed. It can be used to insert, update, or delete data. Dgraph automatically generates GraphQL mutations for each type that you define in your schema.

How do you give variables in GraphiQL?

The GraphiQL client allows you to create variables for use in your queries. To add a query variable, click the Query Variables pane and enter a JSON object that defines your variable. To use a variable in your query, prepend the $ character to your variable name and use it to replace the desired value.


1 Answers

You probably defined the input name as a non-null string (something like type: new GraphQLNonNull(GraphQLString) if using js server, or String! in plain GraphQL).

So your input in the mutation must match, which means it must also be a non-null string. If you change to the following, it should work:

mutation M($name: String!) {
  addGroup(name:$name) {
    id,
    name
  }
}

Also if you define a default value as you did, it will be a non-null string.

Finally, you could drop the requirement of being a non-null in the server.

like image 155
dqc Avatar answered Oct 22 '22 21:10

dqc