# 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, experimental_directive_deprecation: bool = False, input_object_one_of: bool = False, type_depth: int = 9) → 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.

  The `type_depth` argument controls how deep to recurse into nested types. Larger values will result in more accurate results, but have a higher load on the server. Some servers might restrict the maximum query depth or complexity. If that’s the case, try decreasing this value. The default is 9.

class graphql.utilities.IntrospectionQuery

  Bases: `TypedDict`

Get the target Operation from a Document:

graphql.utilities.get_operation_ast(document_ast: DocumentNode, operation_name: str | None = None) → 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.

Get the Type for the target Operation AST:

graphql.utilities.get_operation_root_type(schema: GraphQLSchema, operation: OperationDefinitionNode | OperationTypeDefinitionNode) → GraphQLObjectType

  Extract the root type of the operation from the schema.

  This deprecated helper is retained for backwards compatibility; call `GraphQLSchema.get_root_type` instead because `get_operation_root_type` will be removed in v3.3.

  Deprecated since version 3.2: Please use `GraphQLSchema.get_root_type` instead. Will be removed in v3.3.

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, experimental_directive_deprecation: bool = True, input_object_one_of: 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 | Source, assume_valid: bool = False, assume_valid_sdl: bool = False, no_location: bool = False, allow_legacy_fragment_variables: bool = False, experimental_directives_on_directive_definitions: 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_introspection_schema(schema: GraphQLSchema) → str

graphql.utilities.print_schema(schema: GraphQLSchema) → str

graphql.utilities.print_type(type_: GraphQLNamedType) → str

Create a GraphQLType from a GraphQL language AST:

graphql.utilities.type_from_ast(schema: GraphQLSchema, type_node: NamedTypeNode) → GraphQLNamedType | None
graphql.utilities.type_from_ast(schema: GraphQLSchema, type_node: ListTypeNode) → GraphQLList | None
graphql.utilities.type_from_ast(schema: GraphQLSchema, type_node: NonNullTypeNode) → GraphQLNonNull | None
graphql.utilities.type_from_ast(schema: GraphQLSchema, type_node: TypeNode) → 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[Node, Any] | None = None) → Dict
graphql.utilities.ast_to_dict(node: Collection[Node], locations: bool = False, cache: Dict[Node, Any] | None = None) → List[Node]
graphql.utilities.ast_to_dict(node: OperationType, locations: bool = False, cache: Dict[Node, Any] | None = None) → str

  Convert a language AST to a nested Python dictionary.

  Set locations 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: ValueNode | None, type_: GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLWrappingType, variables: Dict[str, Any] | None = 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_: GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLWrappingType) → ValueNode | None

  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.

  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: GraphQLType | None = None, get_field_def_fn: Callable[[GraphQLSchema, GraphQLType, FieldNode], GraphQLField | None] | None = 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: GraphQLType | None = None, get_field_def_fn: Callable[[GraphQLSchema, GraphQLType, FieldNode], GraphQLField | None] | None = 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 `get_field_def_fn` parameter is deprecated; omit it so that TypeInfo uses its built-in field definition lookup. It 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() → GraphQLArgument | None
  get_default_value() → Any
  get_directive() → GraphQLDirective | None
  get_enum_value() → GraphQLEnumValue | None
  get_field_def() → GraphQLField | None
  get_input_type() → GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLWrappingType | None
  get_parent_input_type() → GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLWrappingType | None
  get_parent_type() → GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | None
  get_type() → GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLWrappingType | None
  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)
  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.

  get_visit_fn(kind: str, is_leaving: bool = False) → Callable[[...], VisitorActionEnum | None] | None

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

    This deprecated compatibility helper delegates to `get_enter_leave_for_kind`; call `get_enter_leave_for_kind` directly because `get_visit_fn` will be removed in v3.3.

    Deprecated since version 3.2: Please use `get_enter_leave_for_kind` instead. Will be removed in v3.3.

  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_: ~graphql.type.definition.GraphQLScalarType | ~graphql.type.definition.GraphQLEnumType | ~graphql.type.definition.GraphQLInputObjectType | ~graphql.type.definition.GraphQLWrappingType, on_error: ~typing.Callable[[~typing.List[str | int], ~typing.Any, ~graphql.error.graphql_error.GraphQLError], None] = <function default_on_error>, path: ~graphql.pyutils.path.Path | None = 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, 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 | 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: GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType, type_b: 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.

Assert that a string is a valid GraphQL name:

graphql.utilities.assert_valid_name(name: str) → str

  Uphold the spec rules about naming.

  This deprecated helper is retained for backwards compatibility; call `assert_name` instead because `assert_valid_name` will be removed in v3.3.

  Deprecated since version 3.2: Please use `assert_name` instead. Will be removed in v3.3.

graphql.utilities.is_valid_name_error(name: str) → GraphQLError | None

  Return an Error if a name is invalid.

  This deprecated helper is retained for backwards compatibility; call `assert_name` and catch the raised GraphQLError instead because `is_valid_name_error` will be removed in v3.3.

  Deprecated since version 3.2: Please use `assert_name` instead. Will be removed in v3.3.

Compare two GraphQLSchemas and detect breaking changes:

graphql.utilities.find_breaking_changes(old_schema: GraphQLSchema, new_schema: GraphQLSchema) → List[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[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, description)

  Bases: `NamedTuple`

  __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(*values)

  Bases: `Enum`

  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, description)

  Bases: `NamedTuple`

  __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(*values)

  Bases: `Enum`

  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

Resolve a schema coordinate to the schema element it refers to:

graphql.utilities.resolve_schema_coordinate(schema: GraphQLSchema, schema_coordinate: str | Source) → ResolvedNamedType | ResolvedField | ResolvedInputField | ResolvedEnumValue | ResolvedFieldArgument | ResolvedDirective | ResolvedDirectiveArgument | None

  Resolve a string schema coordinate in the context of a GraphQL schema.

  A schema coordinate is resolved in the context of a GraphQL schema to uniquely identify a schema element. It returns None if the schema coordinate does not resolve to a schema element, meta-field, or introspection schema element. It will raise an error if the containing schema element (if applicable) does not exist.

  https://spec.graphql.org/draft/#sec-Schema-Coordinates.Semantics

graphql.utilities.resolve_ast_schema_coordinate(schema: GraphQLSchema, schema_coordinate: TypeCoordinateNode | MemberCoordinateNode | ArgumentCoordinateNode | DirectiveCoordinateNode | DirectiveArgumentCoordinateNode) → ResolvedNamedType | ResolvedField | ResolvedInputField | ResolvedEnumValue | ResolvedFieldArgument | ResolvedDirective | ResolvedDirectiveArgument | None

  Resolve schema coordinate from a parsed SchemaCoordinate node.

class graphql.utilities.ResolvedNamedType(type: GraphQLNamedType, kind: str = 'NamedType')

  Bases: `NamedTuple`

  A named type resolved from a schema coordinate.

  __init__()
  count(value, /)

    Return number of occurrences of value.

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

    Return first index of value.

    Raises ValueError if the value is not present.

  kind: str

    Alias for field number 1

  type: GraphQLNamedType

    Alias for field number 0

class graphql.utilities.ResolvedField(type: GraphQLObjectType | GraphQLInterfaceType, field: GraphQLField, kind: str = 'Field')

  Bases: `NamedTuple`

  A field resolved from a schema coordinate.

  __init__()
  count(value, /)

    Return number of occurrences of value.

  field: GraphQLField

    Alias for field number 1

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

    Return first index of value.

    Raises ValueError if the value is not present.

  kind: str

    Alias for field number 2

  type: GraphQLObjectType | GraphQLInterfaceType

    Alias for field number 0

class graphql.utilities.ResolvedInputField(type: GraphQLInputObjectType, input_field: GraphQLInputField, kind: str = 'InputField')

  Bases: `NamedTuple`

  An input field resolved from a schema coordinate.

  __init__()
  count(value, /)

    Return number of occurrences of value.

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

    Return first index of value.

    Raises ValueError if the value is not present.

  input_field: GraphQLInputField

    Alias for field number 1

  kind: str

    Alias for field number 2

  type: GraphQLInputObjectType

    Alias for field number 0

class graphql.utilities.ResolvedEnumValue(type: GraphQLEnumType, enum_value: GraphQLEnumValue, kind: str = 'EnumValue')

  Bases: `NamedTuple`

  An enum value resolved from a schema coordinate.

  __init__()
  count(value, /)

    Return number of occurrences of value.

  enum_value: GraphQLEnumValue

    Alias for field number 1

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

    Return first index of value.

    Raises ValueError if the value is not present.

  kind: str

    Alias for field number 2

  type: GraphQLEnumType

    Alias for field number 0

class graphql.utilities.ResolvedFieldArgument(type: GraphQLObjectType | GraphQLInterfaceType, field: GraphQLField, field_argument: GraphQLArgument, kind: str = 'FieldArgument')

  Bases: `NamedTuple`

  A field argument resolved from a schema coordinate.

  __init__()
  count(value, /)

    Return number of occurrences of value.

  field: GraphQLField

    Alias for field number 1

  field_argument: GraphQLArgument

    Alias for field number 2

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

    Return first index of value.

    Raises ValueError if the value is not present.

  kind: str

    Alias for field number 3

  type: GraphQLObjectType | GraphQLInterfaceType

    Alias for field number 0

class graphql.utilities.ResolvedDirective(directive: GraphQLDirective, kind: str = 'Directive')

  Bases: `NamedTuple`

  A directive resolved from a schema coordinate.

  __init__()
  count(value, /)

    Return number of occurrences of value.

  directive: GraphQLDirective

    Alias for field number 0

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

    Return first index of value.

    Raises ValueError if the value is not present.

  kind: str

    Alias for field number 1

class graphql.utilities.ResolvedDirectiveArgument(directive: GraphQLDirective, directive_argument: GraphQLArgument, kind: str = 'DirectiveArgument')

  Bases: `NamedTuple`

  A directive argument resolved from a schema coordinate.

  __init__()
  count(value, /)

    Return number of occurrences of value.

  directive: GraphQLDirective

    Alias for field number 0

  directive_argument: GraphQLArgument

    Alias for field number 1

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

    Return first index of value.

    Raises ValueError if the value is not present.

  kind: str

    Alias for field number 2

graphql.utilities.ResolvedSchemaElement

  alias of `ResolvedNamedType` | `ResolvedField` | `ResolvedInputField` | `ResolvedEnumValue` | `ResolvedFieldArgument` | `ResolvedDirective` | `ResolvedDirectiveArgument`