Reference
GraphQL-core
The primary graphql package includes everything you need to define a GraphQL
schema and fulfill GraphQL requests.
GraphQL-core provides a reference implementation for the GraphQL specification but is also a useful utility for operating on GraphQL files and building sophisticated tools.
This top-level package exports a general purpose function for fulfilling all steps of the GraphQL specification in a single operation, but also includes utilities for every part of the GraphQL specification:
Parsing the GraphQL language.
Building a GraphQL type schema.
Validating a GraphQL request against a type schema.
Executing a GraphQL request against a type schema.
This also includes utility functions for operating on GraphQL types and GraphQL documents to facilitate building tools.
You may also import from each sub-package directly. For example, the following two import statements are equivalent:
from graphql import parse
from graphql.language import parse
The sub-packages of GraphQL-core 3 are:
graphql.language: Parse and operate on the GraphQL language.
graphql.type: Define GraphQL types and schema.
graphql.validation: The Validation phase of fulfilling a GraphQL result.
graphql.execution: The Execution phase of fulfilling a GraphQL request.
graphql.error: Creating and formatting GraphQL errors.
graphql.utilities: Common useful computations upon the GraphQL language and type objects.
Top-Level Functions
- async graphql.graphql(schema: GraphQLSchema, source: str | Source, root_value: Any = None, context_value: Any = None, variable_values: dict[str, Any] | None = None, operation_name: str | None = None, field_resolver: GraphQLFieldResolver | None = None, type_resolver: GraphQLTypeResolver | None = None, middleware: Middleware | None = None, executor_class: type[Executor] | None = None, is_awaitable: Callable[[Any], TypeGuard[Awaitable]] | None = None, is_async_iterable: Callable[[Any], TypeGuard[AsyncIterable]] | None = None, hide_suggestions: bool = False, abort_signal: AbortSignal | None = None, no_location: bool = False, max_tokens: int | None = None, experimental_fragment_arguments: bool = False, rules: Collection[type[ASTValidationRule]] | None = None, max_errors: int | None = None, harness: GraphQLHarness = (<function parse>, <function validate>, <function execute>, <function subscribe>)) ExecutionResult
Execute a GraphQL operation asynchronously.
Parses, validates, and executes a GraphQL document against a schema.
This is the primary entry point for fulfilling GraphQL operations. Use this when you want a single-call request lifecycle that always needs to be awaited.
More sophisticated GraphQL servers, such as those which persist queries, may wish to separate the validation and execution phases to a static-time tooling step and a server runtime step.
This function does not support incremental delivery (
@deferand@stream); useexperimental_execute_incrementally()after parsing and validating when incremental delivery is required.- Parameters:
schema – The schema used for validation or execution.
source – A GraphQL language-formatted string or source object representing the requested operation.
root_value – Initial root value passed to the operation.
context_value – Application context value passed to every resolver. It is made available as the
contextattribute of the resolve info.variable_values – Runtime variable values keyed by variable name.
operation_name – Name of the operation to execute when the document contains multiple operations.
field_resolver – Resolver used when a field does not define its own resolver.
type_resolver – Resolver used when an abstract type does not define its own resolver.
middleware – The middleware to wrap the resolvers with.
executor_class – The executor class to use to build the executor.
is_awaitable – The predicate to be used for checking whether values are awaitable.
is_async_iterable – The predicate to be used for checking whether values are async iterables.
hide_suggestions – Whether suggestion text should be omitted from request errors.
abort_signal – AbortSignal used to cancel execution, e.g. the signal of an
AbortController.no_location – By default, the parser creates AST nodes that know the location in the source that they correspond to. Setting this parameter to
Truedisables that behavior for performance or testing.max_tokens – The maximum number of tokens allowed within the document, to limit the CPU time and memory the parser can burn.
experimental_fragment_arguments – Allows fragment variable definitions and arguments on fragment spreads to be parsed (experimental).
rules – Validation rules to use instead of the specified rules.
max_errors – Maximum number of validation errors before validation stops.
harness – Custom parse, validate, execute, and subscribe functions for this request pipeline. Defaults to
default_harness.
- Returns:
An execution result or validation errors.
Execute a complete asynchronous request with variables:
>>> import asyncio >>> from graphql import graphql, build_schema >>> schema = build_schema(''' ... type Query { ... greeting(name: String!): String ... } ... ''') >>> result = asyncio.run(graphql( ... schema, ... 'query SayHello($name: String!) { greeting(name: $name) }', ... root_value={'greeting': lambda _info, name: f'Hello, {name}!'}, ... variable_values={'name': 'Ada'}, ... operation_name='SayHello', ... )) >>> result ExecutionResult(data={'greeting': 'Hello, Ada!'}, errors=None)
This variant supplies context plus custom field and type resolvers:
>>> schema = build_schema(''' ... interface Named { ... name: String! ... } ... ... type User implements Named { ... name: String! ... } ... ... type Query { ... viewer: Named ... } ... ''') >>> def field_resolver(source, info, **_args): ... assert info.context['locale'] == 'en' ... return source[info.field_name] >>> def type_resolver(value, _info, _abstract_type): ... return 'User' if value['kind'] == 'user' else None >>> result = asyncio.run(graphql( ... schema, ... '{ viewer { __typename name } }', ... root_value={'viewer': {'kind': 'user', 'name': 'Ada'}}, ... context_value={'locale': 'en'}, ... field_resolver=field_resolver, ... type_resolver=type_resolver, ... )) >>> result ExecutionResult(data={'viewer': {'__typename': 'User', 'name': 'Ada'}}, errors=None)
This variant customizes the request pipeline with a harness:
>>> from graphql import AbortController >>> from graphql.harness import default_harness >>> schema = build_schema(''' ... type Query { ... greeting: String ... } ... ''') >>> stages = [] >>> def record_stage(stage): ... def stage_fn(*args, **kwargs): ... stages.append(stage) ... return getattr(default_harness, stage)(*args, **kwargs) ... return stage_fn >>> harness = default_harness._replace( ... parse=record_stage('parse'), ... validate=record_stage('validate'), ... execute=record_stage('execute'), ... subscribe=record_stage('subscribe'), ... ) >>> result = asyncio.run(graphql( ... schema, ... '{ greeting }', ... root_value={'greeting': 'Hello'}, ... rules=[], ... max_errors=25, ... hide_suggestions=True, ... no_location=True, ... abort_signal=AbortController().signal, ... harness=harness, ... )) >>> result ExecutionResult(data={'greeting': 'Hello'}, errors=None) >>> stages ['parse', 'validate', 'execute']
- graphql.graphql_sync(schema: GraphQLSchema, source: str | Source, root_value: Any = None, context_value: Any = None, variable_values: dict[str, Any] | None=None, operation_name: str | None = None, field_resolver: GraphQLFieldResolver | None = None, type_resolver: GraphQLTypeResolver | None = None, middleware: Middleware | None = None, executor_class: type[Executor] | None = None, check_sync: bool = False, hide_suggestions: bool = False, abort_signal: AbortSignal | None = None, no_location: bool = False, max_tokens: int | None = None, experimental_fragment_arguments: bool = False, rules: Collection[type[ASTValidationRule]] | None = None, max_errors: int | None = None, harness: GraphQLHarness = (<function parse>, <function validate>, <function execute>, <function subscribe>)) ExecutionResult
Execute a GraphQL operation synchronously.
Parses, validates, and executes a GraphQL document synchronously.
This function guarantees that execution completes synchronously, or raises an error, assuming that all field resolvers are also synchronous. It raises a
RuntimeErrorwhen execution does not complete synchronously.- Parameters:
schema – The schema used for validation or execution.
source – A GraphQL language-formatted string or source object representing the requested operation.
root_value – Initial root value passed to the operation.
context_value – Application context value passed to every resolver. It is made available as the
contextattribute of the resolve info.variable_values – Runtime variable values keyed by variable name.
operation_name – Name of the operation to execute when the document contains multiple operations.
field_resolver – Resolver used when a field does not define its own resolver.
type_resolver – Resolver used when an abstract type does not define its own resolver.
middleware – The middleware to wrap the resolvers with.
executor_class – The executor class to use to build the executor.
check_sync – Set this to
Trueto still run checks that no awaitable values are returned by resolvers. You can also pass a custom predicate for checking whether values are awaitable.hide_suggestions – Whether suggestion text should be omitted from request errors.
abort_signal – AbortSignal used to cancel execution, e.g. the signal of an
AbortController.no_location – By default, the parser creates AST nodes that know the location in the source that they correspond to. Setting this parameter to
Truedisables that behavior for performance or testing.max_tokens – The maximum number of tokens allowed within the document, to limit the CPU time and memory the parser can burn.
experimental_fragment_arguments – Allows fragment variable definitions and arguments on fragment spreads to be parsed (experimental).
rules – Validation rules to use instead of the specified rules.
max_errors – Maximum number of validation errors before validation stops.
harness – Custom parse, validate, execute, and subscribe functions for this request pipeline. Defaults to
default_harness.
- Returns:
Completed execution output, or request errors if parsing or validation fails.
Execute a complete synchronous request with variables:
>>> from graphql import graphql_sync, build_schema >>> schema = build_schema(''' ... type Query { ... greeting(name: String!): String ... } ... ''') >>> result = graphql_sync( ... schema, ... 'query SayHello($name: String!) { greeting(name: $name) }', ... root_value={'greeting': lambda _info, name: f'Hello, {name}!'}, ... variable_values={'name': 'Ada'}, ... operation_name='SayHello', ... ) >>> result ExecutionResult(data={'greeting': 'Hello, Ada!'}, errors=None)
This variant uses a synchronous custom field resolver and context:
>>> schema = build_schema(''' ... type Query { ... greeting: String ... } ... ''') >>> result = graphql_sync( ... schema, ... '{ greeting }', ... field_resolver=lambda _source, info, **_args: ( ... info.context['default_greeting'] ... ), ... context_value={'default_greeting': 'Hello'}, ... ) >>> result ExecutionResult(data={'greeting': 'Hello'}, errors=None)
Sub-Packages
- Error
- Execution
execute()execute_root_selection_set()experimental_execute_incrementally()execute_sync()default_field_resolver()default_type_resolver()ExecutorExecutionHooksAsyncWorkFinishedInfoAbortedGraphQLExecutionErrorExecutionResultFormattedExecutionResultExperimentalIncrementalExecutionResultsInitialIncrementalExecutionResultFormattedInitialIncrementalExecutionResultSubsequentIncrementalExecutionResultFormattedSubsequentIncrementalExecutionResultIncrementalDeferResultFormattedIncrementalDeferResultIncrementalStreamResultFormattedIncrementalStreamResultIncrementalResultFormattedIncrementalResultPendingResultFormattedPendingResultCompletedResultsubscribe()execute_subscription_event()create_source_event_stream()map_source_to_response_event()map_async_iterable()RootSelectionSetExecutorMiddlewareMiddlewareManagerget_argument_values()get_directive_values()get_variable_values()VariableValues
- Language
- PyUtils
camel_to_snake()snake_to_camel()cached_property()register_description()unregister_description()did_you_mean()identity_func()inspect()is_awaitable()is_async_iterable()is_collection()is_iterable()natural_comparison_key()AbortControllerAbortSignalAbortErrorAwaitableOrValuesuggestion_list()FrozenErrorPathprint_path_list()SimplePubSubSimplePubSubIteratorUndefinedRefMapRefSet
- Type
- Utilities
get_introspection_query()IntrospectionQueryget_operation_ast()introspection_from_schema()build_client_schema()build_ast_schema()build_schema()extend_schema()lexicographic_sort_schema()print_schema()print_type()print_directive()print_introspection_schema()type_from_ast()ast_to_dict()value_from_ast()value_from_ast_untyped()ast_from_value()value_to_literal()replace_variables()get_default_value_ast()TypeInfoTypeInfoVisitorcoerce_input_value()coerce_input_literal()validate_input_value()validate_input_literal()concat_ast()separate_operations()strip_ignored_characters()is_equal_type()is_type_sub_type_of()do_types_overlap()find_schema_changes()find_breaking_changes()find_dangerous_changes()SafeChangeSafeChangeTypeBreakingChangeBreakingChangeTypeDangerousChangeDangerousChangeTypeSchemaChangeresolve_schema_coordinate()resolve_ast_schema_coordinate()ResolvedNamedTypeResolvedFieldResolvedInputFieldResolvedEnumValueResolvedFieldArgumentResolvedDirectiveResolvedDirectiveArgumentResolvedSchemaElement
- Validation