GraphQL mutation variables
Asked Answered
L

3

12

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.

Lippert answered 18/9, 2015 at 17:13 Comment(0)
F
13

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.

Flatter answered 29/7, 2016 at 13:44 Comment(1)
Incredible the the ! was the issue... Alas it does make sense!Treenatreenail
O
0

I think in you addGroup() mutation the args for name is of type String! that is new GraphQLNonNull(GraphQLString) but in your mutation you specify as String which conflicts with the type system.

Oilskin answered 24/9, 2015 at 7:55 Comment(0)
D
0

When you have an error like this check your database model, in my case I checked my schema and as mongo pluralizes the words was causing me error but I could fix it, also check the documentation.

mutation {
  createProject(
    name:"project two",
    description:"project two"
  ) {
    name
  }
}

=> works

Dorcy answered 17/2, 2023 at 4:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.