scalagraphqlsangria

Sangria not seeing GraphQL query variables


When I have a query like this:

{
  "query": "mutation { createInventory(name: $name, schema: $schema) }",
  "variables": {
    "name": "i1",
    "schema": "s"
  }
}

I get an error back: Variable '$name' is not defined.

I checked those variables were being extracted from JSON properly, and they were. To be sure, I tried explicitly passing in the name variable when I execute the query:

Executor.execute(
    GraphQLSchema.schema,
    query,
    ctx,
    variables = InputUnmarshaller.mapVars(Map("name" -> "foo"))
)

Why would Sangria not be recognizing these variables? Is there something wrong with how I'm naming them?


Solution

  • You're missing the "variable definition" section of the GraphQL query itself. This is a part of the query which indicates the types of variables it expects to be passed in.

    So this should work, provided I've guessed the right types for the variables:

    {
      "query": "mutation myMutation($name: String, $schema: String) { createInventory(name: $name, schema: $schema) }",
      "variables": {
        "name": "i1",
        "schema": "s"
      }
    }
    

    Read more in my article, The Anatomy of a GraphQL Query.