Debian Codegraph @

docs/usage/queries.rst

raw
1 Executing Queries
2 -----------------
3
4 .. currentmodule:: graphql.execution
5
6 Now that we have defined the schema and breathed life into it with our resolver
7 functions, we can execute arbitrary query against the schema.
8
9 The :mod:`graphql` package provides the :func:`graphql.graphql` function to execute
10 queries. This is the main feature of GraphQL-core.
11
12 Note however that this function is actually a coroutine intended to be used in
13 asynchronous code running in an event loop.
14
15 Here is one way to use it::
16
17 import asyncio
18 from graphql import graphql
19
20 async def query_artoo():
21 result = await graphql(schema, """
22 {
23 droid(id: "2001") {
24 name
25 primaryFunction
26 }
27 }
28 """)
29 print(result)
30
31 asyncio.run(query_artoo())
32
33 In our query, we asked for the droid with the id 2001, which is R2-D2, and its primary
34 function, Astromech. When everything has been implemented correctly as shown above, you
35 should get the expected result::
36
37 ExecutionResult(
38 data={'droid': {'name': 'R2-D2', 'primaryFunction': 'Astromech'}},
39 errors=None)
40
41 The :class:`ExecutionResult` has a ``data`` attribute with the actual result, and an
42 ``errors`` attribute with a list of errors if there were any.
43
44 If all your resolvers work synchronously, as in our case, you can also use the
45 :func:`graphql.graphql_sync` function to query the result in ordinary synchronous code::
46
47 from graphql import graphql_sync
48
49 result = graphql_sync(schema, """
50 query FetchHuman($id: String!) {
51 human(id: $id) {
52 name
53 homePlanet
54 }
55 }
56 """, variable_values={'id': '1000'})
57 print(result)
58
59 Here we asked for the human with the id 1000, Luke Skywalker, and his home planet,
60 Tatooine. So the output of the code above is::
61
62 ExecutionResult(
63 data={'human': {'name': 'Luke Skywalker', 'homePlanet': 'Tatooine'}},
64 errors=None)
65
66 Let's see what happens when we make a mistake in the query, by querying a non-existing
67 ``homeTown`` field::
68
69 result = graphql_sync(schema, """
70 {
71 human(id: "1000") {
72 name
73 homePlace
74 }
75 }
76 """)
77 print(result)
78
79 You will get the following result as output::
80
81 ExecutionResult(data=None, errors=[GraphQLError(
82 "Cannot query field 'homePlace' on type 'Human'. Did you mean 'homePlanet'?",
83 locations=[SourceLocation(line=5, column=9)])])
84
85 This is very helpful. Not only do we get the exact location of the mistake in the query,
86 but also a suggestion for correcting the bad field name.
87
88 GraphQL also allows to request the meta field ``__typename``. We can use this to verify
89 that the hero of "The Empire Strikes Back" episode is Luke Skywalker and that he is in
90 fact a human::
91
92 result = graphql_sync(schema, """
93 {
94 hero(episode: EMPIRE) {
95 __typename
96 name
97 }
98 }
99 """)
100 print(result)
101
102 This gives the following output::
103
104 ExecutionResult(
105 data={'hero': {'__typename': 'Human', 'name': 'Luke Skywalker'}},
106 errors=None)
107
108 Finally, let's see what happens when we try to access the secret backstory of our hero::
109
110 result = graphql_sync(schema, """
111 {
112 hero(episode: EMPIRE) {
113 name
114 secretBackstory
115 }
116 }
117 """)
118 print(result)
119
120 While we get the name of the hero, the secret backstory fields remains empty, since its
121 resolver function raises an error. However, we get the error that has been raised by the
122 resolver in the ``errors`` attribute of the result::
123
124 ExecutionResult(
125 data={'hero': {'name': 'Luke Skywalker', 'secretBackstory': None}},
126 errors=[GraphQLError('secretBackstory is secret.',
127 locations=[SourceLocation(line=5, column=9)],
128 path=['hero', 'secretBackstory'])])
129