Utilities

GraphQL Utilities

The graphql.utilities package contains common useful computations to use with the GraphQL language and type objects.

The GraphQL query recommended for a full schema introspection:

graphql.utilities.get_introspection_query(descriptions: bool = True, specified_by_url: bool = False, directive_is_repeatable: bool = False, schema_description: bool = False, input_value_deprecation: bool = False) str

Get a query for introspection.

Optionally, you can exclude descriptions, include specification URLs, include repeatability of directives, and specify whether to include the schema description as well.

class graphql.utilities.IntrospectionQuery

Bases: TypedDict

The root typed dictionary for schema introspections.

Get the target Operation from a Document:

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

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.

Convert a GraphQLSchema to an IntrospectionQuery:

graphql.utilities.introspection_from_schema(schema: GraphQLSchema, descriptions: bool = True, specified_by_url: bool = True, directive_is_repeatable: bool = True, schema_description: bool = True, input_value_deprecation: bool = True) IntrospectionQuery

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.

Build a GraphQLSchema from an introspection result:

graphql.utilities.build_client_schema(introspection: IntrospectionQuery, assume_valid: bool = False) 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.

Build a GraphQLSchema from GraphQL Schema language:

graphql.utilities.build_ast_schema(document_ast: DocumentNode, assume_valid: bool = False, assume_valid_sdl: bool = False) 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, Mutation and Subscription.

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.utilities.build_schema(source: str | graphql.language.source.Source, assume_valid: bool = False, assume_valid_sdl: bool = False, no_location: bool = False, allow_legacy_fragment_variables: bool = False) GraphQLSchema

Build a GraphQLSchema directly from a source document.

Extend an existing GraphQLSchema from a parsed GraphQL Schema language AST:

graphql.utilities.extend_schema(schema: GraphQLSchema, document_ast: DocumentNode, assume_valid: bool = False, assume_valid_sdl: bool = False) 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.

Sort a GraphQLSchema:

graphql.utilities.lexicographic_sort_schema(schema: GraphQLSchema) GraphQLSchema

Sort GraphQLSchema.

This function returns a sorted copy of the given GraphQLSchema.

Print a GraphQLSchema to GraphQL Schema language:

graphql.utilities.print_schema(schema: GraphQLSchema) str

Print the given GraphQL schema in SDL format.

graphql.utilities.print_type(type_: GraphQLNamedType) str

Print a named GraphQL type.

graphql.utilities.print_directive(directive: GraphQLDirective) str

Print a GraphQL directive.

graphql.utilities.print_introspection_schema(schema: GraphQLSchema) str

Print the built-in introspection schema in SDL format.

Create a GraphQLType from a GraphQL language AST:

graphql.utilities.type_from_ast(schema: GraphQLSchema, type_node: NamedTypeNode) graphql.type.definition.GraphQLNamedType | None
graphql.utilities.type_from_ast(schema: GraphQLSchema, type_node: ListTypeNode) graphql.type.definition.GraphQLList | None
graphql.utilities.type_from_ast(schema: GraphQLSchema, type_node: NonNullTypeNode) graphql.type.definition.GraphQLNonNull | None
graphql.utilities.type_from_ast(schema: GraphQLSchema, type_node: TypeNode) graphql.type.definition.GraphQLType | None

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.

Convert a language AST to a dictionary:

graphql.utilities.ast_to_dict(node: Node, locations: bool = False, cache: dict[graphql.language.ast.Node, Any] | None = None) dict
graphql.utilities.ast_to_dict(node: Collection[Node], locations: bool = False, cache: dict[graphql.language.ast.Node, Any] | None = None) list[graphql.language.ast.Node]
graphql.utilities.ast_to_dict(node: OperationType, locations: bool = False, cache: dict[graphql.language.ast.Node, Any] | None = None) str

Convert a language AST to a nested Python dictionary.

Set location to True in order to get the locations as well.

Create a Python value from a GraphQL language AST with a type:

graphql.utilities.value_from_ast(value_node: graphql.language.ast.ValueNode | None, type_: Union[GraphQLScalarType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull[Union[GraphQLScalarType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList]]], 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

Create a Python value from a GraphQL language AST without a type:

graphql.utilities.value_from_ast_untyped(value_node: ValueNode, variables: dict[str, Any] | None = 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

Create a GraphQL language AST from a Python value:

graphql.utilities.ast_from_value(value: Any, type_: Union[GraphQLScalarType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull[Union[GraphQLScalarType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList]]]) Optional[Union[IntValueNode, FloatValueNode, StringValueNode, BooleanValueNode, NullValueNode, EnumValueNode, ConstListValueNode, ConstObjectValueNode]]

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

A helper to use within recursive-descent visitors which need to be aware of the GraphQL type system:

class graphql.utilities.TypeInfo(schema: GraphQLSchema, initial_type: Optional[GraphQLType] = None, get_field_def_fn: Optional[Callable[[GraphQLSchema, Union[GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType], FieldNode], Optional[GraphQLField]]] = 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: GraphQLSchema, initial_type: Optional[GraphQLType] = None, get_field_def_fn: Optional[Callable[[GraphQLSchema, Union[GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType], FieldNode], Optional[GraphQLField]]] = None) None

Initialize the TypeInfo for the given GraphQL schema.

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

The optional last parameter is deprecated and will be removed in v3.3.

enter(node: Node) None
enter_argument(node: ArgumentNode) None
enter_directive(node: DirectiveNode) None
enter_enum_value(node: EnumValueNode) None
enter_field(node: FieldNode) None
enter_fragment_definition(node: InlineFragmentNode) None
enter_inline_fragment(node: InlineFragmentNode) None
enter_list_value(_node: ListValueNode) None
enter_object_field(node: ObjectFieldNode) None
enter_operation_definition(node: OperationDefinitionNode) None
enter_selection_set(_node: SelectionSetNode) None
enter_variable_definition(node: VariableDefinitionNode) None
get_argument() graphql.type.definition.GraphQLArgument | None
get_default_value() Any
get_directive() graphql.type.directives.GraphQLDirective | None
get_enum_value() graphql.type.definition.GraphQLEnumValue | None
get_field_def() graphql.type.definition.GraphQLField | None
get_input_type() Optional[Union[GraphQLScalarType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull[Union[GraphQLScalarType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList]]]]
get_parent_input_type() Optional[Union[GraphQLScalarType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull[Union[GraphQLScalarType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList]]]]
get_parent_type() Optional[Union[GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType]]
get_type() Optional[Union[GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLList, GraphQLNonNull[Union[GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLList]]]]
leave(node: Node) None
leave_argument() None
leave_directive() None
leave_enum_value() None
leave_field() None
leave_fragment_definition() None
leave_inline_fragment() None
leave_list_value() None
leave_object_field() None
leave_operation_definition() None
leave_selection_set() None
leave_variable_definition() None
class graphql.utilities.TypeInfoVisitor(type_info: TypeInfo, visitor: Visitor)

Bases: Visitor

A visitor which maintains a provided TypeInfo.

BREAK = True
IDLE = None
REMOVE = Ellipsis
SKIP = False
__init__(type_info: TypeInfo, visitor: Visitor) None
enter(node: Node, *args: Any) Any
enter_leave_map: dict[str, EnterLeaveVisitor]
get_enter_leave_for_kind(kind: str) EnterLeaveVisitor

Given a node kind, return the EnterLeaveVisitor for that kind.

leave(node: Node, *args: Any) Any

Coerce a Python value to a GraphQL type, or produce errors:

graphql.utilities.coerce_input_value(input_value: ~typing.Any, type_: ~typing.Union[~graphql.type.definition.GraphQLScalarType, ~graphql.type.definition.GraphQLEnumType, ~graphql.type.definition.GraphQLInputObjectType, ~graphql.type.definition.GraphQLList, ~graphql.type.definition.GraphQLNonNull[~typing.Union[~graphql.type.definition.GraphQLScalarType, ~graphql.type.definition.GraphQLEnumType, ~graphql.type.definition.GraphQLInputObjectType, ~graphql.type.definition.GraphQLList]]], on_error: ~typing.Callable[[~typing.List[~typing.Union[str, int]], ~typing.Any, ~graphql.error.graphql_error.GraphQLError], None] = <function default_on_error>, path: ~typing.Optional[~graphql.pyutils.path.Path] = None) Any

Coerce a Python value given a GraphQL Input Type.

Concatenate multiple ASTs together:

graphql.utilities.concat_ast(asts: Collection[DocumentNode]) 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.

Separate an AST into an AST per Operation:

graphql.utilities.separate_operations(document_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.

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

graphql.utilities.strip_ignored_characters(source: 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}

Comparators for types:

graphql.utilities.is_equal_type(type_a: GraphQLType, type_b: GraphQLType) bool

Check whether two types are equal.

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

graphql.utilities.is_type_sub_type_of(schema: GraphQLSchema, maybe_subtype: GraphQLType, super_type: 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.utilities.do_types_overlap(schema: GraphQLSchema, type_a: Union[GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType], type_b: Union[GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType]) bool

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.

Compare two GraphQLSchemas and detect breaking changes:

graphql.utilities.find_breaking_changes(old_schema: GraphQLSchema, new_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.utilities.find_dangerous_changes(old_schema: GraphQLSchema, new_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.utilities.BreakingChange(type: BreakingChangeType, description: str)

Bases: NamedTuple

Type and description of a breaking change

__init__()
count(value, /)

Return number of occurrences of value.

description: str

Alias for field number 1

index(value, start=0, stop=9223372036854775807, /)

Return first index of value.

Raises ValueError if the value is not present.

type: BreakingChangeType

Alias for field number 0

class graphql.utilities.BreakingChangeType(value)

Bases: Enum

Types of breaking changes

ARG_CHANGED_KIND = 42
ARG_REMOVED = 41
DIRECTIVE_ARG_REMOVED = 51
DIRECTIVE_LOCATION_REMOVED = 54
DIRECTIVE_REMOVED = 50
DIRECTIVE_REPEATABLE_REMOVED = 53
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.utilities.DangerousChange(type: DangerousChangeType, description: str)

Bases: NamedTuple

Type and description of a dangerous change

__init__()
count(value, /)

Return number of occurrences of value.

description: str

Alias for field number 1

index(value, start=0, stop=9223372036854775807, /)

Return first index of value.

Raises ValueError if the value is not present.

type: DangerousChangeType

Alias for field number 0

class graphql.utilities.DangerousChangeType(value)

Bases: Enum

Types of dangerous changes

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