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.
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, specified_by_url: bool = True, directive_is_repeatable: bool = True, schema_description: bool = True, input_value_deprecation: 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, 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
toTrue
to assume the produced schema is valid. Setassume_valid_sdl
toTrue
to assume it is already a valid SDL document.
- graphql.utilities.build_schema(source: Union[str, graphql.language.source.Source], assume_valid: bool = False, assume_valid_sdl: bool = False, no_location: bool = False, experimental_fragment_variables: bool = False) graphql.type.schema.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: graphql.type.schema.GraphQLSchema, document_ast: graphql.language.ast.DocumentNode, assume_valid: bool = False, assume_valid_sdl: bool = 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
toTrue
to assume the produced schema is valid. Setassume_valid_sdl
toTrue
to assume it is already a valid SDL document.
Sort a GraphQLSchema:
- graphql.utilities.lexicographic_sort_schema(schema: graphql.type.schema.GraphQLSchema) graphql.type.schema.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: 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
@deprecated: Convenience function for printing a Python value
Create a GraphQLType from a GraphQL language AST:
- graphql.utilities.type_from_ast(schema: graphql.type.schema.GraphQLSchema, type_node: graphql.language.ast.NamedTypeNode) Optional[graphql.type.definition.GraphQLNamedType]
- graphql.utilities.type_from_ast(schema: graphql.type.schema.GraphQLSchema, type_node: graphql.language.ast.ListTypeNode) Optional[graphql.type.definition.GraphQLList]
- graphql.utilities.type_from_ast(schema: graphql.type.schema.GraphQLSchema, type_node: graphql.language.ast.NonNullTypeNode) Optional[graphql.type.definition.GraphQLNonNull]
- graphql.utilities.type_from_ast(schema: graphql.type.schema.GraphQLSchema, type_node: graphql.language.ast.TypeNode) Optional[graphql.type.definition.GraphQLType]
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: 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: 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
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 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: 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)
andleave(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) None
- enter_argument(node: graphql.language.ast.ArgumentNode) None
- enter_directive(node: graphql.language.ast.DirectiveNode) None
- enter_enum_value(node: graphql.language.ast.EnumValueNode) None
- enter_field(node: graphql.language.ast.FieldNode) None
- enter_fragment_definition(node: graphql.language.ast.InlineFragmentNode) None
- enter_inline_fragment(node: graphql.language.ast.InlineFragmentNode) None
- enter_list_value(node: graphql.language.ast.ListValueNode) None
- enter_object_field(node: graphql.language.ast.ObjectFieldNode) None
- enter_operation_definition(node: graphql.language.ast.OperationDefinitionNode) None
- enter_selection_set(node: graphql.language.ast.SelectionSetNode) None
- enter_variable_definition(node: graphql.language.ast.VariableDefinitionNode) None
- get_argument() Optional[graphql.type.definition.GraphQLArgument]
- get_default_value() Any
- get_directive() Optional[graphql.type.directives.GraphQLDirective]
- get_enum_value() Optional[graphql.type.definition.GraphQLEnumValue]
- get_field_def() Optional[graphql.type.definition.GraphQLField]
- get_input_type() Optional[Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLInputObjectType, graphql.type.definition.GraphQLWrappingType]]
- get_parent_input_type() Optional[Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLInputObjectType, graphql.type.definition.GraphQLWrappingType]]
- get_parent_type() Optional[Union[graphql.type.definition.GraphQLObjectType, graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType]]
- get_type() Optional[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]]
- leave(node: graphql.language.ast.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: 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)
- enter(node: graphql.language.ast.Node, *args: Any) Any
- get_visit_fn(kind: str, is_leaving: bool = False) Callable
Get the visit function for the given node kind and direction.
- leave(node: graphql.language.ast.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.GraphQLWrappingType], 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[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) 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: 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: graphql.type.schema.GraphQLSchema, type_a: Union[graphql.type.definition.GraphQLObjectType, graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType], type_b: Union[graphql.type.definition.GraphQLObjectType, graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.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.
- graphql.utilities.is_valid_name_error(name: str) 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)
Bases:
tuple
- __init__()
- count(value, /)
Return number of occurrences of value.
- property description
Alias for field number 1
- index(value, start=0, stop=9223372036854775807, /)
Return first index of value.
Raises ValueError if the value is not present.
- property type
Alias for field number 0
- class graphql.utilities.BreakingChangeType(value)
Bases:
enum.Enum
An enumeration.
- 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:
tuple
- __init__()
- count(value, /)
Return number of occurrences of value.
- property description
Alias for field number 1
- index(value, start=0, stop=9223372036854775807, /)
Return first index of value.
Raises ValueError if the value is not present.
- property type
Alias for field number 0
- class graphql.utilities.DangerousChangeType(value)
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
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.
Deprecated since version 3.1.3.
Please use
validate
withNoDeprecatedCustomRule
instead:from graphql import validate, NoDeprecatedCustomRule errors = validate(schema, document, [NoDeprecatedCustomRule])