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=True) → str

Get a query for introspection, optionally without descriptions.

Get the target Operation from a Document:

graphql.utilities.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.

Get the Type for the target Operation AST:

graphql.utilities.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.

Convert a GraphQLSchema to an IntrospectionQuery:

graphql.utilities.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.

Build a GraphQLSchema from an introspection result:

graphql.utilities.build_client_schema(introspection: Dict[KT, VT], 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.

Build a GraphQLSchema from GraphQL Schema language:

graphql.utilities.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.utilities.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.utilities.get_description(node: graphql.language.ast.Node) → Optional[str]

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

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

graphql.utilities.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.

Sort a GraphQLSchema: .. autofunction:: lexicographic_sort_schema

Print a GraphQLSchema to GraphQL Schema language:

graphql.utilities.print_introspection_schema(schema: graphql.type.schema.GraphQLSchema) → str
graphql.utilities.print_schema(schema: graphql.type.schema.GraphQLSchema) → str
graphql.utilities.print_type(type_: graphql.type.definition.GraphQLNamedType) → str
graphql.utilities.print_value(value: Any, type_: Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLInputObjectType, graphql.type.definition.GraphQLWrappingType]) → str

Convenience function for printing a Python value

Create a GraphQLType from a GraphQL language AST:

graphql.utilities.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.

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

graphql.utilities.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: 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 INVALID 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: graphql.language.ast.ValueNode, variables: 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 |

Create a GraphQL language AST from a Python value:

graphql.utilities.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 value.

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: graphql.type.schema.GraphQLSchema, get_field_def_fn: Callable[[graphql.type.schema.GraphQLSchema, graphql.type.definition.GraphQLType, graphql.language.ast.FieldNode], Optional[graphql.type.definition.GraphQLField]] = None, initial_type: graphql.type.definition.GraphQLType = None)

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

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

graphql.utilities.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: graphql.pyutils.path.Path = None) → Any

Coerce a Python value given a GraphQL Input Type.

Deprecated, use coerce_input_value():

graphql.utilities.coerce_value(input_value: Any, type_: Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLInputObjectType, graphql.type.definition.GraphQLWrappingType], blame_node: graphql.language.ast.Node = None, path: graphql.pyutils.path.Path = None) → graphql.utilities.coerce_value.CoercedValue

Coerce a Python value given a GraphQL Type.

Deprecated. Use coerce_input_value() directly for richer information.

Concatenate multiple ASTs together:

graphql.utilities.concat_ast(asts: Sequence[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.

Separate an AST into an AST per Operation:

graphql.utilities.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.

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

graphql.utilities.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}

Comparators for types:

graphql.utilities.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.utilities.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.utilities.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.

Assert that a string is a valid GraphQL name:

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

Uphold the spec rules about naming.

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

Return an Error if a name is invalid.

Compare two GraphQLSchemas and detect breaking changes:

graphql.utilities.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.utilities.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.utilities.BreakingChange(type, description)
class graphql.utilities.BreakingChangeType

An enumeration.

class graphql.utilities.DangerousChange(type, description)
class graphql.utilities.DangerousChangeType

An enumeration.

Report all deprecated usages within a GraphQL document:

graphql.utilities.find_deprecated_usages(schema: graphql.type.schema.GraphQLSchema, ast: graphql.language.ast.DocumentNode) → List[graphql.error.graphql_error.GraphQLError]

Get a list of GraphQLError instances describing each deprecated use.