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:

async graphql.graphql(schema: graphql.type.schema.GraphQLSchema, source: Union[str, graphql.language.source.Source], root_value: Any = None, context_value: Any = None, variable_values: Optional[Dict[str, Any]] = None, operation_name: Optional[str] = None, field_resolver: Optional[Callable[[...], Any]] = None, type_resolver: Optional[Callable[[Any, graphql.type.definition.GraphQLResolveInfo, GraphQLAbstractType], Union[Awaitable[Union[GraphQLObjectType, str, None]], GraphQLObjectType, str, None]]] = None, middleware: Union[Tuple, List, graphql.execution.middleware.MiddlewareManager, None] = None, execution_context_class: Type[graphql.execution.execute.ExecutionContext] = <class 'graphql.execution.execute.ExecutionContext'>) → graphql.execution.execute.ExecutionResult

Execute a GraphQL operation asynchronously.

This is the primary entry point function for fulfilling GraphQL operations by parsing, validating, and executing a GraphQL document along side a GraphQL schema.

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.

Accepts the following arguments:

Parameters
  • schema – The GraphQL type system to use when validating and executing a query.

  • source – A GraphQL language formatted string representing the requested operation.

  • root_value – The value provided as the first argument to resolver functions on the top level type (e.g. the query object type).

  • context_value – The context value is provided as an attribute of the second argument (the resolve info) to resolver functions. It is used to pass shared information useful at any point during query execution, for example the currently logged in user and connections to databases or other services.

  • variable_values – A mapping of variable name to runtime value to use for all variables defined in the request string.

  • operation_name – The name of the operation to use if request string contains multiple possible operations. Can be omitted if request string contains only one operation.

  • field_resolver – A resolver function to use when one is not provided by the schema. If not provided, the default field resolver is used (which looks for a value or method on the source value with the field’s name).

  • type_resolver – A type resolver function to use when none is provided by the schema. If not provided, the default type resolver is used (which looks for a __typename field or alternatively calls the is_type_of method).

  • middleware – The middleware to wrap the resolvers with

  • execution_context_class – The execution context class to use to build the context

graphql.graphql_sync(schema: graphql.type.schema.GraphQLSchema, source: Union[str, graphql.language.source.Source], root_value: Any = None, context_value: Any = None, variable_values: Optional[Dict[str, Any]] = None, operation_name: Optional[str] = None, field_resolver: Optional[Callable[[...], Any]] = None, type_resolver: Optional[Callable[[Any, graphql.type.definition.GraphQLResolveInfo, GraphQLAbstractType], Union[Awaitable[Union[GraphQLObjectType, str, None]], GraphQLObjectType, str, None]]] = None, middleware: Union[Tuple, List, graphql.execution.middleware.MiddlewareManager, None] = None, execution_context_class: Type[graphql.execution.execute.ExecutionContext] = <class 'graphql.execution.execute.ExecutionContext'>) → graphql.execution.execute.ExecutionResult

Execute a GraphQL operation synchronously.

The graphql_sync function also fulfills GraphQL operations by parsing, validating, and executing a GraphQL document along side a GraphQL schema. However, it guarantees to complete synchronously (or throw an error) assuming that all field resolvers are also synchronous.

class graphql.GraphQLSchema(query: Optional[graphql.type.definition.GraphQLObjectType] = None, mutation: Optional[graphql.type.definition.GraphQLObjectType] = None, subscription: Optional[graphql.type.definition.GraphQLObjectType] = None, types: Optional[Collection[graphql.type.definition.GraphQLNamedType]] = None, directives: Optional[Collection[graphql.type.directives.GraphQLDirective]] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.SchemaDefinitionNode] = None, extension_ast_nodes: Optional[Collection[graphql.language.ast.SchemaExtensionNode]] = None, assume_valid: bool = False)

Bases: object

Schema Definition

A Schema is created by supplying the root types of each type of operation, query and mutation (optional). A schema definition is then supplied to the validator and executor.

Example:

MyAppSchema = GraphQLSchema(
  query=MyAppQueryRootType,
  mutation=MyAppMutationRootType)

Note: When the schema is constructed, by default only the types that are reachable by traversing the root types are included, other types must be explicitly referenced.

Example:

character_interface = GraphQLInterfaceType('Character', ...)

human_type = GraphQLObjectType(
    'Human', interfaces=[character_interface], ...)

droid_type = GraphQLObjectType(
    'Droid', interfaces: [character_interface], ...)

schema = GraphQLSchema(
    query=GraphQLObjectType('Query',
        fields={'hero': GraphQLField(character_interface, ....)}),
    ...
    # Since this schema references only the `Character` interface it's
    # necessary to explicitly list the types that implement it if
    # you want them to be included in the final schema.
    types=[human_type, droid_type])

Note: If a list of directives is provided to GraphQLSchema, that will be the exact list of directives represented and allowed. If directives is not provided, then a default set of the specified directives (e.g. @include and @skip) will be used. If you wish to provide additional directives to these specified directives, you must explicitly declare them. Example:

MyAppSchema = GraphQLSchema(
  ...
  directives=specified_directives + [my_custom_directive])
__init__(query: Optional[graphql.type.definition.GraphQLObjectType] = None, mutation: Optional[graphql.type.definition.GraphQLObjectType] = None, subscription: Optional[graphql.type.definition.GraphQLObjectType] = None, types: Optional[Collection[graphql.type.definition.GraphQLNamedType]] = None, directives: Optional[Collection[graphql.type.directives.GraphQLDirective]] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.SchemaDefinitionNode] = None, extension_ast_nodes: Optional[Collection[graphql.language.ast.SchemaExtensionNode]] = None, assume_valid: bool = False) → None

Initialize GraphQL schema.

If this schema was built from a source known to be valid, then it may be marked with assume_valid to avoid an additional type system validation. Otherwise check for common mistakes during construction to produce clear and early error messages.

_implementations: Dict[str, InterfaceImplementations] = None
_sub_type_map: Dict[str, Set[str]] = None
ast_node: Optional[ast.SchemaDefinitionNode] = None
directives: FrozenList[GraphQLDirective] = None
extension_ast_nodes: Optional[FrozenList[ast.SchemaExtensionNode]] = None
extensions: Optional[Dict[str, Any]] = None
get_directive(name: str) → Optional[graphql.type.directives.GraphQLDirective]
get_implementations(interface_type: graphql.type.definition.GraphQLInterfaceType) → graphql.type.schema.InterfaceImplementations
get_possible_types(abstract_type: Union[graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType]) → List[graphql.type.definition.GraphQLObjectType]

Get list of all possible concrete types for given abstract type.

get_type(name: str) → Optional[graphql.type.definition.GraphQLNamedType]
is_possible_type(abstract_type: Union[graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType], possible_type: graphql.type.definition.GraphQLObjectType) → bool

Check whether a concrete type is possible for an abstract type.

Deprecated: Use is_sub_type() instead.

is_sub_type(abstract_type: Union[graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType], maybe_sub_type: Union[graphql.type.definition.GraphQLObjectType, graphql.type.definition.GraphQLInterfaceType]) → bool

Check whether a type is a subtype of a given abstract type.

mutation_type: Optional[GraphQLObjectType] = None
query_type: Optional[GraphQLObjectType] = None
subscription_type: Optional[GraphQLObjectType] = None
to_kwargs() → Dict[str, Any]
type_map: TypeMap = None
type_map_directive_reducer(map_: Dict[str, graphql.type.definition.GraphQLNamedType], directive: Optional[graphql.type.directives.GraphQLDirective] = None) → Dict[str, graphql.type.definition.GraphQLNamedType]

Reducer function for creating the type map from given directives.

type_map_reducer(map_: Dict[str, graphql.type.definition.GraphQLNamedType], type_: Optional[graphql.type.definition.GraphQLNamedType] = None) → Dict[str, graphql.type.definition.GraphQLNamedType]

Reducer function for creating the type map from given types.

property validation_errors
class graphql.GraphQLDirective(name: str, locations: Collection[graphql.language.directive_locations.DirectiveLocation], args: Optional[Dict[str, graphql.type.definition.GraphQLArgument]] = None, is_repeatable: bool = False, description: Optional[str] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.DirectiveDefinitionNode] = None)

Bases: object

GraphQL Directive

Directives are used by the GraphQL runtime as a way of modifying execution behavior. Type system creators will usually not create these directly.

__init__(name: str, locations: Collection[graphql.language.directive_locations.DirectiveLocation], args: Optional[Dict[str, graphql.type.definition.GraphQLArgument]] = None, is_repeatable: bool = False, description: Optional[str] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.DirectiveDefinitionNode] = None) → None

Initialize self. See help(type(self)) for accurate signature.

args: Dict[str, GraphQLArgument] = None
ast_node: Optional[ast.DirectiveDefinitionNode] = None
description: Optional[str] = None
extensions: Optional[Dict[str, Any]] = None
is_repeatable: bool = None
locations: List[DirectiveLocation] = None
name: str = None
to_kwargs() → Dict[str, Any]
class graphql.GraphQLScalarType(name: str, serialize: Optional[Callable] = None, parse_value: Optional[Callable] = None, parse_literal: Optional[Callable] = None, description: Optional[str] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.ScalarTypeDefinitionNode] = None, extension_ast_nodes: Optional[Collection[graphql.language.ast.ScalarTypeExtensionNode]] = None)

Bases: graphql.type.definition.GraphQLNamedType

Scalar Type Definition

The leaf values of any request and input values to arguments are Scalars (or Enums) and are defined with a name and a series of functions used to parse input from ast or variables and to ensure validity.

If a type’s serialize function does not return a value (i.e. it returns None), then no error will be included in the response.

Example:

def serialize_odd(value):
if value % 2 == 1:

return value

odd_type = GraphQLScalarType(‘Odd’, serialize=serialize_odd)

__init__(name: str, serialize: Optional[Callable] = None, parse_value: Optional[Callable] = None, parse_literal: Optional[Callable] = None, description: Optional[str] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.ScalarTypeDefinitionNode] = None, extension_ast_nodes: Optional[Collection[graphql.language.ast.ScalarTypeExtensionNode]] = None) → None

Initialize self. See help(type(self)) for accurate signature.

ast_node: Optional[ScalarTypeDefinitionNode] = None
extension_ast_nodes: Optional[FrozenList[ScalarTypeExtensionNode]] = None
parse_literal(node: graphql.language.ast.ValueNode, _variables: Optional[Dict[str, Any]] = None) → Any

Parses an externally provided literal value to use as an input.

This default method uses the parse_value method and should be replaced with a more specific version when creating a scalar type.

static parse_value(value: Any) → Any

Parses an externally provided value to use as an input.

This default method just passes the value through and should be replaced with a more specific version when creating a scalar type.

static serialize(value: Any) → Any

Serializes an internal value to include in a response.

This default method just passes the value through and should be replaced with a more specific version when creating a scalar type.

to_kwargs() → Dict[str, Any]
class graphql.GraphQLObjectType(name: str, fields: Union[Callable[[], Dict[str, graphql.type.definition.GraphQLField]], Dict[str, graphql.type.definition.GraphQLField]], interfaces: Union[Callable[[], Collection[GraphQLInterfaceType]], Collection[GraphQLInterfaceType], None] = None, is_type_of: Optional[Callable[[Any, graphql.type.definition.GraphQLResolveInfo], Union[Awaitable[bool], bool]]] = None, extensions: Optional[Dict[str, Any]] = None, description: Optional[str] = None, ast_node: Optional[graphql.language.ast.ObjectTypeDefinitionNode] = None, extension_ast_nodes: Optional[Collection[graphql.language.ast.ObjectTypeExtensionNode]] = None)

Bases: graphql.type.definition.GraphQLNamedType

Object Type Definition

Almost all of the GraphQL types you define will be object types. Object types have a name, but most importantly describe their fields.

Example:

AddressType = GraphQLObjectType('Address', {
    'street': GraphQLField(GraphQLString),
    'number': GraphQLField(GraphQLInt),
    'formatted': GraphQLField(GraphQLString,
        lambda obj, info, **args: f'{obj.number} {obj.street}')
})

When two types need to refer to each other, or a type needs to refer to itself in a field, you can use a lambda function with no arguments (a so-called “thunk”) to supply the fields lazily.

Example:

PersonType = GraphQLObjectType('Person', lambda: {
    'name': GraphQLField(GraphQLString),
    'bestFriend': GraphQLField(PersonType)
})
__init__(name: str, fields: Union[Callable[[], Dict[str, graphql.type.definition.GraphQLField]], Dict[str, graphql.type.definition.GraphQLField]], interfaces: Union[Callable[[], Collection[GraphQLInterfaceType]], Collection[GraphQLInterfaceType], None] = None, is_type_of: Optional[Callable[[Any, graphql.type.definition.GraphQLResolveInfo], Union[Awaitable[bool], bool]]] = None, extensions: Optional[Dict[str, Any]] = None, description: Optional[str] = None, ast_node: Optional[graphql.language.ast.ObjectTypeDefinitionNode] = None, extension_ast_nodes: Optional[Collection[graphql.language.ast.ObjectTypeExtensionNode]] = None) → None

Initialize self. See help(type(self)) for accurate signature.

ast_node: Optional[ObjectTypeDefinitionNode] = None
extension_ast_nodes: Optional[FrozenList[ObjectTypeExtensionNode]] = None
fields

Get provided fields, wrapping them as GraphQLFields if needed.

interfaces

Get provided interfaces.

is_type_of: Optional[GraphQLIsTypeOfFn] = None
to_kwargs() → Dict[str, Any]
class graphql.GraphQLInterfaceType(name: str, fields: Union[Callable[[], Dict[str, graphql.type.definition.GraphQLField]], Dict[str, graphql.type.definition.GraphQLField], None] = None, interfaces: Union[Callable[[], Collection[GraphQLInterfaceType]], Collection[GraphQLInterfaceType], None] = None, resolve_type: Optional[Callable[[Any, graphql.type.definition.GraphQLResolveInfo, GraphQLAbstractType], Union[Awaitable[Union[GraphQLObjectType, str, None]], GraphQLObjectType, str, None]]] = None, description: Optional[str] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.InterfaceTypeDefinitionNode] = None, extension_ast_nodes: Optional[Collection[graphql.language.ast.InterfaceTypeExtensionNode]] = None)

Bases: graphql.type.definition.GraphQLNamedType

Interface Type Definition

When a field can return one of a heterogeneous set of types, an Interface type is used to describe what types are possible, what fields are in common across all types, as well as a function to determine which type is actually used when the field is resolved.

Example:

EntityType = GraphQLInterfaceType('Entity', {
        'name': GraphQLField(GraphQLString),
    })
__init__(name: str, fields: Union[Callable[[], Dict[str, graphql.type.definition.GraphQLField]], Dict[str, graphql.type.definition.GraphQLField], None] = None, interfaces: Union[Callable[[], Collection[GraphQLInterfaceType]], Collection[GraphQLInterfaceType], None] = None, resolve_type: Optional[Callable[[Any, graphql.type.definition.GraphQLResolveInfo, GraphQLAbstractType], Union[Awaitable[Union[GraphQLObjectType, str, None]], GraphQLObjectType, str, None]]] = None, description: Optional[str] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.InterfaceTypeDefinitionNode] = None, extension_ast_nodes: Optional[Collection[graphql.language.ast.InterfaceTypeExtensionNode]] = None) → None

Initialize self. See help(type(self)) for accurate signature.

ast_node: Optional[InterfaceTypeDefinitionNode] = None
extension_ast_nodes: Optional[FrozenList[InterfaceTypeExtensionNode]] = None
fields

Get provided fields, wrapping them as GraphQLFields if needed.

interfaces

Get provided interfaces.

resolve_type: Optional[GraphQLTypeResolver] = None
to_kwargs() → Dict[str, Any]
class graphql.GraphQLUnionType(name, types: Union[Callable[[], Collection[graphql.type.definition.GraphQLObjectType]], Collection[graphql.type.definition.GraphQLObjectType]], resolve_type: Optional[Callable[[Any, graphql.type.definition.GraphQLResolveInfo, GraphQLAbstractType], Union[Awaitable[Union[GraphQLObjectType, str, None]], GraphQLObjectType, str, None]]] = None, description: Optional[str] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.UnionTypeDefinitionNode] = None, extension_ast_nodes: Optional[Collection[graphql.language.ast.UnionTypeExtensionNode]] = None)

Bases: graphql.type.definition.GraphQLNamedType

Union Type Definition

When a field can return one of a heterogeneous set of types, a Union type is used to describe what types are possible as well as providing a function to determine which type is actually used when the field is resolved.

Example:

class PetType(GraphQLUnionType):

name = ‘Pet’ types = [DogType, CatType]

def resolve_type(self, value, _type):
if isinstance(value, Dog):

return DogType()

if isinstance(value, Cat):

return CatType()

__init__(name, types: Union[Callable[[], Collection[graphql.type.definition.GraphQLObjectType]], Collection[graphql.type.definition.GraphQLObjectType]], resolve_type: Optional[Callable[[Any, graphql.type.definition.GraphQLResolveInfo, GraphQLAbstractType], Union[Awaitable[Union[GraphQLObjectType, str, None]], GraphQLObjectType, str, None]]] = None, description: Optional[str] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.UnionTypeDefinitionNode] = None, extension_ast_nodes: Optional[Collection[graphql.language.ast.UnionTypeExtensionNode]] = None) → None

Initialize self. See help(type(self)) for accurate signature.

ast_node: Optional[UnionTypeDefinitionNode] = None
extension_ast_nodes: Optional[FrozenList[UnionTypeExtensionNode]] = None
resolve_type: Optional[GraphQLTypeResolver] = None
to_kwargs() → Dict[str, Any]
types

Get provided types.

class graphql.GraphQLEnumType(name: str, values: Union[Dict[str, GraphQLEnumValue], Dict[str, Any], Type[enum.Enum]], description: Optional[str] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.EnumTypeDefinitionNode] = None, extension_ast_nodes: Optional[Collection[graphql.language.ast.EnumTypeExtensionNode]] = None)

Bases: graphql.type.definition.GraphQLNamedType

Enum Type Definition

Some leaf values of requests and input values are Enums. GraphQL serializes Enum values as strings, however internally Enums can be represented by any kind of type, often integers. They can also be provided as a Python Enum.

Example:

RGBType = GraphQLEnumType('RGB', {
    'RED': 0,
    'GREEN': 1,
    'BLUE': 2
})

Example using a Python Enum:

class RGBEnum(enum.Enum):
    RED = 0
    GREEN = 1
    BLUE = 2

RGBType = GraphQLEnumType('RGB', enum.Enum)

Instead of raw values, you can also specify GraphQLEnumValue objects with more detail like description or deprecation information.

Note: If a value is not provided in a definition, the name of the enum value will be used as its internal value when the value is serialized.

__init__(name: str, values: Union[Dict[str, GraphQLEnumValue], Dict[str, Any], Type[enum.Enum]], description: Optional[str] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.EnumTypeDefinitionNode] = None, extension_ast_nodes: Optional[Collection[graphql.language.ast.EnumTypeExtensionNode]] = None) → None

Initialize self. See help(type(self)) for accurate signature.

_value_lookup
ast_node: Optional[EnumTypeDefinitionNode] = None
extension_ast_nodes: Optional[FrozenList[EnumTypeExtensionNode]] = None
parse_literal(value_node: graphql.language.ast.ValueNode, _variables: Optional[Dict[str, Any]] = None) → Any
parse_value(input_value: str) → Any
serialize(output_value: Any) → str
to_kwargs() → Dict[str, Any]
values: GraphQLEnumValueMap = None
class graphql.GraphQLInputObjectType(name: str, fields: Union[Callable[[], Dict[str, GraphQLInputField]], Dict[str, GraphQLInputField]], description: Optional[str] = None, out_type: Optional[Callable[[Dict[str, Any]], Any]] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.InputObjectTypeDefinitionNode] = None, extension_ast_nodes: Optional[Collection[graphql.language.ast.InputObjectTypeExtensionNode]] = None)

Bases: graphql.type.definition.GraphQLNamedType

Input Object Type Definition

An input object defines a structured collection of fields which may be supplied to a field argument.

Using NonNull will ensure that a value must be provided by the query.

Example:

NonNullFloat = GraphQLNonNull(GraphQLFloat())

class GeoPoint(GraphQLInputObjectType):
    name = 'GeoPoint'
    fields = {
        'lat': GraphQLInputField(NonNullFloat),
        'lon': GraphQLInputField(NonNullFloat),
        'alt': GraphQLInputField(
                  GraphQLFloat(), default_value=0)
    }

The outbound values will be Python dictionaries by default, but you can have them converted to other types by specifying an out_type function or class.

__init__(name: str, fields: Union[Callable[[], Dict[str, GraphQLInputField]], Dict[str, GraphQLInputField]], description: Optional[str] = None, out_type: Optional[Callable[[Dict[str, Any]], Any]] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.InputObjectTypeDefinitionNode] = None, extension_ast_nodes: Optional[Collection[graphql.language.ast.InputObjectTypeExtensionNode]] = None) → None

Initialize self. See help(type(self)) for accurate signature.

ast_node: Optional[InputObjectTypeDefinitionNode] = None
extension_ast_nodes: Optional[FrozenList[InputObjectTypeExtensionNode]] = None
fields

Get provided fields, wrap them as GraphQLInputField if needed.

static out_type(value: Dict[str, Any]) → Any

Transform outbound values (this is an extension of GraphQL.js).

This default implementation passes values unaltered as dictionaries.

to_kwargs() → Dict[str, Any]
class graphql.GraphQLList(type_: GT)

Bases: graphql.type.definition.GraphQLWrappingType

List Type Wrapper

A list is a wrapping type which points to another type. Lists are often created within the context of defining the fields of an object type.

Example:

class PersonType(GraphQLObjectType):
    name = 'Person'

    @property
    def fields(self):
        return {
            'parents': GraphQLField(GraphQLList(PersonType())),
            'children': GraphQLField(GraphQLList(PersonType())),
        }
__init__(type_: GT)

Initialize self. See help(type(self)) for accurate signature.

of_type = None
class graphql.GraphQLNonNull(type_: GNT)

Bases: graphql.type.definition.GraphQLWrappingType, typing.Generic

Non-Null Type Wrapper

A non-null is a wrapping type which points to another type. Non-null types enforce that their values are never null and can ensure an error is raised if this ever occurs during a request. It is useful for fields which you can make a strong guarantee on non-nullability, for example usually the id field of a database row will never be null.

Example:

class RowType(GraphQLObjectType):
    name = 'Row'
    fields = {
        'id': GraphQLField(GraphQLNonNull(GraphQLString()))
    }

Note: the enforcement of non-nullability occurs within the executor.

__init__(type_: GNT)

Initialize self. See help(type(self)) for accurate signature.

of_type = None
class graphql.TypeKind

Bases: enum.Enum

An enumeration.

ENUM = 'enum'
INPUT_OBJECT = 'input object'
INTERFACE = 'interface'
LIST = 'list'
NON_NULL = 'non-null'
OBJECT = 'object'
SCALAR = 'scalar'
UNION = 'union'
graphql.is_schema(schema: Any) → bool

Test if the given value is a GraphQL schema.

graphql.is_directive(directive: Any) → bool

Test if the given value is a GraphQL directive.

graphql.is_type(type_: Any) → bool
graphql.is_scalar_type(type_: Any) → bool
graphql.is_object_type(type_: Any) → bool
graphql.is_interface_type(type_: Any) → bool
graphql.is_union_type(type_: Any) → bool
graphql.is_enum_type(type_: Any) → bool
graphql.is_input_object_type(type_: Any) → bool
graphql.is_list_type(type_: Any) → bool
graphql.is_non_null_type(type_: Any) → bool
graphql.is_input_type(type_: Any) → bool
graphql.is_output_type(type_: Any) → bool
graphql.is_leaf_type(type_: Any) → bool
graphql.is_composite_type(type_: Any) → bool
graphql.is_abstract_type(type_: Any) → bool
graphql.is_wrapping_type(type_: Any) → bool
graphql.is_nullable_type(type_: Any) → bool
graphql.is_named_type(type_: Any) → bool
graphql.is_required_argument(arg: graphql.type.definition.GraphQLArgument) → bool
graphql.is_required_input_field(field: graphql.type.definition.GraphQLInputField) → bool
graphql.is_specified_scalar_type(type_: graphql.type.definition.GraphQLNamedType) → bool

Check whether the given named GraphQL type is a specified scalar type.

graphql.is_introspection_type(type_: graphql.type.definition.GraphQLNamedType) → bool

Check whether the given named GraphQL type is an introspection type.

graphql.is_specified_directive(directive: graphql.type.directives.GraphQLDirective) → bool

Check whether the given directive is one of the specified directives.

graphql.assert_schema(schema: Any) → graphql.type.schema.GraphQLSchema
graphql.assert_directive(directive: Any) → graphql.type.directives.GraphQLDirective
graphql.assert_type(type_: Any) → graphql.type.definition.GraphQLType
graphql.assert_scalar_type(type_: Any) → graphql.type.definition.GraphQLScalarType
graphql.assert_object_type(type_: Any) → graphql.type.definition.GraphQLObjectType
graphql.assert_interface_type(type_: Any) → graphql.type.definition.GraphQLInterfaceType
graphql.assert_union_type(type_: Any) → graphql.type.definition.GraphQLUnionType
graphql.assert_enum_type(type_: Any) → graphql.type.definition.GraphQLEnumType
graphql.assert_input_object_type(type_: Any) → graphql.type.definition.GraphQLInputObjectType
graphql.assert_list_type(type_: Any) → graphql.type.definition.GraphQLList
graphql.assert_non_null_type(type_: Any) → graphql.type.definition.GraphQLNonNull
graphql.assert_input_type(type_: Any) → Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLInputObjectType, graphql.type.definition.GraphQLWrappingType]
graphql.assert_output_type(type_: Any) → Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLObjectType, graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLWrappingType]
graphql.assert_leaf_type(type_: Any) → Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLEnumType]
graphql.assert_composite_type(type_: Any) → graphql.type.definition.GraphQLType
graphql.assert_abstract_type(type_: Any) → Union[graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType]
graphql.assert_wrapping_type(type_: Any) → graphql.type.definition.GraphQLWrappingType
graphql.assert_nullable_type(type_: Any) → Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLObjectType, graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLInputObjectType, graphql.type.definition.GraphQLList]
graphql.assert_named_type(type_: Any) → graphql.type.definition.GraphQLNamedType
graphql.get_nullable_type(type_)

Unwrap possible non-null type

graphql.get_named_type(type_)

Unwrap possible wrapping type

graphql.validate_schema(schema: graphql.type.schema.GraphQLSchema) → List[graphql.error.graphql_error.GraphQLError]

Validate a GraphQL schema.

Implements the “Type Validation” sub-sections of the specification’s “Type System” section.

Validation runs synchronously, returning a list of encountered errors, or an empty list if no errors were encountered and the Schema is valid.

graphql.assert_valid_schema(schema: graphql.type.schema.GraphQLSchema) → None

Utility function which asserts a schema is valid.

Throws a TypeError if the schema is invalid.

class graphql.GraphQLType

Bases: object

Base class for all GraphQL types

__init__()

Initialize self. See help(type(self)) for accurate signature.

class graphql.GraphQLWrappingType(type_: GT)

Bases: graphql.type.definition.GraphQLType, typing.Generic

Base class for all GraphQL wrapping types

__init__(type_: GT)

Initialize self. See help(type(self)) for accurate signature.

of_type: GT = None
class graphql.GraphQLNamedType(name: str, description: Optional[str] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.TypeDefinitionNode] = None, extension_ast_nodes: Optional[Collection[graphql.language.ast.TypeExtensionNode]] = None)

Bases: graphql.type.definition.GraphQLType

Base class for all GraphQL named types

__init__(name: str, description: Optional[str] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.TypeDefinitionNode] = None, extension_ast_nodes: Optional[Collection[graphql.language.ast.TypeExtensionNode]] = None) → None

Initialize self. See help(type(self)) for accurate signature.

ast_node: Optional[TypeDefinitionNode] = None
description: Optional[str] = None
extension_ast_nodes: Optional[FrozenList[TypeExtensionNode]] = None
extensions: Optional[Dict[str, Any]] = None
name: str = None
to_kwargs() → Dict[str, Any]
class graphql.GraphQLArgument(type_: Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLInputObjectType, graphql.type.definition.GraphQLWrappingType], default_value: Any = Undefined, description: Optional[str] = None, out_name: Optional[str] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.InputValueDefinitionNode] = None)

Bases: object

Definition of a GraphQL argument

__init__(type_: Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLInputObjectType, graphql.type.definition.GraphQLWrappingType], default_value: Any = Undefined, description: Optional[str] = None, out_name: Optional[str] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.InputValueDefinitionNode] = None) → None

Initialize self. See help(type(self)) for accurate signature.

ast_node: Optional[InputValueDefinitionNode] = None
default_value: Any = None
description: Optional[str] = None
extensions: Optional[Dict[str, Any]] = None
out_name: Optional[str] = None
to_kwargs() → Dict[str, Any]
type: 'GraphQLInputType' = None
class graphql.GraphQLEnumValue(value: Any = None, description: Optional[str] = None, deprecation_reason: Optional[str] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.EnumValueDefinitionNode] = None)

Bases: object

__init__(value: Any = None, description: Optional[str] = None, deprecation_reason: Optional[str] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.EnumValueDefinitionNode] = None) → None

Initialize self. See help(type(self)) for accurate signature.

ast_node: Optional[EnumValueDefinitionNode] = None
deprecation_reason: Optional[str] = None
description: Optional[str] = None
extensions: Optional[Dict[str, Any]] = None
property is_deprecated
to_kwargs() → Dict[str, Any]
value: Any = None
class graphql.GraphQLField(type_: Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLObjectType, graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLWrappingType], args: Optional[Dict[str, GraphQLArgument]] = None, resolve: Optional[GraphQLFieldResolver] = None, subscribe: Optional[GraphQLFieldResolver] = None, description: Optional[str] = None, deprecation_reason: Optional[str] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.FieldDefinitionNode] = None)

Bases: object

Definition of a GraphQL field

__init__(type_: Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLObjectType, graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLWrappingType], args: Optional[Dict[str, GraphQLArgument]] = None, resolve: Optional[GraphQLFieldResolver] = None, subscribe: Optional[GraphQLFieldResolver] = None, description: Optional[str] = None, deprecation_reason: Optional[str] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.FieldDefinitionNode] = None) → None

Initialize self. See help(type(self)) for accurate signature.

args: GraphQLArgumentMap = None
ast_node: Optional[FieldDefinitionNode] = None
deprecation_reason: Optional[str] = None
description: Optional[str] = None
extensions: Optional[Dict[str, Any]] = None
property is_deprecated
resolve: Optional['GraphQLFieldResolver'] = None
subscribe: Optional['GraphQLFieldResolver'] = None
to_kwargs() → Dict[str, Any]
type: 'GraphQLOutputType' = None
class graphql.GraphQLInputField(type_: Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLInputObjectType, graphql.type.definition.GraphQLWrappingType], default_value: Any = Undefined, description: Optional[str] = None, out_name: Optional[str] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.InputValueDefinitionNode] = None)

Bases: object

Definition of a GraphQL input field

__init__(type_: Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLInputObjectType, graphql.type.definition.GraphQLWrappingType], default_value: Any = Undefined, description: Optional[str] = None, out_name: Optional[str] = None, extensions: Optional[Dict[str, Any]] = None, ast_node: Optional[graphql.language.ast.InputValueDefinitionNode] = None) → None

Initialize self. See help(type(self)) for accurate signature.

ast_node: Optional[InputValueDefinitionNode] = None
default_value: Any = None
description: Optional[str] = None
extensions: Optional[Dict[str, Any]] = None
out_name: Optional[str] = None
to_kwargs() → Dict[str, Any]
type: 'GraphQLInputType' = None
class graphql.GraphQLResolveInfo

Bases: tuple

Collection of information passed to the resolvers.

This is always passed as the first argument to the resolvers.

Note that contrary to the JavaScript implementation, the context (commonly used to represent an authenticated user, or request-specific caches) is included here and not passed as an additional argument.

__init__()

Initialize self. See help(type(self)) for accurate signature.

_asdict()

Return a new OrderedDict which maps field names to their values.

_field_defaults = {}
_field_types = {'context': typing.Any, 'field_name': <class 'str'>, 'field_nodes': typing.List[graphql.language.ast.FieldNode], 'fragments': typing.Dict[str, graphql.language.ast.FragmentDefinitionNode], 'operation': <class 'graphql.language.ast.OperationDefinitionNode'>, 'parent_type': ForwardRef('GraphQLObjectType'), 'path': <class 'graphql.pyutils.path.Path'>, 'return_type': ForwardRef('GraphQLOutputType'), 'root_value': typing.Any, 'schema': ForwardRef('GraphQLSchema'), 'variable_values': typing.Dict[str, typing.Any]}
_fields = ('field_name', 'field_nodes', 'return_type', 'parent_type', 'path', 'schema', 'fragments', 'root_value', 'operation', 'variable_values', 'context')
_fields_defaults = {}
classmethod _make(iterable)

Make a new GraphQLResolveInfo object from a sequence or iterable

_replace(**kwds)

Return a new GraphQLResolveInfo object replacing specified fields with new values

property context

Alias for field number 10

count()

Return number of occurrences of value.

property field_name

Alias for field number 0

property field_nodes

Alias for field number 1

property fragments

Alias for field number 6

index()

Return first index of value.

Raises ValueError if the value is not present.

property operation

Alias for field number 8

property parent_type

Alias for field number 3

property path

Alias for field number 4

property return_type

Alias for field number 2

property root_value

Alias for field number 7

property schema

Alias for field number 5

property variable_values

Alias for field number 9

graphql.ResponsePath

alias of graphql.pyutils.path.Path

class graphql.Source(body: str, name: Optional[str] = None, location_offset: Optional[graphql.language.location.SourceLocation] = None)

Bases: object

A representation of source input to GraphQL.

__init__(body: str, name: Optional[str] = None, location_offset: Optional[graphql.language.location.SourceLocation] = None) → None

Initialize source input.

name and location_offset are optional. They are useful for clients who store GraphQL documents in source files; for example, if the GraphQL input starts at line 40 in a file named Foo.graphql, it might be useful for name to be “Foo.graphql” and location to be (40, 0).

line and column in location_offset are 1-indexed

body
get_location(position: int) → graphql.language.location.SourceLocation
location_offset
name
graphql.get_location(source: Source, position: int) → graphql.language.location.SourceLocation

Get the line and column for a character position in the source.

Takes a Source and a UTF-8 character offset, and returns the corresponding line and column as a SourceLocation.

graphql.print_location(location: graphql.language.ast.Location) → str

Render a helpful description of the location in the GraphQL Source document.

graphql.print_source_location(source: graphql.language.source.Source, source_location: graphql.language.location.SourceLocation) → str

Render a helpful description of the location in the GraphQL Source document.

class graphql.Lexer(source: graphql.language.source.Source)

Bases: object

GraphQL Lexer

A Lexer is a stateful stream generator in that every time it is advanced, it returns the next token in the Source. Assuming the source lexes, the final Token emitted by the lexer will be of kind EOF, after which the lexer will repeatedly return the same EOF token whenever called.

__init__(source: graphql.language.source.Source)

Given a Source object, initialize a Lexer for that source.

advance() → graphql.language.ast.Token

Advance the token stream to the next non-ignored token.

lookahead() → graphql.language.ast.Token

Look ahead and return the next non-ignored token, but do not change state.

position_after_whitespace(body: str, start_position: int) → int

Go to next position after a whitespace.

Reads from body starting at start_position until it finds a non-whitespace character, then returns the position of that character for lexing.

read_block_string(start: int, line: int, col: int, prev: graphql.language.ast.Token) → graphql.language.ast.Token
read_comment(start: int, line: int, col: int, prev: graphql.language.ast.Token) → graphql.language.ast.Token

Read a comment token from the source file.

read_digits(start: int, char: str) → int

Return the new position in the source after reading digits.

read_name(start: int, line: int, col: int, prev: graphql.language.ast.Token) → graphql.language.ast.Token

Read an alphanumeric + underscore name from the source.

read_number(start: int, char: str, line: int, col: int, prev: graphql.language.ast.Token) → graphql.language.ast.Token

Reads a number token from the source file.

Either a float or an int depending on whether a decimal point appears.

read_string(start: int, line: int, col: int, prev: graphql.language.ast.Token) → graphql.language.ast.Token

Read a string token from the source file.

read_token(prev: graphql.language.ast.Token) → graphql.language.ast.Token

Get the next token from the source starting at the given position.

This skips over whitespace until it finds the next lexable token, then lexes punctuators immediately or calls the appropriate helper function for more complicated tokens.

class graphql.TokenKind

Bases: enum.Enum

The different kinds of tokens that the lexer emits

AMP = '&'
AT = '@'
BANG = '!'
BLOCK_STRING = 'BlockString'
BRACE_L = '{'
BRACE_R = '}'
BRACKET_L = '['
BRACKET_R = ']'
COLON = ':'
COMMENT = 'Comment'
DOLLAR = '$'
EOF = '<EOF>'
EQUALS = '='
FLOAT = 'Float'
INT = 'Int'
NAME = 'Name'
PAREN_L = '('
PAREN_R = ')'
PIPE = '|'
SOF = '<SOF>'
SPREAD = '...'
STRING = 'String'
graphql.parse(source: Union[graphql.language.source.Source, str], no_location=False, experimental_fragment_variables=False) → graphql.language.ast.DocumentNode

Given a GraphQL source, parse it into a Document.

Throws GraphQLError if a syntax error is encountered.

By default, the parser creates AST nodes that know the location in the source that they correspond to. The no_location option disables that behavior for performance or testing.

Experimental features:

If experimental_fragment_variables is set to True, the parser will understand and parse variable definitions contained in a fragment definition. They’ll be represented in the variable_definitions field of the FragmentDefinitionNode.

The syntax is identical to normal, query-defined variables. For example:

fragment A($var: Boolean = false) on T  {
  ...
}
graphql.parse_value(source: Union[graphql.language.source.Source, str], no_location=False, experimental_fragment_variables=False) → graphql.language.ast.ValueNode

Parse the AST for a given string containing a GraphQL value.

Throws GraphQLError if a syntax error is encountered.

This is useful within tools that operate upon GraphQL Values directly and in isolation of complete GraphQL documents.

Consider providing the results to the utility function: value_from_ast().

graphql.parse_type(source: Union[graphql.language.source.Source, str], no_location=False, experimental_fragment_variables=False) → graphql.language.ast.TypeNode

Parse the AST for a given string containing a GraphQL Type.

Throws GraphQLError if a syntax error is encountered.

This is useful within tools that operate upon GraphQL Types directly and in isolation of complete GraphQL documents.

Consider providing the results to the utility function: type_from_ast().

graphql.print_ast(ast: graphql.language.ast.Node) → str

Convert an AST into a string.

The conversion is done using a set of reasonable formatting rules.

graphql.visit(root: graphql.language.ast.Node, visitor: graphql.language.visitor.Visitor, visitor_keys=None) → Any

Visit each node in an AST.

visit() will walk through an AST using a depth first traversal, calling the visitor’s enter methods at each node in the traversal, and calling the leave methods after visiting that node and all of its child nodes.

By returning different values from the enter and leave methods, the behavior of the visitor can be altered, including skipping over a sub-tree of the AST (by returning False), editing the AST by returning a value or None to remove the value, or to stop the whole traversal by returning BREAK.

When using visit() to edit an AST, the original AST will not be modified, and a new version of the AST with the changes applied will be returned from the visit function.

To customize the node attributes to be used for traversal, you can provide a dictionary visitor_keys mapping node kinds to node attributes.

class graphql.ParallelVisitor(visitors: Collection[graphql.language.visitor.Visitor])

Bases: graphql.language.visitor.Visitor

A Visitor which delegates to many visitors to run in parallel.

Each visitor will be visited for each node before moving on.

If a prior visitor edits a node, no following visitors will see that node.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(visitors: Collection[graphql.language.visitor.Visitor])

Create a new visitor from the given list of parallel visitors.

enter(node, *args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

leave(node, *args)
class graphql.TypeInfoVisitor(type_info: graphql.utilities.type_info.TypeInfo, visitor: graphql.language.visitor.Visitor)

Bases: graphql.language.visitor.Visitor

A visitor which maintains a provided TypeInfo.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(type_info: graphql.utilities.type_info.TypeInfo, visitor: graphql.language.visitor.Visitor)

Initialize self. See help(type(self)) for accurate signature.

enter(node, *args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

leave(node, *args)
class graphql.Visitor

Bases: object

Visitor that walks through an AST.

Visitors can define two generic methods “enter” and “leave”. The former will be called when a node is entered in the traversal, the latter is called after visiting the node and its child nodes. These methods have the following signature:

def enter(self, node, key, parent, path, ancestors):
    # The return value has the following meaning:
    # IDLE (None): no action
    # SKIP: skip visiting this node
    # BREAK: stop visiting altogether
    # REMOVE: delete this node
    # any other value: replace this node with the returned value
    return

def enter(self, node, key, parent, path, ancestors):
    # The return value has the following meaning:
    # IDLE (None) or SKIP: no action
    # BREAK: stop visiting altogether
    # REMOVE: delete this node
    # any other value: replace this node with the returned value
    return

The parameters have the following meaning:

Parameters
  • node – The current node being visiting.

  • key – The index or key to this node from the parent node or Array.

  • parent – the parent immediately above this node, which may be an Array.

  • path – The key path to get to this node from the root node.

  • ancestors – All nodes and Arrays visited before reaching parent of this node. These correspond to array indices in path. Note: ancestors includes arrays which contain the parent of visited node.

You can also define node kind specific methods by suffixing them with an underscore followed by the kind of the node to be visited. For instance, to visit field nodes, you would defined the methods enter_field() and/or leave_field(), with the same signature as above. If no kind specific method has been defined for a given node, the generic method is called.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__()

Initialize self. See help(type(self)) for accurate signature.

classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

class graphql.DirectiveLocation

Bases: enum.Enum

The enum type representing the directive location values.

ARGUMENT_DEFINITION = 'argument definition'
ENUM = 'enum'
ENUM_VALUE = 'enum value'
FIELD = 'field'
FIELD_DEFINITION = 'field definition'
FRAGMENT_DEFINITION = 'fragment definition'
FRAGMENT_SPREAD = 'fragment spread'
INLINE_FRAGMENT = 'inline fragment'
INPUT_FIELD_DEFINITION = 'input field definition'
INPUT_OBJECT = 'input object'
INTERFACE = 'interface'
MUTATION = 'mutation'
OBJECT = 'object'
QUERY = 'query'
SCALAR = 'scalar'
SCHEMA = 'schema'
SUBSCRIPTION = 'subscription'
UNION = 'union'
VARIABLE_DEFINITION = 'variable definition'
graphql.is_definition_node(node: graphql.language.ast.Node) → bool
graphql.is_executable_definition_node(node: graphql.language.ast.Node) → bool
graphql.is_selection_node(node: graphql.language.ast.Node) → bool
graphql.is_value_node(node: graphql.language.ast.Node) → bool
graphql.is_type_node(node: graphql.language.ast.Node) → bool
graphql.is_type_system_definition_node(node: graphql.language.ast.Node) → bool
graphql.is_type_definition_node(node: graphql.language.ast.Node) → bool
graphql.is_type_system_extension_node(node: graphql.language.ast.Node) → bool
graphql.is_type_extension_node(node: graphql.language.ast.Node) → bool
class graphql.SourceLocation

Bases: tuple

Represents a location in a Source.

__init__()

Initialize self. See help(type(self)) for accurate signature.

_asdict()

Return a new OrderedDict which maps field names to their values.

_field_defaults = {}
_field_types = {'column': <class 'int'>, 'line': <class 'int'>}
_fields = ('line', 'column')
_fields_defaults = {}
classmethod _make(iterable)

Make a new SourceLocation object from a sequence or iterable

_replace(**kwds)

Return a new SourceLocation object replacing specified fields with new values

property column

Alias for field number 1

count()

Return number of occurrences of value.

property formatted
index()

Return first index of value.

Raises ValueError if the value is not present.

property line

Alias for field number 0

class graphql.Location(start_token: graphql.language.ast.Token, end_token: graphql.language.ast.Token, source: graphql.language.source.Source)

Bases: object

AST Location

Contains a range of UTF-8 character offsets and token references that identify the region of the source from which the AST derived.

__init__(start_token: graphql.language.ast.Token, end_token: graphql.language.ast.Token, source: graphql.language.source.Source)

Initialize self. See help(type(self)) for accurate signature.

end
end_token
source
start
start_token
class graphql.Token(kind: graphql.language.token_kind.TokenKind, start: int, end: int, line: int, column: int, prev: Optional[Token] = None, value: Optional[str] = None)

Bases: object

AST Token

Represents a range of characters represented by a lexical token within a Source.

__init__(kind: graphql.language.token_kind.TokenKind, start: int, end: int, line: int, column: int, prev: Optional[Token] = None, value: Optional[str] = None) → None

Initialize self. See help(type(self)) for accurate signature.

column
property desc

A helper property to describe a token as a string for debugging

end
kind
line
next
prev
start
value
class graphql.Node(**kwargs)

Bases: object

AST nodes

__init__(**kwargs)

Initialize the node with the given keyword arguments.

keys = ['loc']
kind: str = 'ast'
loc
class graphql.NameNode(**kwargs)

Bases: graphql.language.ast.Node

__init__(**kwargs)

Initialize the node with the given keyword arguments.

keys = ['loc', 'value']
kind = 'name'
loc
value
class graphql.DocumentNode(**kwargs)

Bases: graphql.language.ast.Node

__init__(**kwargs)

Initialize the node with the given keyword arguments.

definitions
keys = ['loc', 'definitions']
kind = 'document'
loc
class graphql.DefinitionNode(**kwargs)

Bases: graphql.language.ast.Node

__init__(**kwargs)

Initialize the node with the given keyword arguments.

keys = ['loc']
kind: str = 'definition'
loc
class graphql.ExecutableDefinitionNode(**kwargs)

Bases: graphql.language.ast.DefinitionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

directives
keys = ['loc', 'name', 'directives', 'variable_definitions', 'selection_set']
kind = 'executable_definition'
loc
name
selection_set
variable_definitions
class graphql.OperationDefinitionNode(**kwargs)

Bases: graphql.language.ast.ExecutableDefinitionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

directives
keys = ['loc', 'name', 'directives', 'variable_definitions', 'selection_set', 'operation']
kind = 'operation_definition'
loc
name
operation
selection_set
variable_definitions
class graphql.OperationType

Bases: enum.Enum

An enumeration.

MUTATION = 'mutation'
QUERY = 'query'
SUBSCRIPTION = 'subscription'
class graphql.VariableDefinitionNode(**kwargs)

Bases: graphql.language.ast.Node

__init__(**kwargs)

Initialize the node with the given keyword arguments.

default_value
directives
keys = ['loc', 'variable', 'type', 'default_value', 'directives']
kind = 'variable_definition'
loc
type
variable
class graphql.VariableNode(**kwargs)

Bases: graphql.language.ast.ValueNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

keys = ['loc', 'name']
kind = 'variable'
loc
name
class graphql.SelectionSetNode(**kwargs)

Bases: graphql.language.ast.Node

__init__(**kwargs)

Initialize the node with the given keyword arguments.

keys = ['loc', 'selections']
kind = 'selection_set'
loc
selections
class graphql.SelectionNode(**kwargs)

Bases: graphql.language.ast.Node

__init__(**kwargs)

Initialize the node with the given keyword arguments.

directives
keys = ['loc', 'directives']
kind = 'selection'
loc
class graphql.FieldNode(**kwargs)

Bases: graphql.language.ast.SelectionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

alias
arguments
directives
keys = ['loc', 'directives', 'alias', 'name', 'arguments', 'selection_set']
kind = 'field'
loc
name
selection_set
class graphql.ArgumentNode(**kwargs)

Bases: graphql.language.ast.Node

__init__(**kwargs)

Initialize the node with the given keyword arguments.

keys = ['loc', 'name', 'value']
kind = 'argument'
loc
name
value
class graphql.FragmentSpreadNode(**kwargs)

Bases: graphql.language.ast.SelectionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

directives
keys = ['loc', 'directives', 'name']
kind = 'fragment_spread'
loc
name
class graphql.InlineFragmentNode(**kwargs)

Bases: graphql.language.ast.SelectionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

directives
keys = ['loc', 'directives', 'type_condition', 'selection_set']
kind = 'inline_fragment'
loc
selection_set
type_condition
class graphql.FragmentDefinitionNode(**kwargs)

Bases: graphql.language.ast.ExecutableDefinitionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

directives
keys = ['loc', 'name', 'directives', 'variable_definitions', 'selection_set', 'type_condition']
kind = 'fragment_definition'
loc
name
selection_set
type_condition
variable_definitions
class graphql.ValueNode(**kwargs)

Bases: graphql.language.ast.Node

__init__(**kwargs)

Initialize the node with the given keyword arguments.

keys = ['loc']
kind: str = 'value'
loc
class graphql.IntValueNode(**kwargs)

Bases: graphql.language.ast.ValueNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

keys = ['loc', 'value']
kind = 'int_value'
loc
value
class graphql.FloatValueNode(**kwargs)

Bases: graphql.language.ast.ValueNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

keys = ['loc', 'value']
kind = 'float_value'
loc
value
class graphql.StringValueNode(**kwargs)

Bases: graphql.language.ast.ValueNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

block
keys = ['loc', 'value', 'block']
kind = 'string_value'
loc
value
class graphql.BooleanValueNode(**kwargs)

Bases: graphql.language.ast.ValueNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

keys = ['loc', 'value']
kind = 'boolean_value'
loc
value
class graphql.NullValueNode(**kwargs)

Bases: graphql.language.ast.ValueNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

keys = ['loc']
kind: str = 'null_value'
loc
class graphql.EnumValueNode(**kwargs)

Bases: graphql.language.ast.ValueNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

keys = ['loc', 'value']
kind = 'enum_value'
loc
value
class graphql.ListValueNode(**kwargs)

Bases: graphql.language.ast.ValueNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

keys = ['loc', 'values']
kind = 'list_value'
loc
values
class graphql.ObjectValueNode(**kwargs)

Bases: graphql.language.ast.ValueNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

fields
keys = ['loc', 'fields']
kind = 'object_value'
loc
class graphql.ObjectFieldNode(**kwargs)

Bases: graphql.language.ast.Node

__init__(**kwargs)

Initialize the node with the given keyword arguments.

keys = ['loc', 'name', 'value']
kind = 'object_field'
loc
name
value
class graphql.DirectiveNode(**kwargs)

Bases: graphql.language.ast.Node

__init__(**kwargs)

Initialize the node with the given keyword arguments.

arguments
keys = ['loc', 'name', 'arguments']
kind = 'directive'
loc
name
class graphql.TypeNode(**kwargs)

Bases: graphql.language.ast.Node

__init__(**kwargs)

Initialize the node with the given keyword arguments.

keys = ['loc']
kind: str = 'type'
loc
class graphql.NamedTypeNode(**kwargs)

Bases: graphql.language.ast.TypeNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

keys = ['loc', 'name']
kind = 'named_type'
loc
name
class graphql.ListTypeNode(**kwargs)

Bases: graphql.language.ast.TypeNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

keys = ['loc', 'type']
kind = 'list_type'
loc
type
class graphql.NonNullTypeNode(**kwargs)

Bases: graphql.language.ast.TypeNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

keys = ['loc', 'type']
kind = 'non_null_type'
loc
type
class graphql.TypeSystemDefinitionNode(**kwargs)

Bases: graphql.language.ast.DefinitionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

keys = ['loc']
kind: str = 'type_system_definition'
loc
class graphql.SchemaDefinitionNode(**kwargs)

Bases: graphql.language.ast.TypeSystemDefinitionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

directives
keys = ['loc', 'directives', 'operation_types']
kind = 'schema_definition'
loc
operation_types
class graphql.OperationTypeDefinitionNode(**kwargs)

Bases: graphql.language.ast.Node

__init__(**kwargs)

Initialize the node with the given keyword arguments.

keys = ['loc', 'operation', 'type']
kind = 'operation_type_definition'
loc
operation
type
class graphql.TypeDefinitionNode(**kwargs)

Bases: graphql.language.ast.TypeSystemDefinitionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

description
directives
keys = ['loc', 'description', 'name', 'directives']
kind = 'type_definition'
loc
name
class graphql.ScalarTypeDefinitionNode(**kwargs)

Bases: graphql.language.ast.TypeDefinitionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

description
directives
keys = ['loc', 'description', 'name', 'directives']
kind = 'scalar_type_definition'
loc
name
class graphql.ObjectTypeDefinitionNode(**kwargs)

Bases: graphql.language.ast.TypeDefinitionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

description
directives
fields
interfaces
keys = ['loc', 'description', 'name', 'directives', 'interfaces', 'fields']
kind = 'object_type_definition'
loc
name
class graphql.FieldDefinitionNode(**kwargs)

Bases: graphql.language.ast.TypeDefinitionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

arguments
description
directives
keys = ['loc', 'description', 'name', 'directives', 'arguments', 'type']
kind = 'field_definition'
loc
name
type
class graphql.InputValueDefinitionNode(**kwargs)

Bases: graphql.language.ast.TypeDefinitionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

default_value
description
directives
keys = ['loc', 'description', 'name', 'directives', 'type', 'default_value']
kind = 'input_value_definition'
loc
name
type
class graphql.InterfaceTypeDefinitionNode(**kwargs)

Bases: graphql.language.ast.TypeDefinitionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

description
directives
fields
interfaces
keys = ['loc', 'description', 'name', 'directives', 'fields', 'interfaces']
kind = 'interface_type_definition'
loc
name
class graphql.UnionTypeDefinitionNode(**kwargs)

Bases: graphql.language.ast.TypeDefinitionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

description
directives
keys = ['loc', 'description', 'name', 'directives', 'types']
kind = 'union_type_definition'
loc
name
types
class graphql.EnumTypeDefinitionNode(**kwargs)

Bases: graphql.language.ast.TypeDefinitionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

description
directives
keys = ['loc', 'description', 'name', 'directives', 'values']
kind = 'enum_type_definition'
loc
name
values
class graphql.EnumValueDefinitionNode(**kwargs)

Bases: graphql.language.ast.TypeDefinitionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

description
directives
keys = ['loc', 'description', 'name', 'directives']
kind = 'enum_value_definition'
loc
name
class graphql.InputObjectTypeDefinitionNode(**kwargs)

Bases: graphql.language.ast.TypeDefinitionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

description
directives
fields
keys = ['loc', 'description', 'name', 'directives', 'fields']
kind = 'input_object_type_definition'
loc
name
class graphql.DirectiveDefinitionNode(**kwargs)

Bases: graphql.language.ast.TypeSystemDefinitionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

arguments
description
keys = ['loc', 'description', 'name', 'arguments', 'repeatable', 'locations']
kind = 'directive_definition'
loc
locations
name
repeatable
class graphql.SchemaExtensionNode(**kwargs)

Bases: graphql.language.ast.Node

__init__(**kwargs)

Initialize the node with the given keyword arguments.

directives
keys = ['loc', 'directives', 'operation_types']
kind = 'schema_extension'
loc
operation_types
class graphql.TypeExtensionNode(**kwargs)

Bases: graphql.language.ast.TypeSystemDefinitionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

directives
keys = ['loc', 'name', 'directives']
kind = 'type_extension'
loc
name
class graphql.ScalarTypeExtensionNode(**kwargs)

Bases: graphql.language.ast.TypeExtensionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

directives
keys = ['loc', 'name', 'directives']
kind = 'scalar_type_extension'
loc
name
class graphql.ObjectTypeExtensionNode(**kwargs)

Bases: graphql.language.ast.TypeExtensionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

directives
fields
interfaces
keys = ['loc', 'name', 'directives', 'interfaces', 'fields']
kind = 'object_type_extension'
loc
name
class graphql.InterfaceTypeExtensionNode(**kwargs)

Bases: graphql.language.ast.TypeExtensionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

directives
fields
interfaces
keys = ['loc', 'name', 'directives', 'interfaces', 'fields']
kind = 'interface_type_extension'
loc
name
class graphql.UnionTypeExtensionNode(**kwargs)

Bases: graphql.language.ast.TypeExtensionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

directives
keys = ['loc', 'name', 'directives', 'types']
kind = 'union_type_extension'
loc
name
types
class graphql.EnumTypeExtensionNode(**kwargs)

Bases: graphql.language.ast.TypeExtensionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

directives
keys = ['loc', 'name', 'directives', 'values']
kind = 'enum_type_extension'
loc
name
values
class graphql.InputObjectTypeExtensionNode(**kwargs)

Bases: graphql.language.ast.TypeExtensionNode

__init__(**kwargs)

Initialize the node with the given keyword arguments.

directives
fields
keys = ['loc', 'name', 'directives', 'fields']
kind = 'input_object_type_extension'
loc
name
graphql.execute(schema: graphql.type.schema.GraphQLSchema, document: graphql.language.ast.DocumentNode, root_value: Any = None, context_value: Any = None, variable_values: Optional[Dict[str, Any]] = None, operation_name: Optional[str] = None, field_resolver: Optional[Callable[[...], Any]] = None, type_resolver: Optional[Callable[[Any, graphql.type.definition.GraphQLResolveInfo, GraphQLAbstractType], Union[Awaitable[Union[GraphQLObjectType, str, None]], GraphQLObjectType, str, None]]] = None, middleware: Union[Tuple, List, graphql.execution.middleware.MiddlewareManager, None] = None, execution_context_class: Optional[Type[ExecutionContext]] = None) → Union[Awaitable[graphql.execution.execute.ExecutionResult], graphql.execution.execute.ExecutionResult]

Execute a GraphQL operation.

Implements the “Evaluating 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.default_field_resolver(source, info, **args)

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.default_type_resolver(value: Any, info: graphql.type.definition.GraphQLResolveInfo, abstract_type: Union[graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType]) → Union[Awaitable[Union[graphql.type.definition.GraphQLObjectType, str, None]], graphql.type.definition.GraphQLObjectType, 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.

graphql.get_directive_values(directive_def: graphql.type.directives.GraphQLDirective, node: Union[graphql.language.ast.ExecutableDefinitionNode, graphql.language.ast.SelectionNode, graphql.language.ast.SchemaDefinitionNode, graphql.language.ast.TypeDefinitionNode, graphql.language.ast.TypeExtensionNode], variable_values: Optional[Dict[str, Any]] = None) → Optional[Dict[str, Any]]

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.

class graphql.ExecutionContext(schema: graphql.type.schema.GraphQLSchema, fragments: Dict[str, graphql.language.ast.FragmentDefinitionNode], root_value: Any, context_value: Any, operation: graphql.language.ast.OperationDefinitionNode, variable_values: Dict[str, Any], field_resolver: Callable[[...], Any], type_resolver: Callable[[Any, graphql.type.definition.GraphQLResolveInfo, GraphQLAbstractType], Union[Awaitable[Union[GraphQLObjectType, str, None]], GraphQLObjectType, str, None]], errors: List[graphql.error.graphql_error.GraphQLError], middleware_manager: Optional[graphql.execution.middleware.MiddlewareManager])

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: graphql.type.schema.GraphQLSchema, fragments: Dict[str, graphql.language.ast.FragmentDefinitionNode], root_value: Any, context_value: Any, operation: graphql.language.ast.OperationDefinitionNode, variable_values: Dict[str, Any], field_resolver: Callable[[...], Any], type_resolver: Callable[[Any, graphql.type.definition.GraphQLResolveInfo, GraphQLAbstractType], Union[Awaitable[Union[GraphQLObjectType, str, None]], GraphQLObjectType, str, None]], errors: List[graphql.error.graphql_error.GraphQLError], middleware_manager: Optional[graphql.execution.middleware.MiddlewareManager]) → None

Initialize self. See help(type(self)) for accurate signature.

classmethod build(schema: graphql.type.schema.GraphQLSchema, document: graphql.language.ast.DocumentNode, root_value: Any = None, context_value: Any = None, raw_variable_values: Optional[Dict[str, Any]] = None, operation_name: Optional[str] = None, field_resolver: Optional[Callable[[...], Any]] = None, type_resolver: Optional[Callable[[Any, graphql.type.definition.GraphQLResolveInfo, GraphQLAbstractType], Union[Awaitable[Union[GraphQLObjectType, str, None]], GraphQLObjectType, str, None]]] = None, middleware: Union[Tuple, List, graphql.execution.middleware.MiddlewareManager, None] = None) → Union[List[graphql.error.graphql_error.GraphQLError], graphql.execution.execute.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: graphql.type.definition.GraphQLField, field_nodes: List[graphql.language.ast.FieldNode], parent_type: graphql.type.definition.GraphQLObjectType, path: graphql.pyutils.path.Path) → graphql.type.definition.GraphQLResolveInfo

Build the GraphQLResolveInfo object.

For internal use only.

build_response(data: Union[Awaitable[Optional[Dict[str, Any]]], Dict[str, Any], None]) → Union[Awaitable[graphql.execution.execute.ExecutionResult], graphql.execution.execute.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_and_execute_subfields(return_type: graphql.type.definition.GraphQLObjectType, field_nodes: List[graphql.language.ast.FieldNode], path: graphql.pyutils.path.Path, result: Any) → Union[Awaitable[Dict[str, Any]], Dict[str, Any]]

Collect sub-fields to execute to complete this value.

collect_fields(runtime_type: graphql.type.definition.GraphQLObjectType, selection_set: graphql.language.ast.SelectionSetNode, fields: Dict[str, List[graphql.language.ast.FieldNode]], visited_fragment_names: Set[str]) → Dict[str, List[graphql.language.ast.FieldNode]]

Collect fields.

Given a selection_set, adds all of the fields in that selection to the passed in map of fields, and returns it at the end.

collect_fields requires the “runtime type” of an object. For a field which returns an Interface or Union type, the “runtime type” will be the actual Object type returned by that field.

For internal use only.

collect_subfields(return_type: graphql.type.definition.GraphQLObjectType, field_nodes: List[graphql.language.ast.FieldNode]) → Dict[str, List[graphql.language.ast.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.

complete_abstract_value(return_type: Union[graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType], field_nodes: List[graphql.language.ast.FieldNode], info: graphql.type.definition.GraphQLResolveInfo, path: graphql.pyutils.path.Path, result: Any) → Union[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: Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.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: graphql.type.definition.GraphQLList[typing.Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLObjectType, graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLWrappingType]][Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLObjectType, graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLWrappingType]], field_nodes: List[graphql.language.ast.FieldNode], info: graphql.type.definition.GraphQLResolveInfo, path: graphql.pyutils.path.Path, result: Iterable[Any]) → Union[Awaitable[Any], 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: graphql.type.definition.GraphQLObjectType, field_nodes: List[graphql.language.ast.FieldNode], info: graphql.type.definition.GraphQLResolveInfo, path: graphql.pyutils.path.Path, result: Any) → Union[Awaitable[Dict[str, Any]], Dict[str, Any]]

Complete an Object value by executing all sub-selections.

complete_value(return_type: Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLObjectType, graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLWrappingType], field_nodes: List[graphql.language.ast.FieldNode], info: graphql.type.definition.GraphQLResolveInfo, path: graphql.pyutils.path.Path, result: Any) → Union[Awaitable[Any], Any]

Complete a value.

Implements the instructions for completeValue as defined in the “Field entries” 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.

complete_value_catching_error(return_type: Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLObjectType, graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLWrappingType], field_nodes: List[graphql.language.ast.FieldNode], info: graphql.type.definition.GraphQLResolveInfo, path: graphql.pyutils.path.Path, result: Any) → Union[Awaitable[Any], Any]

Complete a value while catching an error.

This is a small wrapper around completeValue which detects and logs errors in the execution context.

context_value: Any = None
does_fragment_condition_match(fragment: Union[graphql.language.ast.FragmentDefinitionNode, graphql.language.ast.InlineFragmentNode], type_: graphql.type.definition.GraphQLObjectType) → bool

Determine if a fragment is applicable to the given type.

ensure_valid_runtime_type(runtime_type_or_name: Union[graphql.type.definition.GraphQLObjectType, str, None], return_type: Union[graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType], field_nodes: List[graphql.language.ast.FieldNode], info: graphql.type.definition.GraphQLResolveInfo, result: Any) → graphql.type.definition.GraphQLObjectType
errors: List[GraphQLError] = None
execute_fields(parent_type: graphql.type.definition.GraphQLObjectType, source_value: Any, path: Optional[graphql.pyutils.path.Path], fields: Dict[str, List[graphql.language.ast.FieldNode]]) → Union[Awaitable[Dict[str, Any]], Dict[str, Any]]

Execute the given fields concurrently.

Implements the “Evaluating selection sets” section of the spec for “read” mode.

execute_fields_serially(parent_type: graphql.type.definition.GraphQLObjectType, source_value: Any, path: Optional[graphql.pyutils.path.Path], fields: Dict[str, List[graphql.language.ast.FieldNode]]) → Union[Awaitable[Dict[str, Any]], Dict[str, Any]]

Execute the given fields serially.

Implements the “Evaluating selection sets” section of the spec for “write” mode.

execute_operation(operation: graphql.language.ast.OperationDefinitionNode, root_value: Any) → Union[Awaitable[Any], Any, None]

Execute an operation.

Implements the “Evaluating operations” section of the spec.

field_resolver: GraphQLFieldResolver = None
fragments: Dict[str, FragmentDefinitionNode] = None
handle_field_error(raw_error: Exception, field_nodes: List[graphql.language.ast.FieldNode], path: graphql.pyutils.path.Path, return_type: Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLObjectType, graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLWrappingType]) → None
middleware_manager: Optional[MiddlewareManager] = None
operation: OperationDefinitionNode = None
resolve_field(parent_type: graphql.type.definition.GraphQLObjectType, source: Any, field_nodes: List[graphql.language.ast.FieldNode], path: graphql.pyutils.path.Path) → Union[Awaitable[Any], Any]

Resolve the field on the given source object.

In particular, this 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.

resolve_field_value_or_error(field_def: graphql.type.definition.GraphQLField, field_nodes: List[graphql.language.ast.FieldNode], resolve_fn: Callable[[...], Any], source: Any, info: graphql.type.definition.GraphQLResolveInfo) → Union[Exception, Any]

Resolve field to a value or an error.

Isolates the “ReturnOrAbrupt” behavior to not de-opt the resolve_field() method. Returns the result of resolveFn or the abrupt-return Error object.

For internal use only.

root_value: Any = None
schema: GraphQLSchema = None
should_include_node(node: Union[graphql.language.ast.FragmentSpreadNode, graphql.language.ast.FieldNode, graphql.language.ast.InlineFragmentNode]) → bool

Check if node should be included

Determines if a field should be included based on the @include and @skip directives, where @skip has higher precedence than @include.

type_resolver: GraphQLTypeResolver = None
variable_values: Dict[str, Any] = None
class graphql.ExecutionResult

Bases: tuple

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.

__init__()

Initialize self. See help(type(self)) for accurate signature.

_asdict()

Return a new OrderedDict which maps field names to their values.

_field_defaults = {}
_field_types = {'data': typing.Union[typing.Dict[str, typing.Any], NoneType], 'errors': typing.Union[typing.List[graphql.error.graphql_error.GraphQLError], NoneType]}
_fields = ('data', 'errors')
_fields_defaults = {}
classmethod _make(iterable)

Make a new ExecutionResult object from a sequence or iterable

_replace(**kwds)

Return a new ExecutionResult object replacing specified fields with new values

count()

Return number of occurrences of value.

property data

Alias for field number 0

property errors

Alias for field number 1

index()

Return first index of value.

Raises ValueError if the value is not present.

class graphql.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)

Initialize self. See help(type(self)) for accurate signature.

_cached_resolvers
_middleware_resolvers
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
async graphql.subscribe(schema: graphql.type.schema.GraphQLSchema, document: graphql.language.ast.DocumentNode, root_value: Any = None, context_value: Any = None, variable_values: Optional[Dict[str, Any]] = None, operation_name: Optional[str] = None, field_resolver: Optional[Callable[[...], Any]] = None, subscribe_field_resolver: Optional[Callable[[...], Any]] = None) → Union[AsyncIterator[graphql.execution.execute.ExecutionResult], graphql.execution.execute.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.create_source_event_stream(schema: graphql.type.schema.GraphQLSchema, document: graphql.language.ast.DocumentNode, root_value: Any = None, context_value: Any = None, variable_values: Optional[Dict[str, Any]] = None, operation_name: Optional[str] = None, field_resolver: Optional[Callable[[...], Any]] = None) → Union[AsyncIterable[Any], graphql.execution.execute.ExecutionResult]

Create source even 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 invalid arguments, the source stream could not be created, or the resolver did not return an AsyncIterable, this function will throw an error, which should be caught and handled by the caller.

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.

graphql.validate(schema: graphql.type.schema.GraphQLSchema, document_ast: graphql.language.ast.DocumentNode, rules: Optional[Collection[Type[graphql.validation.rules.ASTValidationRule]]] = None, type_info: Optional[graphql.utilities.type_info.TypeInfo] = None, max_errors: Optional[int] = None) → List[graphql.error.graphql_error.GraphQLError]

Implements the “Validation” section of the spec.

Validation runs synchronously, returning a list of encountered errors, or an empty list if no errors were encountered and the document is valid.

A list of specific validation rules may be provided. If not provided, the default list of rules defined by the GraphQL specification will be used.

Each validation rule is a ValidationRule object which is a visitor object that holds a ValidationContext (see the language/visitor API). Visitor methods are expected to return GraphQLErrors, or lists of GraphQLErrors when invalid.

Optionally a custom TypeInfo instance may be provided. If not provided, one will be created from the provided schema.

class graphql.ValidationContext(schema: graphql.type.schema.GraphQLSchema, ast: graphql.language.ast.DocumentNode, type_info: graphql.utilities.type_info.TypeInfo, on_error: Callable[[graphql.error.graphql_error.GraphQLError], None])

Bases: graphql.validation.validation_context.ASTValidationContext

Utility class providing a context for validation using a GraphQL schema.

An instance of this class is passed as the context attribute to all Validators, allowing access to commonly useful contextual information from within a validation rule.

__init__(schema: graphql.type.schema.GraphQLSchema, ast: graphql.language.ast.DocumentNode, type_info: graphql.utilities.type_info.TypeInfo, on_error: Callable[[graphql.error.graphql_error.GraphQLError], None]) → None

Initialize self. See help(type(self)) for accurate signature.

_recursive_variable_usages: Dict[OperationDefinitionNode, List[VariableUsage]] = None
_type_info: TypeInfo = None
_variable_usages: Dict[NodeWithSelectionSet, List[VariableUsage]] = None
get_argument()
get_directive()
get_field_def()
get_fragment(name: str) → Optional[graphql.language.ast.FragmentDefinitionNode]
get_fragment_spreads(node: graphql.language.ast.SelectionSetNode) → List[graphql.language.ast.FragmentSpreadNode]
get_input_type()
get_parent_input_type()
get_parent_type()
get_recursive_variable_usages(operation: graphql.language.ast.OperationDefinitionNode) → List[graphql.validation.validation_context.VariableUsage]
get_recursively_referenced_fragments(operation: graphql.language.ast.OperationDefinitionNode) → List[graphql.language.ast.FragmentDefinitionNode]
get_type()
get_variable_usages(node: Union[graphql.language.ast.OperationDefinitionNode, graphql.language.ast.FragmentDefinitionNode]) → List[graphql.validation.validation_context.VariableUsage]
on_error(error: graphql.error.graphql_error.GraphQLError)
report_error(error: graphql.error.graphql_error.GraphQLError)
schema: GraphQLSchema = None
class graphql.ValidationRule(context: graphql.validation.validation_context.ValidationContext)

Bases: graphql.validation.rules.ASTValidationRule

Visitor for validation using a GraphQL schema.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context: ValidationContext = None
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.ASTValidationRule(context: graphql.validation.validation_context.ASTValidationContext)

Bases: graphql.language.visitor.Visitor

Visitor for validation of an AST.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ASTValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context: ASTValidationContext = None
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.SDLValidationRule(context: graphql.validation.validation_context.SDLValidationContext)

Bases: graphql.validation.rules.ASTValidationRule

Visitor for validation of an SDL AST.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.SDLValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context: ValidationContext = None
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.ExecutableDefinitionsRule(context: graphql.validation.validation_context.ASTValidationContext)

Bases: graphql.validation.rules.ASTValidationRule

Executable definitions

A GraphQL document is only valid for execution if all definitions are either operation or fragment definitions.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ASTValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_document(node: graphql.language.ast.DocumentNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.FieldsOnCorrectTypeRule(context: graphql.validation.validation_context.ValidationContext)

Bases: graphql.validation.rules.ValidationRule

Fields on correct type

A GraphQL document is only valid if all fields selected are defined by the parent type, or are an allowed meta field such as __typename.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_field(node: graphql.language.ast.FieldNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.FragmentsOnCompositeTypesRule(context: graphql.validation.validation_context.ValidationContext)

Bases: graphql.validation.rules.ValidationRule

Fragments on composite type

Fragments use a type condition to determine if they apply, since fragments can only be spread into a composite type (object, interface, or union), the type condition must also be a composite type.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_fragment_definition(node: graphql.language.ast.FragmentDefinitionNode, *_args)
enter_inline_fragment(node: graphql.language.ast.InlineFragmentNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.KnownArgumentNamesRule(context: graphql.validation.validation_context.ValidationContext)

Bases: graphql.validation.rules.known_argument_names.KnownArgumentNamesOnDirectivesRule

Known argument names

A GraphQL field is only valid if all supplied arguments are defined by that field.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context: ValidationContext = None
enter_argument(arg_node: graphql.language.ast.ArgumentNode, *args)
enter_directive(directive_node: graphql.language.ast.DirectiveNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.KnownDirectivesRule(context: Union[graphql.validation.validation_context.ValidationContext, graphql.validation.validation_context.SDLValidationContext])

Bases: graphql.validation.rules.ASTValidationRule

Known directives

A GraphQL document is only valid if all @directives are known by the schema and legally positioned.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: Union[graphql.validation.validation_context.ValidationContext, graphql.validation.validation_context.SDLValidationContext])

Initialize self. See help(type(self)) for accurate signature.

context: Union[ValidationContext, SDLValidationContext] = None
enter_directive(node: graphql.language.ast.DirectiveNode, _key, _parent, _path, ancestors)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.KnownFragmentNamesRule(context: graphql.validation.validation_context.ValidationContext)

Bases: graphql.validation.rules.ValidationRule

Known fragment names

A GraphQL document is only valid if all …Fragment fragment spreads refer to fragments defined in the same document.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_fragment_spread(node: graphql.language.ast.FragmentSpreadNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.KnownTypeNamesRule(context: Union[graphql.validation.validation_context.ValidationContext, graphql.validation.validation_context.SDLValidationContext])

Bases: graphql.validation.rules.ASTValidationRule

Known type names

A GraphQL document is only valid if referenced types (specifically variable definitions and fragment conditions) are defined by the type schema.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: Union[graphql.validation.validation_context.ValidationContext, graphql.validation.validation_context.SDLValidationContext])

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_named_type(node: graphql.language.ast.NamedTypeNode, _key, parent: graphql.language.ast.Node, _path, ancestors: List[graphql.language.ast.Node])
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.LoneAnonymousOperationRule(context: graphql.validation.validation_context.ASTValidationContext)

Bases: graphql.validation.rules.ASTValidationRule

Lone anonymous operation

A GraphQL document is only valid if when it contains an anonymous operation (the query short-hand) that it contains only that one operation definition.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ASTValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_document(node: graphql.language.ast.DocumentNode, *_args)
enter_operation_definition(node: graphql.language.ast.OperationDefinitionNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.NoFragmentCyclesRule(context: graphql.validation.validation_context.ASTValidationContext)

Bases: graphql.validation.rules.ASTValidationRule

No fragment cycles

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ASTValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
detect_cycle_recursive(fragment: graphql.language.ast.FragmentDefinitionNode)
enter_fragment_definition(node: graphql.language.ast.FragmentDefinitionNode, *_args)
enter_operation_definition(*_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.NoUndefinedVariablesRule(context: graphql.validation.validation_context.ValidationContext)

Bases: graphql.validation.rules.ValidationRule

No undefined variables

A GraphQL operation is only valid if all variables encountered, both directly and via fragment spreads, are defined by that operation.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_operation_definition(*_args)
enter_variable_definition(node: graphql.language.ast.VariableDefinitionNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

leave_operation_definition(operation: graphql.language.ast.OperationDefinitionNode, *_args)
report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.NoUnusedFragmentsRule(context: graphql.validation.validation_context.ASTValidationContext)

Bases: graphql.validation.rules.ASTValidationRule

No unused fragments

A GraphQL document is only valid if all fragment definitions are spread within operations, or spread within other fragments spread within operations.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ASTValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_fragment_definition(node: graphql.language.ast.FragmentDefinitionNode, *_args)
enter_operation_definition(node: graphql.language.ast.OperationDefinitionNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

leave_document(*_args)
report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.NoUnusedVariablesRule(context: graphql.validation.validation_context.ValidationContext)

Bases: graphql.validation.rules.ValidationRule

No unused variables

A GraphQL operation is only valid if all variables defined by an operation are used, either directly or within a spread fragment.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_operation_definition(*_args)
enter_variable_definition(definition: graphql.language.ast.VariableDefinitionNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

leave_operation_definition(operation: graphql.language.ast.OperationDefinitionNode, *_args)
report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.OverlappingFieldsCanBeMergedRule(context: graphql.validation.validation_context.ValidationContext)

Bases: graphql.validation.rules.ValidationRule

Overlapping fields can be merged

A selection set is only valid if all fields (including spreading any fragments) either correspond to distinct response names or can be merged without ambiguity.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_selection_set(selection_set: graphql.language.ast.SelectionSetNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.PossibleFragmentSpreadsRule(context: graphql.validation.validation_context.ValidationContext)

Bases: graphql.validation.rules.ValidationRule

Possible fragment spread

A fragment spread is only valid if the type condition could ever possibly be true: if there is a non-empty intersection of the possible parent types, and possible types which pass the type condition.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_fragment_spread(node: graphql.language.ast.FragmentSpreadNode, *_args)
enter_inline_fragment(node: graphql.language.ast.InlineFragmentNode, *_args)
get_fragment_type(name: str)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.ProvidedRequiredArgumentsRule(context: graphql.validation.validation_context.ValidationContext)

Bases: graphql.validation.rules.provided_required_arguments.ProvidedRequiredArgumentsOnDirectivesRule

Provided required arguments

A field or directive is only valid if all required (non-null without a default value) field arguments have been provided.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context: ValidationContext = None
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

leave_directive(directive_node: graphql.language.ast.DirectiveNode, *_args)
leave_field(field_node: graphql.language.ast.FieldNode, *_args)
report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.ScalarLeafsRule(context: graphql.validation.validation_context.ValidationContext)

Bases: graphql.validation.rules.ValidationRule

Scalar leafs

A GraphQL document is valid only if all leaf fields (fields without sub selections) are of scalar or enum types.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_field(node: graphql.language.ast.FieldNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.SingleFieldSubscriptionsRule(context: graphql.validation.validation_context.ASTValidationContext)

Bases: graphql.validation.rules.ASTValidationRule

Subscriptions must only include one field.

A GraphQL subscription is valid only if it contains a single root.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ASTValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_operation_definition(node: graphql.language.ast.OperationDefinitionNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.UniqueArgumentNamesRule(context: graphql.validation.validation_context.ASTValidationContext)

Bases: graphql.validation.rules.ASTValidationRule

Unique argument names

A GraphQL field or directive is only valid if all supplied arguments are uniquely named.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ASTValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_argument(node: graphql.language.ast.ArgumentNode, *_args)
enter_directive(*_args)
enter_field(*_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.UniqueDirectivesPerLocationRule(context: Union[graphql.validation.validation_context.ValidationContext, graphql.validation.validation_context.SDLValidationContext])

Bases: graphql.validation.rules.ASTValidationRule

Unique directive names per location

A GraphQL document is only valid if all non-repeatable directives at a given location are uniquely named.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: Union[graphql.validation.validation_context.ValidationContext, graphql.validation.validation_context.SDLValidationContext])

Initialize self. See help(type(self)) for accurate signature.

context: Union[ValidationContext, SDLValidationContext] = None
enter(node: graphql.language.ast.Node, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.UniqueFragmentNamesRule(context: graphql.validation.validation_context.ASTValidationContext)

Bases: graphql.validation.rules.ASTValidationRule

Unique fragment names

A GraphQL document is only valid if all defined fragments have unique names.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ASTValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_fragment_definition(node: graphql.language.ast.FragmentDefinitionNode, *_args)
enter_operation_definition(*_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.UniqueInputFieldNamesRule(context: graphql.validation.validation_context.ASTValidationContext)

Bases: graphql.validation.rules.ASTValidationRule

Unique input field names

A GraphQL input object value is only valid if all supplied fields are uniquely named.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ASTValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_object_field(node: graphql.language.ast.ObjectFieldNode, *_args)
enter_object_value(*_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

leave_object_value(*_args)
report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.UniqueOperationNamesRule(context: graphql.validation.validation_context.ASTValidationContext)

Bases: graphql.validation.rules.ASTValidationRule

Unique operation names

A GraphQL document is only valid if all defined operations have unique names.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ASTValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_fragment_definition(*_args)
enter_operation_definition(node: graphql.language.ast.OperationDefinitionNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.UniqueVariableNamesRule(context: graphql.validation.validation_context.ASTValidationContext)

Bases: graphql.validation.rules.ASTValidationRule

Unique variable names

A GraphQL operation is only valid if all its variables are uniquely named.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ASTValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_operation_definition(*_args)
enter_variable_definition(node: graphql.language.ast.VariableDefinitionNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.ValuesOfCorrectTypeRule(context: graphql.validation.validation_context.ValidationContext)

Bases: graphql.validation.rules.ValidationRule

Value literals of correct type

A GraphQL document is only valid if all value literals are of the type expected at their position.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_boolean_value(node: graphql.language.ast.BooleanValueNode, *_args)
enter_enum_value(node: graphql.language.ast.EnumValueNode, *_args)
enter_float_value(node: graphql.language.ast.FloatValueNode, *_args)
enter_int_value(node: graphql.language.ast.IntValueNode, *_args)
enter_list_value(node: graphql.language.ast.ListValueNode, *_args)
enter_null_value(node: graphql.language.ast.NullValueNode, *_args)
enter_object_field(node: graphql.language.ast.ObjectFieldNode, *_args)
enter_object_value(node: graphql.language.ast.ObjectValueNode, *_args)
enter_string_value(node: graphql.language.ast.StringValueNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

is_valid_value_node(node: graphql.language.ast.ValueNode) → None

Check whether this is a valid value node.

Any value literal may be a valid representation of a Scalar, depending on that scalar type.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.VariablesAreInputTypesRule(context: graphql.validation.validation_context.ValidationContext)

Bases: graphql.validation.rules.ValidationRule

Variables are input types

A GraphQL operation is only valid if all the variables it defines are of input types (scalar, enum, or input object).

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_variable_definition(node: graphql.language.ast.VariableDefinitionNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.VariablesInAllowedPositionRule(context: graphql.validation.validation_context.ValidationContext)

Bases: graphql.validation.rules.ValidationRule

Variables passed to field arguments conform to type

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.ValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_operation_definition(*_args)
enter_variable_definition(node: graphql.language.ast.VariableDefinitionNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

leave_operation_definition(operation: graphql.language.ast.OperationDefinitionNode, *_args)
report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.LoneSchemaDefinitionRule(context: graphql.validation.validation_context.SDLValidationContext)

Bases: graphql.validation.rules.SDLValidationRule

Lone Schema definition

A GraphQL document is only valid if it contains only one schema definition.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.SDLValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_schema_definition(node: graphql.language.ast.SchemaDefinitionNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.UniqueOperationTypesRule(context: graphql.validation.validation_context.SDLValidationContext)

Bases: graphql.validation.rules.SDLValidationRule

Unique operation types

A GraphQL document is only valid if it has only one type per operation.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.SDLValidationContext)

Initialize self. See help(type(self)) for accurate signature.

check_operation_types(node: Union[graphql.language.ast.SchemaDefinitionNode, graphql.language.ast.SchemaExtensionNode], *_args)
context = None
enter_schema_definition(node: Union[graphql.language.ast.SchemaDefinitionNode, graphql.language.ast.SchemaExtensionNode], *_args)
enter_schema_extension(node: Union[graphql.language.ast.SchemaDefinitionNode, graphql.language.ast.SchemaExtensionNode], *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.UniqueTypeNamesRule(context: graphql.validation.validation_context.SDLValidationContext)

Bases: graphql.validation.rules.SDLValidationRule

Unique type names

A GraphQL document is only valid if all defined types have unique names.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.SDLValidationContext)

Initialize self. See help(type(self)) for accurate signature.

check_type_name(node: graphql.language.ast.TypeDefinitionNode, *_args)
context = None
enter_enum_type_definition(node: graphql.language.ast.TypeDefinitionNode, *_args)
enter_input_object_type_definition(node: graphql.language.ast.TypeDefinitionNode, *_args)
enter_interface_type_definition(node: graphql.language.ast.TypeDefinitionNode, *_args)
enter_object_type_definition(node: graphql.language.ast.TypeDefinitionNode, *_args)
enter_scalar_type_definition(node: graphql.language.ast.TypeDefinitionNode, *_args)
enter_union_type_definition(node: graphql.language.ast.TypeDefinitionNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.UniqueEnumValueNamesRule(context: graphql.validation.validation_context.SDLValidationContext)

Bases: graphql.validation.rules.SDLValidationRule

Unique enum value names

A GraphQL enum type is only valid if all its values are uniquely named.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.SDLValidationContext)

Initialize self. See help(type(self)) for accurate signature.

check_value_uniqueness(node: graphql.language.ast.EnumTypeDefinitionNode, *_args)
context = None
enter_enum_type_definition(node: graphql.language.ast.EnumTypeDefinitionNode, *_args)
enter_enum_type_extension(node: graphql.language.ast.EnumTypeDefinitionNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.UniqueFieldDefinitionNamesRule(context: graphql.validation.validation_context.SDLValidationContext)

Bases: graphql.validation.rules.SDLValidationRule

Unique field definition names

A GraphQL complex type is only valid if all its fields are uniquely named.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.SDLValidationContext)

Initialize self. See help(type(self)) for accurate signature.

check_field_uniqueness(node: graphql.language.ast.ObjectTypeDefinitionNode, *_args)
context = None
enter_input_object_type_definition(node: graphql.language.ast.ObjectTypeDefinitionNode, *_args)
enter_input_object_type_extension(node: graphql.language.ast.ObjectTypeDefinitionNode, *_args)
enter_interface_type_definition(node: graphql.language.ast.ObjectTypeDefinitionNode, *_args)
enter_interface_type_extension(node: graphql.language.ast.ObjectTypeDefinitionNode, *_args)
enter_object_type_definition(node: graphql.language.ast.ObjectTypeDefinitionNode, *_args)
enter_object_type_extension(node: graphql.language.ast.ObjectTypeDefinitionNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.UniqueDirectiveNamesRule(context: graphql.validation.validation_context.SDLValidationContext)

Bases: graphql.validation.rules.SDLValidationRule

Unique directive names

A GraphQL document is only valid if all defined directives have unique names.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.SDLValidationContext)

Initialize self. See help(type(self)) for accurate signature.

context = None
enter_directive_definition(node: graphql.language.ast.DirectiveDefinitionNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
class graphql.PossibleTypeExtensionsRule(context: graphql.validation.validation_context.SDLValidationContext)

Bases: graphql.validation.rules.SDLValidationRule

Possible type extension

A type extension is only valid if the type is defined and has the same kind.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(context: graphql.validation.validation_context.SDLValidationContext)

Initialize self. See help(type(self)) for accurate signature.

check_extension(node: graphql.language.ast.TypeExtensionNode, *_args)
context = None
enter_enum_type_extension(node: graphql.language.ast.TypeExtensionNode, *_args)
enter_input_object_type_extension(node: graphql.language.ast.TypeExtensionNode, *_args)
enter_interface_type_extension(node: graphql.language.ast.TypeExtensionNode, *_args)
enter_object_type_extension(node: graphql.language.ast.TypeExtensionNode, *_args)
enter_scalar_type_extension(node: graphql.language.ast.TypeExtensionNode, *_args)
enter_union_type_extension(node: graphql.language.ast.TypeExtensionNode, *_args)
classmethod get_visit_fn(kind, is_leaving=False) → Callable

Get the visit function for the given node kind and direction.

report_error(error: graphql.error.graphql_error.GraphQLError)
exception graphql.GraphQLError(message: str, nodes: Union[Collection[Node], Node, None] = None, source: Optional[Source] = None, positions: Optional[Collection[int]] = None, path: Optional[Collection[Union[str, int]]] = None, original_error: Optional[Exception] = None, extensions: Optional[Dict[str, Any]] = None)

Bases: Exception

GraphQL Error

A GraphQLError describes an Error found during the parse, validate, or execute phases of performing a GraphQL operation. In addition to a message, it also includes information about the locations in a GraphQL document and/or execution result that correspond to the Error.

__init__(message: str, nodes: Union[Collection[Node], Node, None] = None, source: Optional[Source] = None, positions: Optional[Collection[int]] = None, path: Optional[Collection[Union[str, int]]] = None, original_error: Optional[Exception] = None, extensions: Optional[Dict[str, Any]] = None) → None

Initialize self. See help(type(self)) for accurate signature.

args
extensions

Extension fields to add to the formatted error

property formatted

Get error formatted according to the specification.

locations

Source locations

A list of (line, column) locations within the source GraphQL document which correspond to this error.

Errors during validation often contain multiple locations, for example to point out two things with the same name. Errors during execution include a single location, the field which produced the error.

message

A message describing the Error for debugging purposes

Note: should be treated as readonly, despite invariant usage.

nodes

A list of GraphQL AST Nodes corresponding to this error

original_error

The original error thrown from a field resolver during execution

path

A list of field names and array indexes describing the JSON-path into the execution response which corresponds to this error.

Only included for errors during execution.

positions

Error positions

A list of character offsets within the source GraphQL document which correspond to this error.

source

The source GraphQL document for the first location of this error

Note that if this Error represents more than one node, the source may not represent nodes after the first node.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception graphql.GraphQLSyntaxError(source, position, description)

Bases: graphql.error.graphql_error.GraphQLError

A GraphQLError representing a syntax error.

__init__(source, position, description)

Initialize self. See help(type(self)) for accurate signature.

args
extensions
property formatted

Get error formatted according to the specification.

locations
message
nodes
original_error
path
positions
source
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

graphql.located_error(original_error: Union[Exception, graphql.error.graphql_error.GraphQLError], nodes: Collection[Node], path: Collection[Union[str, int]]) → graphql.error.graphql_error.GraphQLError

Located GraphQL Error

Given an arbitrary Error, presumably thrown while attempting to execute a GraphQL operation, produce a new GraphQLError aware of the location in the document responsible for the original Error.

graphql.format_error(error: GraphQLError) → Dict[str, Any]

Format a GraphQL error.

Given a GraphQLError, format it according to the rules described by the “Response Format, Errors” section of the GraphQL Specification.

graphql.print_error(error: graphql.error.graphql_error.GraphQLError) → str

Print a GraphQLError to a string.

Represents useful location information about the error’s position in the source.

graphql.get_introspection_query(descriptions=True) → str

Get a query for introspection, optionally without descriptions.

graphql.get_operation_ast(document_ast: graphql.language.ast.DocumentNode, operation_name: Optional[str] = None) → Optional[graphql.language.ast.OperationDefinitionNode]

Get operation AST node.

Returns an operation AST given a document AST and optionally an operation name. If a name is not provided, an operation is only returned if only one is provided in the document.

graphql.get_operation_root_type(schema: graphql.type.schema.GraphQLSchema, operation: Union[graphql.language.ast.OperationDefinitionNode, graphql.language.ast.OperationTypeDefinitionNode]) → graphql.type.definition.GraphQLObjectType

Extract the root type of the operation from the schema.

graphql.introspection_from_schema(schema: graphql.type.schema.GraphQLSchema, descriptions: bool = True) → Dict[str, Any]

Build an IntrospectionQuery from a GraphQLSchema

IntrospectionQuery is useful for utilities that care about type and field relationships, but do not need to traverse through those relationships.

This is the inverse of build_client_schema. The primary use case is outside of the server context, for instance when doing schema comparisons.

graphql.build_client_schema(introspection: Dict, assume_valid: bool = False) → graphql.type.schema.GraphQLSchema

Build a GraphQLSchema for use by client tools.

Given the result of a client running the introspection query, creates and returns a GraphQLSchema instance which can be then used with all GraphQL-core 3 tools, but cannot be used to execute a query, as introspection does not represent the “resolver”, “parse” or “serialize” functions or any other server-internal mechanisms.

This function expects a complete introspection result. Don’t forget to check the “errors” field of a server response before calling this function.

graphql.build_ast_schema(document_ast: graphql.language.ast.DocumentNode, assume_valid: bool = False, assume_valid_sdl: bool = False) → graphql.type.schema.GraphQLSchema

Build a GraphQL Schema from a given AST.

This takes the ast of a schema document produced by the parse function in src/language/parser.py.

If no schema definition is provided, then it will look for types named Query and Mutation.

Given that AST it constructs a GraphQLSchema. The resulting schema has no resolve methods, so execution will use default resolvers.

When building a schema from a GraphQL service’s introspection result, it might be safe to assume the schema is valid. Set assume_valid to True to assume the produced schema is valid. Set assume_valid_sdl to True to assume it is already a valid SDL document.

graphql.build_schema(source: Union[str, graphql.language.source.Source], assume_valid=False, assume_valid_sdl=False, no_location=False, experimental_fragment_variables=False) → graphql.type.schema.GraphQLSchema

Build a GraphQLSchema directly from a source document.

graphql.get_description(node: graphql.language.ast.Node) → Optional[str]

@deprecated: Given an ast node, returns its string description.

graphql.extend_schema(schema: graphql.type.schema.GraphQLSchema, document_ast: graphql.language.ast.DocumentNode, assume_valid=False, assume_valid_sdl=False) → graphql.type.schema.GraphQLSchema

Extend the schema with extensions from a given document.

Produces a new schema given an existing schema and a document which may contain GraphQL type extensions and definitions. The original schema will remain unaltered.

Because a schema represents a graph of references, a schema cannot be extended without effectively making an entire copy. We do not know until it’s too late if subgraphs remain unchanged.

This algorithm copies the provided schema, applying extensions while producing the copy. The original schema remains unaltered.

When extending a schema with a known valid extension, it might be safe to assume the schema is valid. Set assume_valid to true to assume the produced schema is valid. Set assume_valid_sdl to True to assume it is already a valid SDL document.

graphql.lexicographic_sort_schema(schema: graphql.type.schema.GraphQLSchema) → graphql.type.schema.GraphQLSchema

Sort GraphQLSchema.

This function returns a sorted copy of the given GraphQLSchema.

graphql.print_schema(schema: graphql.type.schema.GraphQLSchema) → str
graphql.print_type(type_: graphql.type.definition.GraphQLNamedType) → str
graphql.print_introspection_schema(schema: graphql.type.schema.GraphQLSchema) → str
graphql.type_from_ast(schema, type_node)

Get the GraphQL type definition from an AST node.

Given a Schema and an AST node describing a type, return a GraphQLType definition which applies to that type. For example, if provided the parsed AST node for [User], a GraphQLList instance will be returned, containing the type called “User” found in the schema. If a type called “User” is not found in the schema, then None will be returned.

graphql.value_from_ast(value_node: Optional[graphql.language.ast.ValueNode], type_: Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLInputObjectType, graphql.type.definition.GraphQLWrappingType], variables: Optional[Dict[str, Any]] = None) → Any

Produce a Python value given a GraphQL Value AST.

A GraphQL type must be provided, which will be used to interpret different GraphQL Value literals.

Returns Undefined when the value could not be validly coerced according to the provided type.

GraphQL Value | JSON Value | Python Value |
——————– | ————- | ———— |
Input Object | Object | dict |
List | Array | list |
Boolean | Boolean | bool |
String | String | str |
Int / Float | Number | int / float |
Enum Value | Mixed | Any |
NullValue | null | None |
graphql.value_from_ast_untyped(value_node: graphql.language.ast.ValueNode, variables: Optional[Dict[str, Any]] = None) → Any

Produce a Python value given a GraphQL Value AST.

Unlike value_from_ast(), no type is provided. The resulting Python value will reflect the provided GraphQL value AST.

GraphQL Value | JSON Value | Python Value |
——————– | ———- | ———— |
Input Object | Object | dict |
List | Array | list |
Boolean | Boolean | bool |
String / Enum | String | str |
Int / Float | Number | int / float |
Null | null | None |
graphql.ast_from_value(value: Any, type_: Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLInputObjectType, graphql.type.definition.GraphQLWrappingType]) → Optional[graphql.language.ast.ValueNode]

Produce a GraphQL Value AST given a Python object.

This function will match Python/JSON values to GraphQL AST schema format by using the suggested GraphQLInputType. For example:

ast_from_value('value', GraphQLString)

A GraphQL type must be provided, which will be used to interpret different Python values.

JSON Value | GraphQL Value |
————- | ——————– |
Object | Input Object |
Array | List |
Boolean | Boolean |
String | String / Enum Value |
Number | Int / Float |
Mixed | Enum Value |
null | NullValue |
class graphql.TypeInfo(schema: graphql.type.schema.GraphQLSchema, get_field_def_fn: Optional[Callable[[graphql.type.schema.GraphQLSchema, graphql.type.definition.GraphQLType, graphql.language.ast.FieldNode], Optional[graphql.type.definition.GraphQLField]]] = None, initial_type: Optional[graphql.type.definition.GraphQLType] = None)

Bases: object

Utility class for keeping track of type definitions.

TypeInfo is a utility class which, given a GraphQL schema, can keep track of the current field and type definitions at any point in a GraphQL document AST during a recursive descent by calling enter(node) and leave(node).

__init__(schema: graphql.type.schema.GraphQLSchema, get_field_def_fn: Optional[Callable[[graphql.type.schema.GraphQLSchema, graphql.type.definition.GraphQLType, graphql.language.ast.FieldNode], Optional[graphql.type.definition.GraphQLField]]] = None, initial_type: Optional[graphql.type.definition.GraphQLType] = None) → None

Initialize the TypeInfo for the given GraphQL schema.

The experimental optional second parameter is only needed in order to support non-spec-compliant code bases. You should never need to use it. It may disappear in the future.

Initial type may be provided in rare cases to facilitate traversals beginning somewhere other than documents.

enter(node: graphql.language.ast.Node)
enter_argument(node: graphql.language.ast.ArgumentNode)
enter_directive(node: graphql.language.ast.DirectiveNode)
enter_enum_value(node: graphql.language.ast.EnumValueNode)
enter_field(node: graphql.language.ast.FieldNode)
enter_fragment_definition(node: graphql.language.ast.InlineFragmentNode)
enter_inline_fragment(node: graphql.language.ast.InlineFragmentNode)
enter_list_value(node: graphql.language.ast.ListValueNode)
enter_object_field(node: graphql.language.ast.ObjectFieldNode)
enter_operation_definition(node: graphql.language.ast.OperationDefinitionNode)
enter_selection_set(node: graphql.language.ast.SelectionSetNode)
enter_variable_definition(node: graphql.language.ast.VariableDefinitionNode)
get_argument()
get_default_value()
get_directive()
get_enum_value()
get_field_def()
get_input_type()
get_parent_input_type()
get_parent_type()
get_type()
leave(node: graphql.language.ast.Node)
leave_argument()
leave_directive()
leave_enum()
leave_field()
leave_fragment_definition()
leave_inline_fragment()
leave_list_value()
leave_object_field()
leave_operation_definition()
leave_selection_set()
leave_variable_definition()
graphql.coerce_input_value(input_value: Any, type_: Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLInputObjectType, graphql.type.definition.GraphQLWrappingType], on_error: Callable[[List[Union[str, int]], Any, graphql.error.graphql_error.GraphQLError], None] = <function default_on_error>, path: Optional[graphql.pyutils.path.Path] = None) → Any

Coerce a Python value given a GraphQL Input Type.

graphql.concat_ast(asts: Collection[graphql.language.ast.DocumentNode]) → graphql.language.ast.DocumentNode

Concat ASTs.

Provided a collection of ASTs, presumably each from different files, concatenate the ASTs together into batched AST, useful for validating many GraphQL source files which together represent one conceptual application.

graphql.separate_operations(document_ast: graphql.language.ast.DocumentNode) → Dict[str, graphql.language.ast.DocumentNode]

Separate operations in a given AST document.

This function accepts a single AST document which may contain many operations and fragments and returns a collection of AST documents each of which contains a single operation as well the fragment definitions it refers to.

graphql.strip_ignored_characters(source: Union[str, graphql.language.source.Source]) → str

Strip characters that are ignored anyway.

Strips characters that are not significant to the validity or execution of a GraphQL document:

  • UnicodeBOM

  • WhiteSpace

  • LineTerminator

  • Comment

  • Comma

  • BlockString indentation

Note: It is required to have a delimiter character between neighboring non-punctuator tokes and this function always uses single space as delimiter.

It is guaranteed that both input and output documents if parsed would result in the exact same AST except for nodes location.

Warning: It is guaranteed that this function will always produce stable results. However, it’s not guaranteed that it will stay the same between different releases due to bugfixes or changes in the GraphQL specification.

Query example:

query SomeQuery($foo: String!, $bar: String) {
  someField(foo: $foo, bar: $bar) {
    a
    b {
      c
      d
    }
  }
}

Becomes:

query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}}

SDL example:

"""
Type description
"""
type Foo {
  """
  Field description
  """
  bar: String
}

Becomes:

"""Type description""" type Foo{"""Field description""" bar:String}
graphql.is_equal_type(type_a: graphql.type.definition.GraphQLType, type_b: graphql.type.definition.GraphQLType)

Check whether two types are equal.

Provided two types, return true if the types are equal (invariant).

graphql.is_type_sub_type_of(schema: graphql.type.schema.GraphQLSchema, maybe_subtype: graphql.type.definition.GraphQLType, super_type: graphql.type.definition.GraphQLType) → bool

Check whether a type is subtype of another type in a given schema.

Provided a type and a super type, return true if the first type is either equal or a subset of the second super type (covariant).

graphql.do_types_overlap(schema, type_a, type_b)

Check whether two types overlap in a given schema.

Provided two composite types, determine if they “overlap”. Two composite types overlap when the Sets of possible concrete types for each intersect.

This is often used to determine if a fragment of a given type could possibly be visited in a context of another type.

This function is commutative.

graphql.assert_valid_name(name: str) → str

Uphold the spec rules about naming.

graphql.is_valid_name_error(name: str, node: Optional[graphql.language.ast.Node] = None) → Optional[graphql.error.graphql_error.GraphQLError]

Return an Error if a name is invalid.

graphql.find_breaking_changes(old_schema: graphql.type.schema.GraphQLSchema, new_schema: graphql.type.schema.GraphQLSchema) → List[graphql.utilities.find_breaking_changes.BreakingChange]

Find breaking changes.

Given two schemas, returns a list containing descriptions of all the types of breaking changes covered by the other functions down below.

graphql.find_dangerous_changes(old_schema: graphql.type.schema.GraphQLSchema, new_schema: graphql.type.schema.GraphQLSchema) → List[graphql.utilities.find_breaking_changes.DangerousChange]

Find dangerous changes.

Given two schemas, returns a list containing descriptions of all the types of potentially dangerous changes covered by the other functions down below.

class graphql.BreakingChange(type, description)

Bases: tuple

__init__()

Initialize self. See help(type(self)) for accurate signature.

_asdict()

Return a new OrderedDict which maps field names to their values.

_field_defaults = {}
_field_types = {'description': <class 'str'>, 'type': <enum 'BreakingChangeType'>}
_fields = ('type', 'description')
_fields_defaults = {}
classmethod _make(iterable)

Make a new BreakingChange object from a sequence or iterable

_replace(**kwds)

Return a new BreakingChange object replacing specified fields with new values

count()

Return number of occurrences of value.

property description

Alias for field number 1

index()

Return first index of value.

Raises ValueError if the value is not present.

property type

Alias for field number 0

class graphql.BreakingChangeType

Bases: enum.Enum

An enumeration.

ARG_CHANGED_KIND = 42
ARG_REMOVED = 41
DIRECTIVE_ARG_REMOVED = 51
DIRECTIVE_LOCATION_REMOVED = 53
DIRECTIVE_REMOVED = 50
FIELD_CHANGED_KIND = 31
FIELD_REMOVED = 30
IMPLEMENTED_INTERFACE_REMOVED = 23
REQUIRED_ARG_ADDED = 40
REQUIRED_DIRECTIVE_ARG_ADDED = 52
REQUIRED_INPUT_FIELD_ADDED = 22
TYPE_CHANGED_KIND = 11
TYPE_REMOVED = 10
TYPE_REMOVED_FROM_UNION = 20
VALUE_REMOVED_FROM_ENUM = 21
class graphql.DangerousChange(type, description)

Bases: tuple

__init__()

Initialize self. See help(type(self)) for accurate signature.

_asdict()

Return a new OrderedDict which maps field names to their values.

_field_defaults = {}
_field_types = {'description': <class 'str'>, 'type': <enum 'DangerousChangeType'>}
_fields = ('type', 'description')
_fields_defaults = {}
classmethod _make(iterable)

Make a new DangerousChange object from a sequence or iterable

_replace(**kwds)

Return a new DangerousChange object replacing specified fields with new values

count()

Return number of occurrences of value.

property description

Alias for field number 1

index()

Return first index of value.

Raises ValueError if the value is not present.

property type

Alias for field number 0

class graphql.DangerousChangeType

Bases: enum.Enum

An enumeration.

ARG_DEFAULT_VALUE_CHANGE = 65
IMPLEMENTED_INTERFACE_ADDED = 64
OPTIONAL_ARG_ADDED = 63
OPTIONAL_INPUT_FIELD_ADDED = 62
TYPE_ADDED_TO_UNION = 61
VALUE_ADDED_TO_ENUM = 60
exception graphql.UndefinedType

Bases: ValueError

Auxiliary class for creating the Undefined singleton.

__init__()

Initialize self. See help(type(self)) for accurate signature.

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

Top-Level Functions

async graphql.graphql(schema: graphql.type.schema.GraphQLSchema, source: Union[str, graphql.language.source.Source], root_value: Any = None, context_value: Any = None, variable_values: Optional[Dict[str, Any]] = None, operation_name: Optional[str] = None, field_resolver: Optional[Callable[[...], Any]] = None, type_resolver: Optional[Callable[[Any, graphql.type.definition.GraphQLResolveInfo, GraphQLAbstractType], Union[Awaitable[Union[GraphQLObjectType, str, None]], GraphQLObjectType, str, None]]] = None, middleware: Union[Tuple, List, graphql.execution.middleware.MiddlewareManager, None] = None, execution_context_class: Type[graphql.execution.execute.ExecutionContext] = <class 'graphql.execution.execute.ExecutionContext'>) → graphql.execution.execute.ExecutionResult

Execute a GraphQL operation asynchronously.

This is the primary entry point function for fulfilling GraphQL operations by parsing, validating, and executing a GraphQL document along side a GraphQL schema.

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.

Accepts the following arguments:

Parameters
  • schema – The GraphQL type system to use when validating and executing a query.

  • source – A GraphQL language formatted string representing the requested operation.

  • root_value – The value provided as the first argument to resolver functions on the top level type (e.g. the query object type).

  • context_value – The context value is provided as an attribute of the second argument (the resolve info) to resolver functions. It is used to pass shared information useful at any point during query execution, for example the currently logged in user and connections to databases or other services.

  • variable_values – A mapping of variable name to runtime value to use for all variables defined in the request string.

  • operation_name – The name of the operation to use if request string contains multiple possible operations. Can be omitted if request string contains only one operation.

  • field_resolver – A resolver function to use when one is not provided by the schema. If not provided, the default field resolver is used (which looks for a value or method on the source value with the field’s name).

  • type_resolver – A type resolver function to use when none is provided by the schema. If not provided, the default type resolver is used (which looks for a __typename field or alternatively calls the is_type_of method).

  • middleware – The middleware to wrap the resolvers with

  • execution_context_class – The execution context class to use to build the context

graphql.graphql_sync(schema: graphql.type.schema.GraphQLSchema, source: Union[str, graphql.language.source.Source], root_value: Any = None, context_value: Any = None, variable_values: Optional[Dict[str, Any]] = None, operation_name: Optional[str] = None, field_resolver: Optional[Callable[[...], Any]] = None, type_resolver: Optional[Callable[[Any, graphql.type.definition.GraphQLResolveInfo, GraphQLAbstractType], Union[Awaitable[Union[GraphQLObjectType, str, None]], GraphQLObjectType, str, None]]] = None, middleware: Union[Tuple, List, graphql.execution.middleware.MiddlewareManager, None] = None, execution_context_class: Type[graphql.execution.execute.ExecutionContext] = <class 'graphql.execution.execute.ExecutionContext'>) → graphql.execution.execute.ExecutionResult

Execute a GraphQL operation synchronously.

The graphql_sync function also fulfills GraphQL operations by parsing, validating, and executing a GraphQL document along side a GraphQL schema. However, it guarantees to complete synchronously (or throw an error) assuming that all field resolvers are also synchronous.