0
# GraphQL Execution
1
2
Functions for executing GraphQL queries, mutations, and subscriptions with support for both synchronous and asynchronous execution contexts.
3
4
## Capabilities
5
6
### Asynchronous Execution
7
8
Executes GraphQL operations asynchronously, supporting async resolvers and I/O operations.
9
10
```python { .api }
11
async def graphql(
12
schema: GraphQLSchema,
13
data: dict,
14
*,
15
context_value: Optional[Any] = None,
16
root_value: Optional[Any] = None,
17
debug: bool = False,
18
validation_rules: Optional[list] = None,
19
require_query: bool = False,
20
error_formatter: Optional[Callable] = None,
21
extensions: Optional[list[Extension]] = None,
22
middleware: Optional[list] = None,
23
**kwargs
24
) -> dict:
25
"""
26
Execute GraphQL operation asynchronously.
27
28
Parameters:
29
- schema: Executable GraphQL schema
30
- data: Dict containing 'query', optional 'variables', and 'operationName'
31
- context_value: Context object passed to all resolvers
32
- root_value: Root value passed to root resolvers
33
- debug: Enable debug mode for detailed error information
34
- validation_rules: Custom validation rules for the query
35
- require_query: Require 'query' key in data dict
36
- error_formatter: Custom error formatting function
37
- extensions: List of GraphQL extensions to apply
38
- middleware: List of middleware functions
39
40
Returns:
41
Dict with 'data' key and optional 'errors' key containing execution results
42
"""
43
```
44
45
### Synchronous Execution
46
47
Executes GraphQL operations synchronously, suitable for non-async environments.
48
49
```python { .api }
50
def graphql_sync(
51
schema: GraphQLSchema,
52
data: dict,
53
*,
54
context_value: Optional[Any] = None,
55
root_value: Optional[Any] = None,
56
debug: bool = False,
57
validation_rules: Optional[list] = None,
58
require_query: bool = False,
59
error_formatter: Optional[Callable] = None,
60
extensions: Optional[list[Extension]] = None,
61
middleware: Optional[list] = None,
62
**kwargs
63
) -> dict:
64
"""
65
Execute GraphQL operation synchronously.
66
67
Parameters:
68
- schema: Executable GraphQL schema
69
- data: Dict containing 'query', optional 'variables', and 'operationName'
70
- context_value: Context object passed to all resolvers
71
- root_value: Root value passed to root resolvers
72
- debug: Enable debug mode for detailed error information
73
- validation_rules: Custom validation rules for the query
74
- require_query: Require 'query' key in data dict
75
- error_formatter: Custom error formatting function
76
- extensions: List of GraphQL extensions to apply
77
- middleware: List of middleware functions
78
79
Returns:
80
Dict with 'data' key and optional 'errors' key containing execution results
81
"""
82
```
83
84
### Subscription Execution
85
86
Executes GraphQL subscriptions, returning an async iterator for real-time data streaming.
87
88
```python { .api }
89
async def subscribe(
90
schema: GraphQLSchema,
91
data: dict,
92
*,
93
context_value: Optional[Any] = None,
94
root_value: Optional[Any] = None,
95
debug: bool = False,
96
validation_rules: Optional[list] = None,
97
require_query: bool = False,
98
error_formatter: Optional[Callable] = None,
99
extensions: Optional[list[Extension]] = None,
100
middleware: Optional[list] = None,
101
**kwargs
102
):
103
"""
104
Execute GraphQL subscription returning async iterator.
105
106
Parameters:
107
- schema: Executable GraphQL schema
108
- data: Dict containing subscription query, optional 'variables', and 'operationName'
109
- context_value: Context object passed to all resolvers
110
- root_value: Root value passed to root resolvers
111
- debug: Enable debug mode for detailed error information
112
- validation_rules: Custom validation rules for the query
113
- require_query: Require 'query' key in data dict
114
- error_formatter: Custom error formatting function
115
- extensions: List of GraphQL extensions to apply
116
- middleware: List of middleware functions
117
118
Returns:
119
AsyncIterator yielding subscription results or single error dict
120
"""
121
```
122
123
## Usage Examples
124
125
### Basic Query Execution
126
127
```python
128
import asyncio
129
from ariadne import graphql
130
131
async def execute_query():
132
query_data = {
133
"query": """
134
query GetUser($id: ID!) {
135
user(id: $id) {
136
id
137
name
138
139
}
140
}
141
""",
142
"variables": {"id": "123"}
143
}
144
145
result = await graphql(schema, query_data)
146
147
if result.get("errors"):
148
print("Query errors:", result["errors"])
149
else:
150
print("Query result:", result["data"])
151
152
# Run the async function
153
asyncio.run(execute_query())
154
```
155
156
### Synchronous Execution
157
158
```python
159
from ariadne import graphql_sync
160
161
query_data = {
162
"query": """
163
query {
164
hello
165
}
166
"""
167
}
168
169
result = graphql_sync(schema, query_data)
170
print(result) # {"data": {"hello": "Hello, World!"}}
171
```
172
173
### Subscription Execution
174
175
```python
176
import asyncio
177
from ariadne import subscribe
178
179
async def handle_subscription():
180
subscription_data = {
181
"query": """
182
subscription {
183
messageAdded {
184
id
185
content
186
author
187
}
188
}
189
"""
190
}
191
192
async for result in await subscribe(schema, subscription_data):
193
if result.get("errors"):
194
print("Subscription error:", result["errors"])
195
break
196
else:
197
print("New message:", result["data"])
198
199
asyncio.run(handle_subscription())
200
```
201
202
### Execution with Context
203
204
```python
205
from ariadne import graphql
206
207
# Define context with user information
208
context = {
209
"user": {"id": "123", "role": "admin"},
210
"request": request_object
211
}
212
213
result = await graphql(
214
schema,
215
query_data,
216
context_value=context,
217
debug=True # Enable debug mode for development
218
)
219
```
220
221
### Custom Error Formatting
222
223
```python
224
from ariadne import graphql
225
226
def custom_error_formatter(error, debug=False):
227
formatted = {"message": str(error)}
228
229
if debug:
230
formatted["locations"] = error.locations
231
formatted["path"] = error.path
232
233
return formatted
234
235
result = await graphql(
236
schema,
237
query_data,
238
error_formatter=custom_error_formatter,
239
debug=True
240
)
241
```