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, 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_depthargument 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.- Parameters:
descriptions – Whether to include descriptions in the introspection result.
specified_by_url – Whether to include
specifiedByURLin the introspection result.directive_is_repeatable – Whether to include the
isRepeatableflag on directives.schema_description – Whether to include the
descriptionfield on the schema.input_value_deprecation – Whether the target GraphQL server supports deprecation of input values.
experimental_directive_deprecation – Whether the target GraphQL server supports deprecation of directives.
one_of – Whether the target GraphQL server supports
@oneOfinput objects.type_depth – How deep to recurse into nested types.
- Returns:
The resolved introspection query.
Generate the default introspection query:
>>> from graphql import get_introspection_query >>> query = get_introspection_query() >>> '__schema' in query True >>> 'description' in query True >>> 'specifiedByURL' in query False
This variant customizes optional introspection fields and nesting depth:
>>> query = get_introspection_query( ... descriptions=False, ... specified_by_url=True, ... directive_is_repeatable=True, ... schema_description=True, ... input_value_deprecation=True, ... experimental_directive_deprecation=True, ... one_of=True, ... type_depth=3, ... ) >>> 'description' in query False >>> 'specifiedByURL' in query True >>> 'isRepeatable' in query True >>> 'includeDeprecated: true' in query True >>> 'isOneOf' in query True >>> query.count('ofType') > 0 True
- class graphql.utilities.IntrospectionQuery
Bases:
TypedDictThe result shape returned by a full introspection query.
The
__schemakey holds the introspection representation of the schema.
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.
- Parameters:
document_ast – The parsed GraphQL document AST.
operation_name – The optional name of the operation to select.
- Returns:
The selected operation definition node, or
Noneif no matching operation could be determined.
>>> from graphql import get_operation_ast, parse >>> document = parse('query GetName { name }') >>> operation = get_operation_ast(document, 'GetName') >>> operation.name.value 'GetName' >>> print(get_operation_ast(document, 'Missing')) None
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, 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.
- Parameters:
schema – The GraphQL schema to introspect.
descriptions – Whether to include descriptions in the introspection result.
specified_by_url – Whether to include
specifiedByURLin the introspection result.directive_is_repeatable – Whether to include the
isRepeatableflag on directives.schema_description – Whether to include the
descriptionfield on the schema.input_value_deprecation – Whether to include deprecation information of input values.
experimental_directive_deprecation – Whether to include deprecation information of directives.
one_of – Whether to include the
isOneOfflag on input objects.
- Returns:
Introspection result data for the schema.
Include schema metadata using the default introspection options:
>>> from graphql import build_schema, introspection_from_schema >>> schema = build_schema(''' ... scalar Url @specifiedBy(url: "https://url.spec.whatwg.org/") ... ... type Query { ... homepage: Url ... } ... ''') >>> introspection = introspection_from_schema(schema) >>> url_type = next(type_ for type_ in introspection['__schema']['types'] ... if type_['name'] == 'Url') >>> url_type['specifiedByURL'] 'https://url.spec.whatwg.org/'
This variant disables optional introspection metadata:
>>> introspection = introspection_from_schema( ... schema, ... descriptions=False, ... specified_by_url=False, ... directive_is_repeatable=False, ... schema_description=False, ... input_value_deprecation=False, ... experimental_directive_deprecation=False, ... one_of=False, ... ) >>> url_type = next(type_ for type_ in introspection['__schema']['types'] ... if type_['name'] == 'Url') >>> deprecated_directive = next( ... directive for directive in introspection['__schema']['directives'] ... if directive['name'] == 'deprecated') >>> 'specifiedByURL' in url_type False >>> 'description' in url_type False >>> 'description' in introspection['__schema'] False >>> 'isRepeatable' in deprecated_directive False
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.
- Parameters:
introspection – Introspection result data to build from.
assume_valid – Set to
Trueto assume the produced schema is valid and skip schema validation.
- Returns:
The client schema represented by the introspection result.
>>> from graphql import ( ... build_client_schema, build_schema, introspection_from_schema) >>> schema = build_schema('type Query { hello: String }') >>> client_schema = build_client_schema( ... introspection_from_schema(schema), assume_valid=True) >>> client_schema.query_type.name 'Query'
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 definition language document produced by the
parse()function and constructs a GraphQLSchema from it.If no schema definition is provided, then it will look for types named Query, Mutation and Subscription.
The resulting schema has no resolver functions, so execution will use the default field resolver.
When building a schema from a GraphQL service’s introspection result, it might be safe to assume the schema is valid. Set
assume_validtoTrueto assume the produced schema is valid. Setassume_valid_sdltoTrueto assume it is already a valid SDL document.- Parameters:
document_ast – The parsed GraphQL document AST.
assume_valid – Set to
Trueto assume the produced schema is valid and skip schema validation.assume_valid_sdl – Set to
Trueto assume the SDL document is valid and skip SDL validation.
- Returns:
The schema built from the provided SDL document.
Build a schema from a valid parsed SDL document:
>>> from graphql import build_ast_schema, parse >>> document = parse('type Query { hello: String }') >>> schema = build_ast_schema(document) >>> schema.query_type.name 'Query'
This variant uses validation options when the SDL references unknown directives:
>>> document = parse('type Query { hello: String @unknown }') >>> build_ast_schema(document) Traceback (most recent call last): ... TypeError: Unknown directive '@unknown'. >>> schema = build_ast_schema(document, assume_valid=True, assume_valid_sdl=True)
- graphql.utilities.build_schema(source: str | Source, assume_valid: bool = False, assume_valid_sdl: bool = False, no_location: bool = False, experimental_fragment_arguments: bool = False) GraphQLSchema
Build a GraphQLSchema directly from a source document.
Builds a GraphQLSchema directly from a schema definition language source.
- Parameters:
source – The GraphQL source text or source object.
assume_valid – Set to
Trueto assume the produced schema is valid and skip schema validation.assume_valid_sdl – Set to
Trueto assume the SDL document is valid and skip SDL validation.no_location – Set to
Trueto create AST nodes without location information.experimental_fragment_arguments – Allows fragment variable definitions and arguments on fragment spreads to be parsed (experimental).
- Returns:
The schema built from the provided SDL document.
Build a schema from SDL source using the default options:
>>> from graphql import build_schema >>> schema = build_schema('type Query { hello: String }') >>> schema.query_type.name 'Query'
This variant enables parser options and omits source locations:
>>> schema = build_schema( ... 'directive @tag on DIRECTIVE_DEFINITION\n' ... 'directive @compose @tag on FIELD_DEFINITION', ... experimental_fragment_arguments=True, ... no_location=True, ... ) >>> directive = schema.get_directive('compose') >>> directive.name 'compose' >>> print(directive.ast_node.loc) None
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_validtoTrueto assume the produced schema is valid. Setassume_valid_sdltoTrueto assume it is already a valid SDL document.- Parameters:
schema – The GraphQL schema to extend.
document_ast – The parsed GraphQL document AST.
assume_valid – Set to
Trueto assume the produced schema is valid and skip schema validation.assume_valid_sdl – Set to
Trueto assume the SDL extension is valid and skip SDL validation.
- Returns:
A new schema with the extensions and definitions applied.
Extend a schema with new fields and types:
>>> from graphql import build_schema, extend_schema, parse >>> schema = build_schema(''' ... type Query { ... greeting: String ... } ... ''') >>> extension_ast = parse(''' ... extend type Query { ... farewell: String ... } ... ... type Review { ... body: String ... } ... ''') >>> extended_schema = extend_schema(schema, extension_ast) >>> print(schema.get_type('Review')) None >>> extended_schema.get_type('Review').name 'Review' >>> list(extended_schema.query_type.fields) ['greeting', 'farewell']
This variant bypasses validation for an otherwise invalid extension:
>>> invalid_extension = parse(''' ... extend type Missing { ... field: String ... } ... ''') >>> extend_schema(schema, invalid_extension) Traceback (most recent call last): ... TypeError: Cannot extend type 'Missing' because it is not defined. >>> extended_schema = extend_schema( ... schema, invalid_extension, assume_valid=True, assume_valid_sdl=True)
Sort a GraphQLSchema:
- graphql.utilities.lexicographic_sort_schema(schema: GraphQLSchema) GraphQLSchema
Sort GraphQLSchema.
This function returns a sorted copy of the given GraphQLSchema.
- Parameters:
schema – The GraphQL schema to sort.
- Returns:
A copy of the schema with types, fields, arguments, and values sorted lexicographically.
>>> from graphql import build_schema, lexicographic_sort_schema, print_schema >>> schema = build_schema(''' ... type Query { ... zebra: String ... apple: String ... } ... ... enum Episode { ... JEDI ... NEW_HOPE ... EMPIRE ... } ... ''') >>> sorted_schema = lexicographic_sort_schema(schema) >>> print(print_schema(sorted_schema)) enum Episode { EMPIRE JEDI NEW_HOPE } type Query { apple: String zebra: String }
Print a GraphQLSchema to GraphQL Schema language:
- graphql.utilities.print_schema(schema: GraphQLSchema) str
Print the schema.
- Parameters:
schema – The GraphQL schema to print.
- Returns:
The printed string representation in SDL.
>>> from graphql import build_schema, print_schema >>> schema = build_schema(''' ... directive @upper on FIELD_DEFINITION ... ... type Query { ... greeting: String @upper ... } ... ''') >>> print(print_schema(schema)) directive @upper on FIELD_DEFINITION type Query { greeting: String }
- graphql.utilities.print_type(type_: GraphQLNamedType) str
Print the type.
- Parameters:
type – The GraphQL named type to print.
- Returns:
The printed string representation in SDL.
>>> from graphql import build_schema, print_type >>> schema = build_schema(''' ... type User { ... id: ID! ... name: String ... } ... ... type Query { ... viewer: User ... } ... ''') >>> print(print_type(schema.get_type('User'))) type User { id: ID! name: String }
- graphql.utilities.print_directive(directive: GraphQLDirective) str
Print a GraphQL directive.
Prints a directive definition in GraphQL SDL.
- Parameters:
directive – Directive to print.
- Returns:
SDL string for the directive definition.
>>> from graphql import ( ... DirectiveLocation, ... GraphQLArgument, ... GraphQLDirective, ... GraphQLString, ... ) >>> from graphql.utilities import print_directive >>> auth_directive = GraphQLDirective( ... name='auth', ... description='Requires authorization.', ... locations=[DirectiveLocation.FIELD_DEFINITION], ... args={'scope': GraphQLArgument(GraphQLString)}, ... ) >>> print(print_directive(auth_directive)) """Requires authorization.""" directive @auth(scope: String) on FIELD_DEFINITION
- graphql.utilities.print_introspection_schema(schema: GraphQLSchema) str
Print the introspection schema.
- Parameters:
schema – The GraphQL schema whose introspection types are printed.
- Returns:
The printed string representation in SDL.
>>> from graphql import build_schema, print_introspection_schema >>> schema = build_schema(''' ... type Query { ... greeting: String ... } ... ''') >>> printed = print_introspection_schema(schema) >>> 'type __Schema' in printed True >>> 'enum __TypeKind' in printed True >>> 'type Query' in printed False
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.- Parameters:
schema – The GraphQL schema to use.
type_node – The GraphQL type AST node to resolve.
- Returns:
The GraphQL type referenced by the AST node, or
Noneif it cannot be resolved.
>>> from graphql import build_schema, parse_type, type_from_ast >>> schema = build_schema(''' ... type User { ... name: String ... } ... ... type Query { ... users: [User!]! ... } ... ''') >>> type_from_ast(schema, parse_type('User')) <GraphQLObjectType 'User'> >>> print(type_from_ast(schema, parse_type('[User!]!'))) [User!]! >>> print(type_from_ast(schema, parse_type('[String]'))) [String] >>> print(type_from_ast(schema, parse_type('Missing'))) None >>> print(type_from_ast(schema, parse_type('[Missing]'))) None
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
locationstoTruein order to get the locations as well.- Parameters:
node – The AST node (or collection of AST nodes) to convert.
locations – Whether to include the start and end locations of the nodes.
cache – Mapping of already converted nodes, used internally to share the dictionaries of nodes that appear multiple times in the AST.
- Returns:
A nested dictionary representing the AST.
>>> from graphql import parse_type, parse_value >>> from graphql.utilities import ast_to_dict >>> ast_to_dict(parse_type('[String]')) {'kind': 'list_type', 'type': {'kind': 'named_type', 'name': {'kind': 'name', 'value': 'String'}}} >>> ast_to_dict(parse_value('42'), locations=True) {'kind': 'int_value', 'value': '42', 'loc': {'start': 0, 'end': 2}}
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 | GraphQLList | GraphQLNonNull[GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList], 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
Undefinedwhen 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
- Parameters:
value_node – GraphQL value AST node to convert.
type – The GraphQL input type used to interpret the value.
variables – Optional runtime variable values keyed by variable name.
- Returns:
The coerced Python value, or
Undefinedif the AST value cannot be coerced to the type.
Coerce literal values without variables:
>>> from graphql import ( ... GraphQLInputField, GraphQLInputObjectType, GraphQLInt, GraphQLList, ... GraphQLNonNull, GraphQLString, parse_value, value_from_ast) >>> ReviewInput = GraphQLInputObjectType('ReviewInput', { ... 'stars': GraphQLInputField(GraphQLNonNull(GraphQLInt)), ... 'tags': GraphQLInputField(GraphQLList(GraphQLString)), ... }) >>> value_from_ast(parse_value('{ stars: 5, tags: ["featured"] }'), ReviewInput) {'stars': 5, 'tags': ['featured']} >>> value_from_ast(parse_value('{ stars: "bad" }'), ReviewInput) Undefined
This variant resolves variable references from runtime values:
>>> value_from_ast(parse_value('$stars'), GraphQLInt, {'stars': 5}) 5 >>> value_from_ast(parse_value('$stars'), GraphQLInt, {}) Undefined
Deprecated since version 3.3: Use
coerce_input_literal()instead.value_from_astwill be removed in a future version.
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
- Parameters:
value_node – GraphQL value AST node to convert.
variables – Optional runtime variable values keyed by variable name.
- Returns:
Python value represented by the GraphQL value AST.
>>> from graphql import parse_value, value_from_ast_untyped >>> value_from_ast_untyped(parse_value('[1, 2, 3]')) [1, 2, 3] >>> value_from_ast_untyped(parse_value('$name'), {'name': 'Ada'}) 'Ada'
Create a GraphQL language AST from a Python value:
- graphql.utilities.ast_from_value(value: Any, type_: GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList | GraphQLNonNull[GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList]) IntValueNode | FloatValueNode | StringValueNode | BooleanValueNode | NullValueNode | EnumValueNode | ConstListValueNode | ConstObjectValueNode | 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
- Parameters:
value – Runtime value to convert.
type – The GraphQL input type used to interpret the value.
- Returns:
A GraphQL value AST for the provided Python value, or
Nonewhen no literal can represent it.
>>> from graphql import ( ... GraphQLInputField, GraphQLInputObjectType, GraphQLInt, GraphQLList, ... GraphQLNonNull, GraphQLString, Undefined, ast_from_value, print_ast) >>> ReviewInput = GraphQLInputObjectType('ReviewInput', { ... 'stars': GraphQLInputField(GraphQLNonNull(GraphQLInt)), ... 'tags': GraphQLInputField(GraphQLList(GraphQLString)), ... }) >>> value_node = ast_from_value( ... {'stars': 5, 'tags': ['featured', 'verified']}, ReviewInput) >>> print(print_ast(value_node)) { stars: 5, tags: ["featured", "verified"] } >>> print(ast_from_value(Undefined, GraphQLString)) None >>> print(ast_from_value(None, GraphQLNonNull(GraphQLString))) None
Deprecated since version 3.3: Use
value_to_literal()instead, with care to operate on external values.ast_from_valuewill be removed in a future version.
Create a GraphQL literal (AST) from a Python value:
- graphql.utilities.value_to_literal(value: Any, type_: GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList | GraphQLNonNull[GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList]) IntValueNode | FloatValueNode | StringValueNode | BooleanValueNode | NullValueNode | EnumValueNode | ConstListValueNode | ConstObjectValueNode | None
Produce a GraphQL Value AST given a Python value and a GraphQL type.
Scalar types are converted by calling the
value_to_literalmethod on that type, otherwise the default scalarvalue_to_literalmethod is used, defined below.The provided value is a non-coerced “input” value. This function does not perform any coercion, however it does perform validation. Provided values which are invalid for the given type will result in a
Nonereturn value.- Parameters:
value – Python value to convert.
type – GraphQL input type to convert the value against.
- Returns:
A GraphQL value AST, or
Noneif the value is invalid.
>>> from graphql import ( ... GraphQLInputField, ... GraphQLInputObjectType, ... GraphQLInt, ... GraphQLList, ... GraphQLNonNull, ... GraphQLString, ... print_ast, ... ) >>> from graphql.utilities import value_to_literal >>> review_input = GraphQLInputObjectType( ... 'ReviewInput', ... { ... 'stars': GraphQLInputField(GraphQLNonNull(GraphQLInt)), ... 'tags': GraphQLInputField(GraphQLList(GraphQLString)), ... }, ... ) >>> literal = value_to_literal({'stars': 5, 'tags': ['featured']}, review_input) >>> print_ast(literal) '{ stars: 5, tags: ["featured"] }' >>> value_to_literal({'tags': ['missing stars']}, review_input) is None True
Replace any variables in an AST value with their literal values:
- graphql.utilities.replace_variables(value_node: ValueNode, variable_values: VariableValues | None = None, fragment_variable_values: FragmentVariableValues | None = None) ConstValueNode
Replace any variables in an AST value with literal values.
Replaces any variables found within an AST value literal with literals supplied from a map of variable values, or removes them if no variable replacement exists, returning a constant value.
Used primarily to ensure only complete constant values are used during input coercion of custom scalars which accept complex literals.
- Parameters:
value_node – Value AST node in which variables should be replaced.
variable_values – Operation variable values returned by
get_variable_values().fragment_variable_values – Fragment variable values for the current fragment scope.
- Returns:
A constant value AST with variables replaced.
>>> from graphql import build_schema, parse, parse_value, print_ast >>> from graphql.execution import get_variable_values >>> from graphql.utilities import replace_variables >>> schema = build_schema(''' ... type Query { ... review(stars: Int = 5): String ... } ... ''') >>> document = parse('query ($stars: Int = 5) { review(stars: $stars) }') >>> operation = document.definitions[0] >>> variable_values = get_variable_values( ... schema, operation.variable_definitions, {'stars': 4} ... ) >>> literal = replace_variables( ... parse_value('{ stars: $stars, comment: $missing }'), variable_values ... ) >>> print_ast(literal) '{ stars: 4 }'
Get the AST of the default value of an argument or input field:
- graphql.utilities.get_default_value_ast(arg_or_input_field: GraphQLArgument | GraphQLInputField) ConstValueNode | None
Get the AST of the default value of an argument or input field.
Returns
Noneif no default value is provided.Both external defaults (
default, given as a runtime value or as a literal) and deprecated internal defaults (default_value) are supported.- Parameters:
arg_or_input_field – The argument or input field to inspect.
- Returns:
The default value as a constant value AST node, or
None.
>>> from graphql import ( ... GraphQLArgument, ... GraphQLDefaultInput, ... GraphQLInt, ... GraphQLList, ... build_schema, ... print_ast, ... ) >>> from graphql.utilities import get_default_value_ast >>> schema = build_schema(''' ... type Query { ... greet(name: String = "Ada", times: Int): String ... } ... ''') >>> args = schema.query_type.fields['greet'].args >>> print_ast(get_default_value_ast(args['name'])) '"Ada"' >>> get_default_value_ast(args['times']) is None True >>> argument = GraphQLArgument( ... GraphQLList(GraphQLInt), default=GraphQLDefaultInput([1, 2]) ... ) >>> print_ast(get_default_value_ast(argument)) '[1, 2]'
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, fragment_signatures: Callable[[str], FragmentSignature | None] | None = None)
Bases:
objectUtility 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).- Parameters:
schema – Schema used for type lookups.
initial_type – Optional type to use at the start of traversal. It may be provided in rare cases to facilitate traversals beginning somewhere other than documents.
fragment_signatures – Optional function returning the signatures of the fragments available during traversal by fragment name.
Track field types during a traversal with a
TypeInfoVisitor:>>> from graphql import ( ... TypeInfo, TypeInfoVisitor, Visitor, build_schema, parse, visit) >>> schema = build_schema(''' ... type Query { ... greeting: String ... } ... ''') >>> type_info = TypeInfo(schema) >>> seen_types = [] >>> class FieldVisitor(Visitor): ... def enter_field(self, *_args): ... seen_types.append(str(type_info.get_type())) >>> _ = visit(parse('{ greeting }'), TypeInfoVisitor(type_info, FieldVisitor())) >>> seen_types ['String']
This variant starts from an initial type and supplies fragment signatures:
>>> from graphql import FragmentSpreadNode, NameNode, SelectionSetNode >>> from graphql.utilities.type_info import FragmentSignature >>> schema = build_schema(''' ... type Query { ... greeting(name: String): String ... } ... ''') >>> fragment_document = parse( ... 'fragment GreetingFields($name: String) on Query { greeting(name: $name) }', ... experimental_fragment_arguments=True, ... ) >>> fragment_definition = fragment_document.definitions[0] >>> variable_definition = fragment_definition.variable_definitions[0] >>> type_info = TypeInfo( ... schema, ... schema.query_type, ... lambda name: FragmentSignature( ... fragment_definition, {'name': variable_definition} ... ) ... if name == 'GreetingFields' ... else None, ... ) >>> type_info.enter(SelectionSetNode(selections=())) >>> type_info.enter( ... FragmentSpreadNode( ... name=NameNode(value='GreetingFields'), arguments=(), directives=() ... ) ... ) >>> str(type_info.get_parent_type()) 'Query' >>> type_info.get_fragment_signature().definition.name.value 'GreetingFields'
- enter(node: Node) None
Update this TypeInfo instance for an entered AST node.
- Parameters:
node – AST node being entered.
>>> from graphql import TypeInfo, build_schema, parse >>> schema = build_schema(''' ... type Query { ... greeting: String ... } ... ''') >>> document = parse('{ greeting }') >>> operation = document.definitions[0] >>> selection_set = operation.selection_set >>> field = selection_set.selections[0] >>> type_info = TypeInfo(schema) >>> type_info.enter(operation) >>> type_info.enter(selection_set) >>> type_info.enter(field) >>> field.kind 'field' >>> type_info.get_parent_type().name 'Query' >>> str(type_info.get_type()) 'String'
- get_argument() GraphQLArgument | None
Get the current argument definition.
- Returns:
The current argument definition, if known.
>>> from graphql import ( ... TypeInfo, TypeInfoVisitor, Visitor, build_schema, parse, visit) >>> schema = build_schema(''' ... type Query { ... reviews(limit: Int = 10): [String] ... } ... ''') >>> type_info = TypeInfo(schema) >>> arguments = [] >>> class ArgumentVisitor(Visitor): ... def enter_argument(self, node, *_args): ... arguments.append(type_info.get_argument()) >>> document = parse('{ reviews(limit: 5) }') >>> _ = visit(document, TypeInfoVisitor(type_info, ArgumentVisitor())) >>> arguments == [schema.query_type.fields['reviews'].args['limit']] True
- get_default_value() Any
Get the default value for the current input position.
- Returns:
The current default value, if one is available.
>>> from graphql import ( ... TypeInfo, TypeInfoVisitor, Visitor, build_schema, parse, visit) >>> schema = build_schema(''' ... type Query { ... reviews(limit: Int = 10): [String] ... } ... ''') >>> type_info = TypeInfo(schema) >>> default_values = [] >>> class ArgumentVisitor(Visitor): ... def enter_argument(self, node, *_args): ... default_values.append(type_info.get_default_value()) >>> document = parse('{ reviews(limit: 5) }') >>> _ = visit(document, TypeInfoVisitor(type_info, ArgumentVisitor())) >>> from graphql import print_ast >>> [print_ast(default.literal) for default in default_values] ['10']
- get_directive() GraphQLDirective | None
Get the current directive definition.
- Returns:
The current directive definition, if known.
>>> from graphql import ( ... TypeInfo, TypeInfoVisitor, Visitor, build_schema, parse, visit) >>> schema = build_schema(''' ... type Query { ... greeting: String ... } ... ''') >>> type_info = TypeInfo(schema) >>> directive_names = [] >>> class DirectiveVisitor(Visitor): ... def enter_directive(self, node, *_args): ... directive_names.append(type_info.get_directive().name) >>> document = parse('{ greeting @include(if: true) }') >>> _ = visit(document, TypeInfoVisitor(type_info, DirectiveVisitor())) >>> directive_names ['include']
- get_enum_value() GraphQLEnumValue | None
Get the current enum value definition.
- Returns:
The current enum value definition, if known.
>>> from graphql import ( ... TypeInfo, TypeInfoVisitor, Visitor, build_schema, parse, visit) >>> schema = build_schema(''' ... enum Sort { ... NEWEST ... OLDEST ... } ... ... type Query { ... reviews(sort: Sort = NEWEST): [String] ... } ... ''') >>> type_info = TypeInfo(schema) >>> enum_values = [] >>> class EnumValueVisitor(Visitor): ... def enter_enum_value(self, node, *_args): ... enum_values.append(type_info.get_enum_value().value) >>> document = parse('{ reviews(sort: OLDEST) }') >>> _ = visit(document, TypeInfoVisitor(type_info, EnumValueVisitor())) >>> enum_values ['OLDEST']
- get_field_def() GraphQLField | None
Get the current field definition.
- Returns:
The current field definition, if known.
>>> from graphql import ( ... TypeInfo, TypeInfoVisitor, Visitor, build_schema, parse, visit) >>> schema = build_schema(''' ... type Query { ... greeting: String ... } ... ''') >>> type_info = TypeInfo(schema) >>> field_defs = [] >>> class FieldVisitor(Visitor): ... def enter_field(self, node, *_args): ... field_defs.append(type_info.get_field_def()) >>> document = parse('{ greeting }') >>> _ = visit(document, TypeInfoVisitor(type_info, FieldVisitor())) >>> field_defs == [schema.query_type.fields['greeting']] True
- get_fragment_argument() VariableDefinitionNode | None
Get the current fragment argument definition.
- Returns:
The variable definition for the current fragment argument.
>>> from graphql import ( ... TypeInfo, TypeInfoVisitor, Visitor, build_schema, parse, visit) >>> schema = build_schema(''' ... type Query { ... greeting(name: String): String ... } ... ''') >>> document = parse(''' ... { ... ...GreetingFields(name: "Ada") ... } ... ... fragment GreetingFields($name: String) on Query { ... greeting(name: $name) ... } ... ''', experimental_fragment_arguments=True) >>> type_info = TypeInfo(schema) >>> argument_names = [] >>> class FragmentArgumentVisitor(Visitor): ... def enter_fragment_argument(self, *_args): ... argument = type_info.get_fragment_argument() ... argument_names.append(argument.variable.name.value) >>> _ = visit( ... document, TypeInfoVisitor(type_info, FragmentArgumentVisitor()) ... ) >>> argument_names ['name']
- get_fragment_signature() FragmentSignature | None
Get the current fragment signature.
- Returns:
The fragment signature for the current fragment spread.
>>> from graphql import ( ... TypeInfo, TypeInfoVisitor, Visitor, build_schema, parse, visit) >>> schema = build_schema(''' ... type Query { ... greeting: String ... } ... ''') >>> document = parse(''' ... { ... ...GreetingFields ... } ... ... fragment GreetingFields on Query { ... greeting ... } ... ''', experimental_fragment_arguments=True) >>> type_info = TypeInfo(schema) >>> fragment_names = [] >>> class FragmentSpreadVisitor(Visitor): ... def enter_fragment_spread(self, *_args): ... signature = type_info.get_fragment_signature() ... fragment_names.append(signature.definition.name.value) >>> _ = visit(document, TypeInfoVisitor(type_info, FragmentSpreadVisitor())) >>> fragment_names ['GreetingFields']
- get_fragment_signature_by_name() Callable[[str], FragmentSignature | None]
Get the function used to look up fragment signatures by name.
- Returns:
A function that maps fragment names to fragment signatures.
>>> from graphql import ( ... TypeInfo, TypeInfoVisitor, Visitor, build_schema, parse, visit) >>> schema = build_schema(''' ... type Query { ... greeting: String ... } ... ''') >>> document = parse(''' ... { ... ...GreetingFields ... } ... ... fragment GreetingFields on Query { ... greeting ... } ... ''', experimental_fragment_arguments=True) >>> type_info = TypeInfo(schema) >>> fragment_names = [] >>> class DocumentVisitor(Visitor): ... def enter_document(self, *_args): ... get_fragment_signature = type_info.get_fragment_signature_by_name() ... signature = get_fragment_signature('GreetingFields') ... fragment_names.append(signature.definition.name.value) >>> _ = visit(document, TypeInfoVisitor(type_info, DocumentVisitor())) >>> fragment_names ['GreetingFields']
- get_input_type() GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList | GraphQLNonNull[GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList] | None
Get the current input type at this point in traversal.
- Returns:
The current input type, if known.
>>> from graphql import ( ... TypeInfo, TypeInfoVisitor, Visitor, build_schema, parse, visit) >>> schema = build_schema(''' ... type Query { ... reviews(stars: Int!, sort: Sort = NEWEST): [String] ... } ... ... enum Sort { ... NEWEST ... OLDEST ... } ... ''') >>> type_info = TypeInfo(schema) >>> input_types = {} >>> class ArgumentVisitor(Visitor): ... def enter_argument(self, node, *_args): ... input_types[node.name.value] = str(type_info.get_input_type()) >>> document = parse('{ reviews(stars: 5, sort: OLDEST) }') >>> _ = visit(document, TypeInfoVisitor(type_info, ArgumentVisitor())) >>> input_types {'stars': 'Int!', 'sort': 'Sort'}
- get_parent_input_type() GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList | GraphQLNonNull[GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList] | None
Get the parent input type for the current input position.
- Returns:
The parent input type, if known.
>>> from graphql import ( ... TypeInfo, TypeInfoVisitor, Visitor, build_schema, parse, visit) >>> schema = build_schema(''' ... input ReviewFilter { ... stars: Int! ... } ... ... type Query { ... reviews(filter: ReviewFilter): [String] ... } ... ''') >>> type_info = TypeInfo(schema) >>> parent_input_types = {} >>> class ObjectFieldVisitor(Visitor): ... def enter_object_field(self, node, *_args): ... parent_input_types[node.name.value] = str( ... type_info.get_parent_input_type()) >>> document = parse('{ reviews(filter: { stars: 5 }) }') >>> _ = visit(document, TypeInfoVisitor(type_info, ObjectFieldVisitor())) >>> parent_input_types {'stars': 'ReviewFilter'}
- get_parent_type() GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | None
Get the current parent composite type.
- Returns:
The current parent composite type, if known.
>>> from graphql import ( ... TypeInfo, TypeInfoVisitor, Visitor, build_schema, parse, visit) >>> schema = build_schema(''' ... type Query { ... viewer: User ... } ... ... type User { ... name: String ... } ... ''') >>> type_info = TypeInfo(schema) >>> parent_types = {} >>> class FieldVisitor(Visitor): ... def enter_field(self, node, *_args): ... parent_types[node.name.value] = str(type_info.get_parent_type()) >>> document = parse('{ viewer { name } }') >>> _ = visit(document, TypeInfoVisitor(type_info, FieldVisitor())) >>> parent_types {'viewer': 'Query', 'name': 'User'}
- get_type() GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLList | GraphQLNonNull[GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLList] | None
Get the current output type at this point in traversal.
- Returns:
The current output type, if known.
>>> from graphql import ( ... TypeInfo, TypeInfoVisitor, Visitor, build_schema, parse, visit) >>> schema = build_schema(''' ... type Query { ... viewer: User ... } ... ... type User { ... name: String ... } ... ''') >>> type_info = TypeInfo(schema) >>> field_types = {} >>> class FieldVisitor(Visitor): ... def enter_field(self, node, *_args): ... field_types[node.name.value] = str(type_info.get_type()) >>> document = parse('{ viewer { name } }') >>> _ = visit(document, TypeInfoVisitor(type_info, FieldVisitor())) >>> field_types {'viewer': 'User', 'name': 'String'}
- leave(node: Node) None
Update this TypeInfo instance for a left AST node.
- Parameters:
node – AST node being left.
>>> from graphql import TypeInfo, build_schema, parse >>> schema = build_schema(''' ... type Query { ... greeting: String ... } ... ''') >>> document = parse('{ greeting }') >>> operation = document.definitions[0] >>> selection_set = operation.selection_set >>> field = selection_set.selections[0] >>> type_info = TypeInfo(schema) >>> type_info.enter(operation) >>> type_info.enter(selection_set) >>> type_info.enter(field) >>> str(type_info.get_type()) 'String' >>> type_info.leave(field) >>> str(type_info.get_type()) 'Query'
- class graphql.utilities.TypeInfoVisitor(type_info: TypeInfo, visitor: Visitor)
Bases:
VisitorA visitor which maintains a provided TypeInfo.
Creates a new visitor instance which maintains a provided TypeInfo instance along with visiting the wrapped visitor.
- Parameters:
type_info – TypeInfo instance to update during traversal.
visitor – Visitor to wrap with TypeInfo updates.
>>> from graphql import ( ... TypeInfo, TypeInfoVisitor, Visitor, build_schema, parse, visit) >>> schema = build_schema(''' ... type Query { ... greeting: String ... } ... ''') >>> type_info = TypeInfo(schema) >>> fields = [] >>> class FieldVisitor(Visitor): ... def enter_field(self, node, *_args): ... fields.append({ ... 'name': node.name.value, ... 'parent_type': str(type_info.get_parent_type()), ... 'type': str(type_info.get_type()), ... }) >>> _ = visit(parse('{ greeting }'), TypeInfoVisitor(type_info, FieldVisitor())) >>> fields [{'name': 'greeting', 'parent_type': 'Query', 'type': 'String'}]
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- enter_leave_map: dict[str, EnterLeaveVisitor]
Cache of the enter and leave methods of this visitor per node kind.
- get_enter_leave_for_kind(kind: str) EnterLeaveVisitor
Given a node kind, return the EnterLeaveVisitor for that kind.
- Parameters:
kind – The AST node kind to resolve methods for.
- Returns:
The enter and leave methods that apply for the given node kind.
>>> from graphql import Visitor >>> class FieldVisitor(Visitor): ... def enter_field(self, node, *_args): ... pass >>> enter, leave = FieldVisitor().get_enter_leave_for_kind('field') >>> callable(enter) True >>> leave is None True
Coerce a Python value to a GraphQL type, or return Undefined:
- graphql.utilities.coerce_input_value(input_value: Any, type_: GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList | GraphQLNonNull[GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList]) Any
Coerce a Python value given a GraphQL Input Type.
Returns
Undefinedwhen the value could not be validly coerced according to the provided type. Usevalidate_input_value()when coercion diagnostics are needed.- Parameters:
input_value – Python value to coerce.
type – GraphQL input type to coerce the value against.
- Returns:
Coerced value, or
Undefinedif coercion fails.
Coerce runtime input values, returning
Undefinedwhen coercion fails:>>> from graphql import ( ... GraphQLInputField, ... GraphQLInputObjectType, ... GraphQLInt, ... GraphQLList, ... GraphQLNonNull, ... GraphQLString, ... ) >>> from graphql.utilities import coerce_input_value >>> review_input = GraphQLInputObjectType( ... 'ReviewInput', ... { ... 'stars': GraphQLInputField(GraphQLNonNull(GraphQLInt)), ... 'tags': GraphQLInputField(GraphQLList(GraphQLString)), ... }, ... ) >>> coerce_input_value({'stars': 5, 'tags': ['featured']}, review_input) {'stars': 5, 'tags': ['featured']} >>> coerce_input_value({'stars': 'bad'}, review_input) Undefined
Coerce a GraphQL literal (AST) to a GraphQL type, or return Undefined:
- graphql.utilities.coerce_input_literal(value_node: ValueNode, type_: GraphQLInputType, variable_values: VariableValues | None = None, fragment_variable_values: FragmentVariableValues | None = None) Any
Produce a coerced Python value given a GraphQL Value AST.
Returns
Undefinedwhen the value could not be validly coerced according to the provided type.Unlike
value_from_ast(), this properly supports fragment variables in addition to operation variables.- Parameters:
value_node – GraphQL value AST node to coerce.
type – GraphQL input type to coerce the literal against.
variable_values – Operation variable values returned by
get_variable_values().fragment_variable_values – Fragment variable values for the current fragment scope.
- Returns:
Coerced value, or
Undefinedif coercion fails.
Coerce literal input values without variables:
>>> from graphql import ( ... GraphQLInputField, ... GraphQLInputObjectType, ... GraphQLInt, ... GraphQLNonNull, ... GraphQLString, ... parse_value, ... ) >>> from graphql.utilities import coerce_input_literal >>> review_input = GraphQLInputObjectType( ... 'ReviewInput', ... { ... 'stars': GraphQLInputField(GraphQLNonNull(GraphQLInt)), ... 'comment': GraphQLInputField(GraphQLString), ... }, ... ) >>> coerce_input_literal( ... parse_value('{ stars: 5, comment: "Loved it" }'), review_input ... ) {'stars': 5, 'comment': 'Loved it'} >>> coerce_input_literal(parse_value('{ comment: "Missing" }'), review_input) Undefined
This variant resolves variable references using the variable values returned by
get_variable_values():>>> from graphql import build_schema, parse >>> from graphql.execution import get_variable_values >>> schema = build_schema(''' ... type Query { ... review(stars: Int): String ... } ... ''') >>> document = parse('query ($stars: Int = 5) { review(stars: $stars) }') >>> operation = document.definitions[0] >>> variable_values = get_variable_values( ... schema, operation.variable_definitions, {'stars': 4} ... ) >>> coerce_input_literal(parse_value('$stars'), GraphQLInt, variable_values) 4
Validate a Python value with a GraphQL type, collecting all errors:
- graphql.utilities.validate_input_value(input_value: Any, type_: GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList | GraphQLNonNull[GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList], on_error: Callable[[GraphQLError, list[str | int]], None], hide_suggestions: bool = False) None
Validate that the provided input value is allowed for this type.
All errors are collected via a callback function.
- Parameters:
input_value – Python value to validate.
type – GraphQL input type to validate the value against.
on_error – Callback invoked for each validation error and path.
hide_suggestions – Whether suggestion text should be omitted from errors.
Collect validation errors with their input paths:
>>> from graphql import ( ... GraphQLInputField, ... GraphQLInputObjectType, ... GraphQLInt, ... GraphQLNonNull, ... ) >>> from graphql.utilities import validate_input_value >>> review_input = GraphQLInputObjectType( ... 'ReviewInput', ... {'stars': GraphQLInputField(GraphQLNonNull(GraphQLInt))}, ... ) >>> errors = [] >>> validate_input_value( ... {'stars': 'bad'}, ... review_input, ... lambda error, path: errors.append( ... {'message': error.message, 'path': path} ... ), ... ) >>> errors [{'message': "Int cannot represent non-integer value: 'bad'", 'path': ['stars']}]
This variant hides suggestion text for unknown input fields:
>>> from graphql import GraphQLString >>> review_input = GraphQLInputObjectType( ... 'ReviewInput', {'comment': GraphQLInputField(GraphQLString)} ... ) >>> errors = [] >>> validate_input_value( ... {'rating': 'extra field'}, ... review_input, ... lambda error, _path: errors.append(error.message), ... True, ... ) >>> errors ["Expected value of type 'ReviewInput' not to include unknown field 'rating', found: {'rating': 'extra field'}."]
Validate a GraphQL literal (AST) with a GraphQL type, collecting all errors:
- graphql.utilities.validate_input_literal(value_node: ValueNode, type_: GraphQLInputType, on_error: OnErrorCB, variables: VariableValues | None = None, fragment_variable_values: FragmentVariableValues | None = None, hide_suggestions: bool = False) None
Validate that the provided input literal is allowed for this type.
All errors are collected via a callback function.
If variable values are not provided, the literal is validated statically (not assuming that those variables are missing runtime values).
- Parameters:
value_node – GraphQL value AST node to validate.
type – GraphQL input type to validate the literal against.
on_error – Callback invoked for each validation error and path.
variables – Operation variable values returned by
get_variable_values().fragment_variable_values – Fragment variable values for the current fragment scope.
hide_suggestions – Whether suggestion text should be omitted from errors.
Validate literal input values and collect literal paths:
>>> from graphql import ( ... GraphQLInputField, ... GraphQLInputObjectType, ... GraphQLInt, ... GraphQLNonNull, ... parse_value, ... ) >>> from graphql.utilities import validate_input_literal >>> review_input = GraphQLInputObjectType( ... 'ReviewInput', ... {'stars': GraphQLInputField(GraphQLNonNull(GraphQLInt))}, ... ) >>> errors = [] >>> validate_input_literal( ... parse_value('{ stars: "bad" }'), ... review_input, ... lambda error, path: errors.append( ... {'message': error.message, 'path': path} ... ), ... ) >>> errors [{'message': 'Int cannot represent non-integer value: "bad"', 'path': ['stars']}]
This variant resolves variable references using the variable values returned by
get_variable_values():>>> from graphql import build_schema, parse >>> from graphql.execution import get_variable_values >>> schema = build_schema(''' ... type Query { ... review(stars: Int): String ... } ... ''') >>> document = parse('query ($stars: Int = 5) { review(stars: $stars) }') >>> operation = document.definitions[0] >>> variable_values = get_variable_values( ... schema, operation.variable_definitions, {'stars': 4} ... ) >>> errors = [] >>> validate_input_literal( ... parse_value('$stars'), ... GraphQLInt, ... lambda error, _path: errors.append(error.message), ... variable_values, ... None, ... True, ... ) >>> errors []
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.
- Parameters:
asts – Document ASTs to concatenate.
- Returns:
A document AST containing all definitions from the provided documents.
>>> from graphql import concat_ast, parse >>> document = concat_ast( ... [parse('type Query { a: String }'), parse('type User { id: ID }')]) >>> len(document.definitions) 2
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 as the fragment definitions it refers to.
- Parameters:
document_ast – The parsed GraphQL document AST.
- Returns:
A dictionary mapping operation names to documents containing each operation and its referenced fragments.
>>> from graphql import parse, print_ast, separate_operations >>> document = parse(''' ... query GetUser { ... viewer { ... ...UserFields ... } ... } ... ... query GetStatus { ... status ... } ... ... fragment UserFields on User { ... id ... } ... ''') >>> separated = separate_operations(document) >>> list(separated) ['GetUser', 'GetStatus'] >>> 'fragment UserFields' in print_ast(separated['GetUser']) True >>> 'fragment UserFields' in print_ast(separated['GetStatus']) False
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 tokens 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}
- Parameters:
source – The GraphQL source text or source object.
- Returns:
A semantically equivalent GraphQL source string without ignored characters.
>>> from graphql import strip_ignored_characters >>> strip_ignored_characters('query Example { name }') 'query Example{name}'
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).
- Parameters:
type_a – The first GraphQL type to compare.
type_b – The second GraphQL type to compare.
- Returns:
Truewhen both types are equal.
>>> from graphql import GraphQLList, GraphQLNonNull, GraphQLString, is_equal_type >>> is_equal_type(GraphQLString, GraphQLString) True >>> is_equal_type(GraphQLList(GraphQLString), GraphQLList(GraphQLString)) True >>> is_equal_type(GraphQLNonNull(GraphQLString), GraphQLString) False
- 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).
- Parameters:
schema – The GraphQL schema to use.
maybe_subtype – The possible subtype to compare.
super_type – The possible supertype to compare.
- Returns:
Truewhenmaybe_subtypeis equal to or a subtype ofsuper_type.
>>> from graphql import ( ... GraphQLNonNull, assert_interface_type, assert_object_type, build_schema, ... is_type_sub_type_of) >>> schema = build_schema(''' ... interface Node { ... id: ID! ... } ... ... type User implements Node { ... id: ID! ... } ... ... type Query { ... node: Node ... } ... ''') >>> Node = assert_interface_type(schema.get_type('Node')) >>> User = assert_object_type(schema.get_type('User')) >>> is_type_sub_type_of(schema, User, Node) True >>> is_type_sub_type_of(schema, GraphQLNonNull(User), Node) True >>> is_type_sub_type_of(schema, Node, User) False
- 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.
- Parameters:
schema – The GraphQL schema to use.
type_a – The first composite type to compare.
type_b – The second composite type to compare.
- Returns:
Truewhen the two composite types can apply to at least one common object type.
>>> from graphql import ( ... assert_object_type, assert_union_type, build_schema, do_types_overlap) >>> schema = build_schema(''' ... type Photo { ... url: String! ... } ... ... type Video { ... url: String! ... } ... ... union Media = Photo | Video ... union StillImage = Photo ... ... type Query { ... media: [Media] ... } ... ''') >>> Media = assert_union_type(schema.get_type('Media')) >>> StillImage = assert_union_type(schema.get_type('StillImage')) >>> Video = assert_object_type(schema.get_type('Video')) >>> do_types_overlap(schema, Media, StillImage) True >>> do_types_overlap(schema, StillImage, Video) False
Compare two GraphQLSchemas and detect changes:
- graphql.utilities.find_schema_changes(old_schema: GraphQLSchema, new_schema: GraphQLSchema) list[SafeChange | DangerousChange | BreakingChange]
Find schema changes.
Finds all schema changes between two schemas.
- Parameters:
old_schema – Schema before the change.
new_schema – Schema after the change.
- Returns:
Safe, dangerous, and breaking changes between the two schemas.
>>> from graphql import build_schema >>> from graphql.utilities import find_schema_changes >>> old_schema = build_schema(''' ... type Query { ... greeting: String ... } ... ''') >>> new_schema = build_schema(''' ... type Query { ... greeting(name: String): String ... farewell: String ... } ... ''') >>> changes = find_schema_changes(old_schema, new_schema) >>> [change.type.name for change in changes] ['FIELD_ADDED', 'OPTIONAL_ARG_ADDED']
- 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.
- Parameters:
old_schema – Schema before the change.
new_schema – Schema after the change.
- Returns:
Breaking changes between the two schemas.
>>> from graphql import build_schema >>> from graphql.utilities import find_breaking_changes >>> old_schema = build_schema(''' ... type Query { ... greeting: String ... } ... ''') >>> new_schema = build_schema(''' ... type Query { ... hello: String ... } ... ''') >>> changes = find_breaking_changes(old_schema, new_schema) >>> [change.type.name for change in changes] ['FIELD_REMOVED']
Deprecated since version 3.3: Please use
find_schema_changesinstead and filter for breaking changes. Will be removed in a future version.
- 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.
- Parameters:
old_schema – Schema before the change.
new_schema – Schema after the change.
- Returns:
Dangerous changes between the two schemas.
>>> from graphql import build_schema >>> from graphql.utilities import find_dangerous_changes >>> old_schema = build_schema(''' ... enum Episode { ... NEW_HOPE ... } ... ... type Query { ... episode: Episode ... } ... ''') >>> new_schema = build_schema(''' ... enum Episode { ... NEW_HOPE ... EMPIRE ... } ... ... type Query { ... episode: Episode ... } ... ''') >>> changes = find_dangerous_changes(old_schema, new_schema) >>> [change.type.name for change in changes] ['VALUE_ADDED_TO_ENUM']
Deprecated since version 3.3: Please use
find_schema_changesinstead and filter for dangerous changes. Will be removed in a future version.
- class graphql.utilities.SafeChange(type: SafeChangeType, description: str)
Bases:
NamedTupleType and description of a safe change
Description of a schema change that is considered safe for existing operations.
- count(value, /)
Return number of occurrences of value.
- description: str
Human-readable description of the safe schema change.
- index(value, start=0, stop=9223372036854775807, /)
Return first index of value.
Raises ValueError if the value is not present.
- type: SafeChangeType
Specific kind of safe schema change.
- class graphql.utilities.SafeChangeType(*values)
Bases:
EnumTypes of safe changes
Categories of schema changes that are considered safe for existing operations.
- ARG_CHANGED_KIND_SAFE = 79
- ARG_DEFAULT_VALUE_ADDED = 80
- DESCRIPTION_CHANGED = 81
- DIRECTIVE_ADDED = 73
- DIRECTIVE_LOCATION_ADDED = 76
- DIRECTIVE_REPEATABLE_ADDED = 75
- FIELD_ADDED = 74
- FIELD_CHANGED_KIND_SAFE = 78
- INPUT_FIELD_DEFAULT_VALUE_ADDED = 82
- OPTIONAL_ARG_ADDED = 72
- OPTIONAL_DIRECTIVE_ARG_ADDED = 77
- OPTIONAL_INPUT_FIELD_ADDED = 71
- TYPE_ADDED = 70
- class graphql.utilities.BreakingChange(type: BreakingChangeType, description: str)
Bases:
NamedTupleType and description of a breaking change
Description of a schema change that may break existing operations.
- count(value, /)
Return number of occurrences of value.
- description: str
Human-readable description of the breaking schema change.
- index(value, start=0, stop=9223372036854775807, /)
Return first index of value.
Raises ValueError if the value is not present.
- type: BreakingChangeType
Specific kind of breaking schema change.
- class graphql.utilities.BreakingChangeType(*values)
Bases:
EnumTypes of breaking changes
Categories of schema changes that may break existing operations.
- 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:
NamedTupleType and description of a dangerous change
Description of a schema change that may be dangerous for existing operations.
- count(value, /)
Return number of occurrences of value.
- description: str
Human-readable description of the dangerous schema change.
- index(value, start=0, stop=9223372036854775807, /)
Return first index of value.
Raises ValueError if the value is not present.
- type: DangerousChangeType
Specific kind of dangerous schema change.
- class graphql.utilities.DangerousChangeType(*values)
Bases:
EnumTypes of dangerous changes
Categories of schema changes that may be dangerous for existing operations.
- ARG_DEFAULT_VALUE_CHANGE = 65
- IMPLEMENTED_INTERFACE_ADDED = 64
- INPUT_FIELD_DEFAULT_VALUE_CHANGE = 66
- OPTIONAL_ARG_ADDED = 63
- OPTIONAL_INPUT_FIELD_ADDED = 62
- TYPE_ADDED_TO_UNION = 61
- VALUE_ADDED_TO_ENUM = 60
- graphql.utilities.SchemaChange
alias of
SafeChange|DangerousChange|BreakingChange
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
- Parameters:
schema – The GraphQL schema to use.
schema_coordinate – The schema coordinate to resolve.
- Returns:
The schema element identified by the coordinate, or
Noneif none exists.
>>> from graphql import build_schema, resolve_schema_coordinate >>> schema = build_schema(''' ... directive @tag(name: String!) on FIELD_DEFINITION ... ... input ReviewInput { ... stars: Int! ... } ... ... enum Episode { ... NEW_HOPE ... } ... ... type Query { ... reviews(input: ReviewInput): [String] @tag(name: "reviews") ... } ... ''') >>> resolve_schema_coordinate(schema, 'Query').kind 'NamedType' >>> resolve_schema_coordinate(schema, 'Query.reviews').kind 'Field' >>> resolve_schema_coordinate(schema, 'Query.reviews(input:)').kind 'FieldArgument' >>> resolve_schema_coordinate(schema, 'ReviewInput.stars').kind 'InputField' >>> resolve_schema_coordinate(schema, 'Episode.NEW_HOPE').kind 'EnumValue' >>> resolve_schema_coordinate(schema, '@tag').kind 'Directive' >>> resolve_schema_coordinate(schema, '@tag(name:)').kind 'DirectiveArgument' >>> print(resolve_schema_coordinate(schema, 'Query.missing')) None
- 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.
- Parameters:
schema – The GraphQL schema to use.
schema_coordinate – The parsed schema coordinate to resolve.
- Returns:
The schema element identified by the parsed coordinate, or
Noneif none exists.
>>> from graphql import ( ... build_schema, parse_schema_coordinate, resolve_ast_schema_coordinate) >>> schema = build_schema(''' ... type Query { ... greeting(name: String): String ... } ... ''') >>> coordinate = parse_schema_coordinate('Query.greeting(name:)') >>> resolved = resolve_ast_schema_coordinate(schema, coordinate) >>> resolved.kind 'FieldArgument' >>> resolved.type.name 'Query' >>> resolved.field_argument.type <GraphQLScalarType 'String'>
- class graphql.utilities.ResolvedNamedType(type: GraphQLNamedType, kind: str = 'NamedType')
Bases:
NamedTupleA named type resolved from a schema coordinate.
- 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
The kind of the resolved schema element.
- type: GraphQLNamedType
The resolved named type.
- class graphql.utilities.ResolvedField(type: GraphQLObjectType | GraphQLInterfaceType, field: GraphQLField, kind: str = 'Field')
Bases:
NamedTupleA field resolved from a schema coordinate.
- count(value, /)
Return number of occurrences of value.
- field: GraphQLField
The resolved field.
- index(value, start=0, stop=9223372036854775807, /)
Return first index of value.
Raises ValueError if the value is not present.
- kind: str
The kind of the resolved schema element.
- type: GraphQLObjectType | GraphQLInterfaceType
The object or interface type that declares the field.
- class graphql.utilities.ResolvedInputField(type: GraphQLInputObjectType, input_field: GraphQLInputField, kind: str = 'InputField')
Bases:
NamedTupleAn input field resolved from a schema coordinate.
- 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
The resolved input field.
- kind: str
The kind of the resolved schema element.
- type: GraphQLInputObjectType
The input object type that declares the input field.
- class graphql.utilities.ResolvedEnumValue(type: GraphQLEnumType, enum_value: GraphQLEnumValue, kind: str = 'EnumValue')
Bases:
NamedTupleAn enum value resolved from a schema coordinate.
- count(value, /)
Return number of occurrences of value.
- enum_value: GraphQLEnumValue
The resolved enum value.
- index(value, start=0, stop=9223372036854775807, /)
Return first index of value.
Raises ValueError if the value is not present.
- kind: str
The kind of the resolved schema element.
- type: GraphQLEnumType
The enum type that declares the enum value.
- class graphql.utilities.ResolvedFieldArgument(type: GraphQLObjectType | GraphQLInterfaceType, field: GraphQLField, field_argument: GraphQLArgument, kind: str = 'FieldArgument')
Bases:
NamedTupleA field argument resolved from a schema coordinate.
- count(value, /)
Return number of occurrences of value.
- field: GraphQLField
The field that declares the argument.
- field_argument: GraphQLArgument
The resolved field argument.
- index(value, start=0, stop=9223372036854775807, /)
Return first index of value.
Raises ValueError if the value is not present.
- kind: str
The kind of the resolved schema element.
- type: GraphQLObjectType | GraphQLInterfaceType
The object or interface type that declares the field.
- class graphql.utilities.ResolvedDirective(directive: GraphQLDirective, kind: str = 'Directive')
Bases:
NamedTupleA directive resolved from a schema coordinate.
- count(value, /)
Return number of occurrences of value.
- directive: GraphQLDirective
The resolved directive.
- index(value, start=0, stop=9223372036854775807, /)
Return first index of value.
Raises ValueError if the value is not present.
- kind: str
The kind of the resolved schema element.
- class graphql.utilities.ResolvedDirectiveArgument(directive: GraphQLDirective, directive_argument: GraphQLArgument, kind: str = 'DirectiveArgument')
Bases:
NamedTupleA directive argument resolved from a schema coordinate.
- count(value, /)
Return number of occurrences of value.
- directive: GraphQLDirective
The directive that declares the argument.
- directive_argument: GraphQLArgument
The resolved directive argument.
- index(value, start=0, stop=9223372036854775807, /)
Return first index of value.
Raises ValueError if the value is not present.
- kind: str
The kind of the resolved schema element.
- graphql.utilities.ResolvedSchemaElement
alias of
ResolvedNamedType|ResolvedField|ResolvedInputField|ResolvedEnumValue|ResolvedFieldArgument|ResolvedDirective|ResolvedDirectiveArgument