# Execution

GraphQL Execution

The `graphql.execution` package is responsible for the execution phase of fulfilling a GraphQL request.

graphql.execution.execute(schema: GraphQLSchema, document: DocumentNode, root_value: Any = None, context_value: Any = None, variable_values: Dict[str, Any] | None = None, operation_name: str | None = None, field_resolver: Callable[[...], Any] | None = None, type_resolver: Callable[[Any, GraphQLResolveInfo, GraphQLInterfaceType | GraphQLUnionType], Awaitable[str | None] | str | None] | None = None, subscribe_field_resolver: Callable[[...], Any] | None = None, max_coercion_errors: int = 50, middleware: Tuple | List | MiddlewareManager | None = None, execution_context_class: Type[ExecutionContext] | None = None, is_awaitable: Callable[[Any], bool] | None = None) → Awaitable[ExecutionResult] | ExecutionResult

  Execute a GraphQL operation.

  Implements the “Executing requests” section of the GraphQL specification.

  Returns an ExecutionResult (if all encountered resolvers are synchronous), or a coroutine object eventually yielding an ExecutionResult.

  If the arguments to this function do not result in a legal execution context, a GraphQLError will be thrown immediately explaining the invalid input.

graphql.execution.execute_sync(schema: GraphQLSchema, document: DocumentNode, root_value: Any = None, context_value: Any = None, variable_values: Dict[str, Any] | None = None, operation_name: str | None = None, field_resolver: Callable[[...], Any] | None = None, type_resolver: Callable[[Any, GraphQLResolveInfo, GraphQLInterfaceType | GraphQLUnionType], Awaitable[str | None] | str | None] | None = None, max_coercion_errors: int = 50, middleware: Tuple | List | MiddlewareManager | None = None, execution_context_class: Type[ExecutionContext] | None = None, check_sync: bool = False) → ExecutionResult

  Execute a GraphQL operation synchronously.

  Also implements the “Executing requests” section of the GraphQL specification.

  However, it guarantees to complete synchronously (or throw an error) assuming that all field resolvers are also synchronous.

  Set check_sync to True to still run checks that no awaitable values are returned.

graphql.execution.default_field_resolver(source: Any, info: GraphQLResolveInfo, **args: Any) → Any

  Default field resolver.

  If a resolve function is not given, then a default resolve behavior is used which takes the property of the source object of the same name as the field and returns it as the result, or if it’s a function, returns the result of calling that function while passing along args and context.

  For dictionaries, the field names are used as keys, for all other objects they are used as attribute names.

graphql.execution.default_type_resolver(value: Any, info: GraphQLResolveInfo, abstract_type: GraphQLInterfaceType | GraphQLUnionType) → Awaitable[str | None] | str | None

  Default type resolver function.

  If a resolve_type function is not given, then a default resolve behavior is used which attempts two strategies:

  First, See if the provided value has a `__typename` field defined, if so, use that value as name of the resolved type.

  Otherwise, test each possible type for the abstract type by calling `is_type_of()` for the object being coerced, returning the first type that matches.

class graphql.execution.ExecutionContext(schema: GraphQLSchema, fragments: Dict[str, FragmentDefinitionNode], root_value: Any, context_value: Any, operation: OperationDefinitionNode, variable_values: Dict[str, Any], field_resolver: Callable[[...], Any], type_resolver: Callable[[Any, GraphQLResolveInfo, GraphQLInterfaceType | GraphQLUnionType], Awaitable[str | None] | str | None], subscribe_field_resolver: Callable[[...], Any], collected_errors: CollectedErrors, middleware_manager: MiddlewareManager | None, is_awaitable: Callable[[Any], bool] | None)

  Bases: `object`

  Data that must be available at all points during query execution.

  Namely, schema of the type system that is currently executing, and the fragments defined in the query document.

  __init__(schema: GraphQLSchema, fragments: Dict[str, FragmentDefinitionNode], root_value: Any, context_value: Any, operation: OperationDefinitionNode, variable_values: Dict[str, Any], field_resolver: Callable[[...], Any], type_resolver: Callable[[Any, GraphQLResolveInfo, GraphQLInterfaceType | GraphQLUnionType], Awaitable[str | None] | str | None], subscribe_field_resolver: Callable[[...], Any], collected_errors: CollectedErrors, middleware_manager: MiddlewareManager | None, is_awaitable: Callable[[Any], bool] | None) → None
  classmethod build(schema: GraphQLSchema, document: DocumentNode, root_value: Any = None, context_value: Any = None, raw_variable_values: Dict[str, Any] | None = None, operation_name: str | None = None, field_resolver: Callable[[...], Any] | None = None, type_resolver: Callable[[Any, GraphQLResolveInfo, GraphQLInterfaceType | GraphQLUnionType], Awaitable[str | None] | str | None] | None = None, subscribe_field_resolver: Callable[[...], Any] | None = None, max_coercion_errors: int = 50, middleware: Tuple | List | MiddlewareManager | None = None, is_awaitable: Callable[[Any], bool] | None = None) → List[GraphQLError] | ExecutionContext

    Build an execution context

    Constructs a ExecutionContext object from the arguments passed to execute, which we will pass throughout the other execution methods.

    Throws a GraphQLError if a valid execution context cannot be created.

    For internal use only.

  build_resolve_info(field_def: GraphQLField, field_nodes: List[FieldNode], parent_type: GraphQLObjectType, path: Path) → GraphQLResolveInfo

    Build the GraphQLResolveInfo object.

    For internal use only.

  static build_response(data: Dict[str, Any] | None, errors: List[GraphQLError]) → ExecutionResult

    Build response.

    Given a completed execution context and data, build the (data, errors) response defined by the “Response” section of the GraphQL spec.

  collect_subfields(return_type: GraphQLObjectType, field_nodes: List[FieldNode]) → Dict[str, List[FieldNode]]

    Collect subfields.

    A cached collection of relevant subfields with regard to the return type is kept in the execution context as `_subfields_cache`. This ensures the subfields are not repeatedly calculated, which saves overhead when resolving lists of values.

  collected_errors: CollectedErrors
  complete_abstract_value(return_type: GraphQLInterfaceType | GraphQLUnionType, field_nodes: List[FieldNode], info: GraphQLResolveInfo, path: Path, result: Any) → Awaitable[Any] | Any

    Complete an abstract value.

    Complete a value of an abstract type by determining the runtime object type of that value, then complete the value for that type.

  static complete_leaf_value(return_type: GraphQLScalarType | GraphQLEnumType, result: Any) → Any

    Complete a leaf value.

    Complete a Scalar or Enum by serializing to a valid value, returning null if serialization is not possible.

  complete_list_value(return_type: GraphQLList[GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLWrappingType], field_nodes: List[FieldNode], info: GraphQLResolveInfo, path: Path, result: AsyncIterable[Any] | Iterable[Any]) → Awaitable[List[Any]] | List[Any]

    Complete a list value.

    Complete a list value by completing each item in the list with the inner type.

  complete_object_value(return_type: GraphQLObjectType, field_nodes: List[FieldNode], info: GraphQLResolveInfo, path: Path, result: Any) → Awaitable[Dict[str, Any]] | Dict[str, Any]

    Complete an Object value by executing all sub-selections.

  complete_value(return_type: GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLWrappingType, field_nodes: List[FieldNode], info: GraphQLResolveInfo, path: Path, result: Any) → Awaitable[Any] | Any

    Complete a value.

    Implements the instructions for completeValue as defined in the “Value completion” section of the spec.

    If the field type is Non-Null, then this recursively completes the value for the inner type. It throws a field error if that completion returns null, as per the “Nullability” section of the spec.

    If the field type is a List, then this recursively completes the value for the inner type on each item in the list.

    If the field type is a Scalar or Enum, ensures the completed value is a legal value of the type by calling the `serialize` method of GraphQL type definition.

    If the field is an abstract type, determine the runtime type of the value and then complete based on that type.

    Otherwise, the field type expects a sub-selection set, and will complete the value by evaluating all sub-selections.

  context_value: Any
  ensure_valid_runtime_type(runtime_type_name: Any, return_type: GraphQLInterfaceType | GraphQLUnionType, field_nodes: List[FieldNode], info: GraphQLResolveInfo, result: Any) → GraphQLObjectType
  execute_field(parent_type: GraphQLObjectType, source: Any, field_nodes: List[FieldNode], path: Path) → Awaitable[Any] | Any

    Resolve the field on the given source object.

    Implements the “Executing fields” section of the spec.

    In particular, this method figures out the value that the field returns by calling its resolve function, then calls complete_value to await coroutine objects, serialize scalars, or execute the sub-selection-set for objects.

  execute_fields(parent_type: GraphQLObjectType, source_value: Any, path: Path | None, fields: Dict[str, List[FieldNode]]) → Awaitable[Dict[str, Any]] | Dict[str, Any]

    Execute the given fields concurrently.

    Implements the “Executing selection sets” section of the spec for fields that may be executed in parallel.

  execute_fields_serially(parent_type: GraphQLObjectType, source_value: Any, path: Path | None, fields: Dict[str, List[FieldNode]]) → Awaitable[Dict[str, Any]] | Dict[str, Any]

    Execute the given fields serially.

    Implements the “Executing selection sets” section of the spec for fields that must be executed serially.

  execute_operation(operation: OperationDefinitionNode, root_value: Any) → Awaitable[Any] | Any | None

    Execute an operation.

    Implements the “Executing operations” section of the spec.

  field_resolver: Callable[[...], Any]
  fragments: Dict[str, FragmentDefinitionNode]
  handle_field_error(error: GraphQLError, return_type: GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLWrappingType, path: Path) → None
  static is_awaitable(value: Any) → bool

    Return true if object can be passed to an `await` expression.

    Instead of testing if the object is an instance of abc.Awaitable, it checks the existence of an __await__ attribute. This is much faster.

  middleware_manager: MiddlewareManager | None
  operation: OperationDefinitionNode
  root_value: Any
  schema: GraphQLSchema
  subscribe_field_resolver: Callable[[...], Any]
  type_resolver: Callable[[Any, GraphQLResolveInfo, GraphQLInterfaceType | GraphQLUnionType], Awaitable[str | None] | str | None]
  variable_values: Dict[str, Any]

class graphql.execution.ExecutionResult(data: Dict[str, Any] | None = None, errors: List[GraphQLError] | None = None, extensions: Dict[str, Any] | None = None)

  Bases: `object`

  The result of GraphQL execution.

  - `data` is the result of a successful execution of the query.

  - `errors` is included when any errors occurred as a non-empty list.

  - `extensions` is reserved for adding non-standard properties.

  __init__(data: Dict[str, Any] | None = None, errors: List[GraphQLError] | None = None, extensions: Dict[str, Any] | None = None)
  data: Dict[str, Any] | None
  errors: List[GraphQLError] | None
  extensions: Dict[str, Any] | None
  property formatted: FormattedExecutionResult

    Get execution result formatted according to the specification.

class graphql.execution.FormattedExecutionResult

  Bases: `TypedDict`

  Formatted execution result

  data: Dict[str, Any] | None
  errors: List[GraphQLFormattedError]
  extensions: Dict[str, Any]

async graphql.execution.subscribe(schema: GraphQLSchema, document: DocumentNode, root_value: Any = None, context_value: Any = None, variable_values: Dict[str, Any] | None = None, operation_name: str | None = None, field_resolver: Callable[[...], Any] | None = None, subscribe_field_resolver: Callable[[...], Any] | None = None, max_coercion_errors: int = 50) → AsyncIterator[ExecutionResult] | ExecutionResult

  Create a GraphQL subscription.

  Implements the “Subscribe” algorithm described in the GraphQL spec.

  Returns a coroutine object which yields either an AsyncIterator (if successful) or an ExecutionResult (client error). The coroutine will raise an exception if a server error occurs.

  If the client-provided arguments to this function do not result in a compliant subscription, a GraphQL Response (ExecutionResult) with descriptive errors and no data will be returned.

  If the source stream could not be created due to faulty subscription resolver logic or underlying systems, the coroutine object will yield a single ExecutionResult containing `errors` and no `data`.

  If the operation succeeded, the coroutine will yield an AsyncIterator, which yields a stream of ExecutionResults representing the response stream.

async graphql.execution.create_source_event_stream(schema: GraphQLSchema, document: DocumentNode, root_value: Any = None, context_value: Any = None, variable_values: Dict[str, Any] | None = None, operation_name: str | None = None, subscribe_field_resolver: Callable[[...], Any] | None = None, max_coercion_errors: int = 50) → AsyncIterable[Any] | ExecutionResult

  Create source event stream

  Implements the “CreateSourceEventStream” algorithm described in the GraphQL specification, resolving the subscription source event stream.

  Returns a coroutine that yields an AsyncIterable.

  If the client-provided arguments to this function do not result in a compliant subscription, a GraphQL Response (ExecutionResult) with descriptive errors and no data will be returned.

  If the source stream could not be created due to faulty subscription resolver logic or underlying systems, the coroutine object will yield a single ExecutionResult containing `errors` and no `data`.

  A source event stream represents a sequence of events, each of which triggers a GraphQL execution for that event.

  This may be useful when hosting the stateful subscription service in a different process or machine than the stateless GraphQL execution engine, or otherwise separating these two steps. For more on this, see the “Supporting Subscriptions at Scale” information in the GraphQL spec.

class graphql.execution.MapAsyncIterator(iterable: AsyncIterable, callback: Callable)

  Bases: `object`

  Map an AsyncIterable over a callback function.

  Given an AsyncIterable and a callback function, return an AsyncIterator which produces values mapped via calling the callback function.

  When the resulting AsyncIterator is closed, the underlying AsyncIterable will also be closed.

  __init__(iterable: AsyncIterable, callback: Callable) → None
  async aclose() → None

    Close the iterator.

  async athrow(type_: BaseException | Type[BaseException], value: BaseException | None = None, traceback: TracebackType | None = None) → None

    Throw an exception into the asynchronous iterator.

  property is_closed: bool

    Check whether the iterator is closed.

graphql.execution.Middleware

  alias of `Tuple` | `List` | `MiddlewareManager` | `None`

class graphql.execution.MiddlewareManager(*middlewares: Any)

  Bases: `object`

  Manager for the middleware chain.

  This class helps to wrap resolver functions with the provided middleware functions and/or objects. The functions take the next middleware function as first argument. If middleware is provided as an object, it must provide a method `resolve` that is used as the middleware function.

  Note that since resolvers return “AwaitableOrValue”s, all middleware functions must be aware of this and check whether values are awaitable before awaiting them.

  __init__(*middlewares: Any)
  get_field_resolver(field_resolver: Callable[[...], Any]) → Callable[[...], Any]

    Wrap the provided resolver with the middleware.

    Returns a function that chains the middleware functions with the provided resolver function.

  middlewares

graphql.execution.get_directive_values(directive_def: GraphQLDirective, node: DirectiveDefinitionNode | DirectiveExtensionNode | EnumValueDefinitionNode | ExecutableDefinitionNode | FieldDefinitionNode | InputValueDefinitionNode | SelectionNode | SchemaDefinitionNode | TypeDefinitionNode | TypeExtensionNode, variable_values: Dict[str, Any] | None = None) → Dict[str, Any] | None

  Get coerced argument values based on provided nodes.

  Prepares a dict of argument values given a directive definition and an AST node which may contain directives. Optionally also accepts a dict of variable values.

  If the directive does not exist on the node, returns None.

graphql.execution.get_variable_values(schema: GraphQLSchema, var_def_nodes: Collection[VariableDefinitionNode], inputs: Dict[str, Any], max_errors: int | None = None) → List[GraphQLError] | Dict[str, Any]

  Get coerced variable values based on provided definitions.

  Prepares a dict of variable values of the correct type based on the provided variable definitions and arbitrary input. If the input cannot be parsed to match the variable definitions, a GraphQLError will be raised.