0
# Primary Execution Functions
1
2
High-level functions that provide the complete GraphQL execution pipeline including parsing, validation, and execution in a single call. These are the primary entry points for executing GraphQL operations.
3
4
## Capabilities
5
6
### Asynchronous Execution
7
8
Execute GraphQL operations asynchronously, supporting async resolvers and middleware with complete error handling and context management.
9
10
```python { .api }
11
async def graphql(
12
schema: GraphQLSchema,
13
source: Union[str, Source],
14
root_value: Any = None,
15
context_value: Any = None,
16
variable_values: Optional[Dict[str, Any]] = None,
17
operation_name: Optional[str] = None,
18
field_resolver: Optional[GraphQLFieldResolver] = None,
19
type_resolver: Optional[GraphQLTypeResolver] = None,
20
middleware: Optional[Middleware] = None,
21
execution_context_class: Optional[Type[ExecutionContext]] = None,
22
is_awaitable: Optional[Callable[[Any], bool]] = None,
23
) -> ExecutionResult
24
```
25
26
**Parameters:**
27
- `schema`: The GraphQL schema to use for validation and execution
28
- `source`: GraphQL query string or Source object
29
- `root_value`: Initial value passed to root-level resolvers
30
- `context_value`: Context object available to all resolvers via resolve_info.context
31
- `variable_values`: Variable values for parameterized queries
32
- `operation_name`: Operation name when document contains multiple operations
33
- `field_resolver`: Default field resolver function
34
- `type_resolver`: Default type resolver for abstract types
35
- `middleware`: Middleware to wrap resolver execution
36
- `execution_context_class`: Custom execution context class
37
- `is_awaitable`: Function to determine if values are awaitable
38
39
**Returns:** ExecutionResult with data, errors, and extensions
40
41
#### Usage Example
42
43
```python
44
import asyncio
45
from graphql import GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLString, graphql
46
47
schema = GraphQLSchema(
48
query=GraphQLObjectType(
49
name='Query',
50
fields={
51
'hello': GraphQLField(
52
GraphQLString,
53
resolve=lambda obj, info: 'Hello World!'
54
)
55
}
56
)
57
)
58
59
async def main():
60
result = await graphql(schema, '{ hello }')
61
print(result.data) # {'hello': 'Hello World!'}
62
63
asyncio.run(main())
64
```
65
66
### Synchronous Execution
67
68
Execute GraphQL operations synchronously, ensuring all resolvers complete without async behavior for simpler integration patterns.
69
70
```python { .api }
71
def graphql_sync(
72
schema: GraphQLSchema,
73
source: Union[str, Source],
74
root_value: Any = None,
75
context_value: Any = None,
76
variable_values: Optional[Dict[str, Any]] = None,
77
operation_name: Optional[str] = None,
78
field_resolver: Optional[GraphQLFieldResolver] = None,
79
type_resolver: Optional[GraphQLTypeResolver] = None,
80
middleware: Optional[Middleware] = None,
81
execution_context_class: Optional[Type[ExecutionContext]] = None,
82
check_sync: bool = False,
83
) -> ExecutionResult
84
```
85
86
**Parameters:** Same as `graphql()` except:
87
- `check_sync`: If True, validates that no awaitable values are returned from resolvers
88
89
**Returns:** ExecutionResult with data, errors, and extensions
90
91
#### Usage Example
92
93
```python
94
from graphql import GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLString, graphql_sync
95
96
schema = GraphQLSchema(
97
query=GraphQLObjectType(
98
name='Query',
99
fields={
100
'greeting': GraphQLField(
101
GraphQLString,
102
resolve=lambda obj, info, name='World': f'Hello {name}!'
103
)
104
}
105
)
106
)
107
108
# Simple query
109
result = graphql_sync(schema, '{ greeting }')
110
print(result.data) # {'greeting': 'Hello World!'}
111
112
# Query with variables
113
result = graphql_sync(
114
schema,
115
'query($name: String) { greeting(name: $name) }',
116
variable_values={'name': 'GraphQL'}
117
)
118
print(result.data) # {'greeting': 'Hello GraphQL!'}
119
```
120
121
### Execution Results
122
123
All execution functions return ExecutionResult objects containing the query results and any errors encountered.
124
125
```python { .api }
126
class ExecutionResult:
127
data: Optional[Dict[str, Any]]
128
errors: Optional[List[GraphQLError]]
129
extensions: Optional[Dict[str, Any]]
130
131
def __init__(
132
self,
133
data: Optional[Dict[str, Any]] = None,
134
errors: Optional[List[GraphQLError]] = None,
135
extensions: Optional[Dict[str, Any]] = None,
136
)
137
138
class FormattedExecutionResult(TypedDict):
139
data: Optional[Dict[str, Any]]
140
errors: Optional[List[GraphQLFormattedError]]
141
extensions: Optional[Dict[str, Any]]
142
```
143
144
**Properties:**
145
- `data`: Query result data as nested dictionaries, None if execution failed
146
- `errors`: List of GraphQL errors encountered during execution
147
- `extensions`: Additional metadata or debugging information
148
149
#### Error Handling Example
150
151
```python
152
from graphql import graphql_sync, GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLString
153
154
def error_resolver(obj, info):
155
raise Exception("Something went wrong!")
156
157
schema = GraphQLSchema(
158
query=GraphQLObjectType(
159
name='Query',
160
fields={
161
'error': GraphQLField(GraphQLString, resolve=error_resolver),
162
'success': GraphQLField(GraphQLString, resolve=lambda obj, info: 'OK')
163
}
164
)
165
)
166
167
result = graphql_sync(schema, '{ error success }')
168
print(result.data) # {'error': None, 'success': 'OK'}
169
print(len(result.errors)) # 1
170
print(result.errors[0].message) # "Something went wrong!"
171
```
172
173
## Types
174
175
```python { .api }
176
# Import required types
177
from typing import Any, Dict, List, Optional, Union, Callable, Type
178
from graphql.type import GraphQLSchema, GraphQLFieldResolver, GraphQLTypeResolver
179
from graphql.execution import ExecutionContext, Middleware
180
from graphql.language import Source
181
from graphql.error import GraphQLError
182
from graphql.pyutils import AwaitableOrValue
183
184
# Core execution result type
185
ExecutionResult = class ExecutionResult:
186
data: Optional[Dict[str, Any]]
187
errors: Optional[List[GraphQLError]]
188
extensions: Optional[Dict[str, Any]]
189
190
# Formatted result for serialization
191
FormattedExecutionResult = TypedDict('FormattedExecutionResult', {
192
'data': Optional[Dict[str, Any]],
193
'errors': Optional[List[GraphQLFormattedError]],
194
'extensions': Optional[Dict[str, Any]]
195
})
196
197
# Union type for potentially awaitable values
198
AwaitableOrValue = Union[T, Awaitable[T]]
199
```