Graphene-django: How to use schema.execute?

Created on 1 Feb 2017  路  2Comments  路  Source: graphql-python/graphene-django

In GraphiQL it is all so easy:

query PendingUsers($id: Int!) {
  pending: pendingUsers(id: $id) {
    email
  }
}

query variables:

{"id": "6"}

How to get the same result in Python, using schema.execute()?

query = '''
  query PendingUsers($id: Int!) {
    pending: pendingUsers(id: $id) {
      email
    }
  }
'''

schema.execute(query)
# => Variable "$id" of required type "Int!" was not provided.

schema.execute(query, {"id": 6}) 
# => Variable "$id" of required type "Int!" was not provided.

schema.execute(query, {"id": "6"})
# => Variable "$id" of required type "Int!" was not provided.

schema.execute(query, {"$id": "6"})
# => Variable "$id" of required type "Int!" was not provided.

schema.execute(query, {"$id": 6})
# => Variable "$id" of required type "Int!" was not provided.

schema.execute(query, id=6)
# TypeError: graphql() got an unexpected keyword argument 'id'

Graphene documentation is very poor. It does not describe too much. There are almost no examples. Unit tests cover only some simple scenarios. :(

Most helpful comment

Hi @hipertracker,

There is clean a way to add this variables to the execution.
This is how you could do it:

schema.execute(query, variable_values={"id": 6})

Hope this helps!

All 2 comments

@hipertracker
your query should have the id inline.

additionally, you need to convert the id to its corresponding global id.

  import graphene
  from graphql_relay.node.node import to_global_id

  global_id = to_global_id("UsersNode", 6)
  query = '''
       query  {{
            pendingUsers(id: "{0}") {
                email
            }}
       }}
  '''.format(global_id)

 result = schema.execute(query)

 print('errors', result.errors)
 print('data', result.data)

I'm assuming your node is called UsersNode, if it isn't replace that with the proper name in the to_global_id

you also don't need to have anything after the first query. I'm not sure why all the docs have something after it. I think its just for description. But I haven't put anything there in any of my code

lastly, if you use format like I am, you'll have to escape out the query brackets by using double brackets

explanation here:
http://stackoverflow.com/questions/32224197/get-consistent-key-error-n

Your query that you pass to execute should look exactly how it would in the graphiql browser version. So its a good way to test if you are doing it correctly

Hi @hipertracker,

There is clean a way to add this variables to the execution.
This is how you could do it:

schema.execute(query, variable_values={"id": 6})

Hope this helps!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

StefanoSega picture StefanoSega  路  4Comments

Eraldo picture Eraldo  路  3Comments

artofhuman picture artofhuman  路  3Comments

dan-klasson picture dan-klasson  路  4Comments

hyusetiawan picture hyusetiawan  路  4Comments