2017-04-20 10:53:17 +03:00
Executing a query
=================
For executing a query a schema, you can directly call the `` execute `` method on it.
.. code :: python
2017-04-27 02:27:44 +03:00
2017-04-20 10:53:17 +03:00
schema = graphene.Schema(...)
result = schema.execute('{ name }')
2017-04-27 02:27:44 +03:00
`` result `` represents the result of execution. `` result.data `` is the result of executing the query, `` result.errors `` is `` None `` if no errors occurred, and is a non-empty list if an error occurred.
2017-04-20 10:53:17 +03:00
Context
_______
2018-08-29 12:35:44 +03:00
You can pass context to a query via `` context `` .
2017-04-20 10:53:17 +03:00
.. code :: python
class Query(graphene.ObjectType):
name = graphene.String()
2019-03-28 02:44:41 +03:00
def resolve_name(root, info):
2017-07-27 13:00:21 +03:00
return info.context.get('name')
2017-04-27 02:27:44 +03:00
2017-04-20 10:53:17 +03:00
schema = graphene.Schema(Query)
2018-08-29 12:35:44 +03:00
result = schema.execute('{ name }', context={'name': 'Syrus'})
2017-04-20 10:53:17 +03:00
2017-07-12 19:52:46 +03:00
Variables
2019-03-28 02:44:41 +03:00
_________
2017-07-12 19:52:46 +03:00
2018-08-29 12:35:44 +03:00
You can pass variables to a query via `` variables `` .
2017-07-12 19:52:46 +03:00
.. code :: python
class Query(graphene.ObjectType):
2019-03-28 02:44:41 +03:00
user = graphene.Field(User, id=graphene.ID(required=True))
2017-07-12 19:52:46 +03:00
2019-03-28 02:44:41 +03:00
def resolve_user(root, info, id):
return get_user_by_id(id)
2017-07-12 19:52:46 +03:00
schema = graphene.Schema(Query)
result = schema.execute(
2019-04-08 22:33:29 +03:00
'''
2019-04-08 22:36:35 +03:00
query getUser($id: ID) {
user(id: $id) {
id
firstName
lastName
2017-07-12 19:52:46 +03:00
}
2019-04-08 22:36:35 +03:00
}
2019-04-08 22:33:29 +03:00
''',
2018-08-29 12:35:44 +03:00
variables={'id': 12},
2017-07-12 19:52:46 +03:00
)