Validation
GraphQL Validation
The graphql.validation package fulfills the Validation phase of fulfilling a
GraphQL result.
- graphql.validation.validate(schema: GraphQLSchema, document_ast: DocumentNode, rules: Collection[type[ASTValidationRule]] | None = None, max_errors: int | None = None, hide_suggestions: bool = False, allow_empty_selection_sets: bool = True) list[GraphQLError]
Implements the “Validation” section of the spec.
Validation runs synchronously, returning a list of encountered errors, or an empty list if no errors were encountered and the document is valid.
A list of specific validation rules may be provided. If not provided, the default list of rules defined by the GraphQL specification will be used.
Each validation rule is a ValidationRule object which is a visitor object that holds a ValidationContext (see the language/visitor API). Visitor methods are expected to return GraphQLErrors, or lists of GraphQLErrors when invalid.
Validate will stop validation after a
max_errorslimit has been reached. Attackers can send pathologically invalid queries to induce a DoS attack, somax_errorsdefaults to 100 errors.Validation is also aborted if the document nests fragments too deeply for the recursion limit of the interpreter. The errors found until then are kept, and an additional error reports the abort.
- Parameters:
schema – Schema to validate against.
document_ast – Document AST to validate.
rules – Validation rules to apply. Defaults to
specified_rules.max_errors – Maximum number of validation errors before validation stops. Defaults to 100.
hide_suggestions – Whether suggestion text should be omitted from validation errors.
allow_empty_selection_sets – If enabled (the default), a selection set on an object, interface or union type is only required to be present, rather than to be non-empty. Pair this with the
allow_empty_selection_setsparse option. See https://github.com/graphql/graphql-spec/pull/1227. Deprecated, since empty selection sets are now always allowed.
- Returns:
Validation errors, or an empty list when the document is valid.
Validate with the default specified rules:
>>> from graphql import build_schema, parse, validate >>> schema = build_schema('type Query { greeting: String }') >>> validate(schema, parse('{ greeting }')) [] >>> errors = validate(schema, parse('{ missing }')) >>> print(errors[0].message) Cannot query field 'missing' on type 'Query'.
This variant uses a custom rule list and validation options:
>>> from graphql.validation import FieldsOnCorrectTypeRule >>> document = parse('{ missingOne missingTwo }') >>> errors = validate(schema, document, [FieldsOnCorrectTypeRule], max_errors=1) >>> len(errors) 2 >>> print(errors[1].message) Too many validation errors, error limit reached. Validation aborted. >>> errors = validate( ... schema, parse('{ name }'), [FieldsOnCorrectTypeRule], hide_suggestions=True ... ) >>> print(errors[0].message) Cannot query field 'name' on type 'Query'.
- class graphql.validation.ASTValidationContext(ast: DocumentNode, on_error: Callable[[GraphQLError], None])
Bases:
objectUtility class providing a context for validation of an AST.
An instance of this class is passed as the context attribute to all Validators, allowing access to commonly useful contextual information from within a validation rule.
- Parameters:
ast – Document AST being validated.
on_error – Callback invoked for each validation error.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext >>> errors = [] >>> context = ASTValidationContext(parse('{ greeting }'), errors.append) >>> context.document.kind 'document' >>> context.report_error(GraphQLError('Example validation error.')) >>> errors[0].message 'Example validation error.'
- document: DocumentNode
The document AST being validated.
- get_fragment(name: str) FragmentDefinitionNode | None
Get the fragment definition with the given name from the document.
- Parameters:
name – The name of the fragment.
- Returns:
The fragment definition, or
Noneif there is no such fragment.
>>> from graphql import parse >>> from graphql.validation import ASTValidationContext >>> document = parse('{ ...Greeting } fragment Greeting on Query { greeting }') >>> context = ASTValidationContext(document, print) >>> context.get_fragment('Greeting').type_condition.name.value 'Query' >>> context.get_fragment('Missing') is None True
- get_fragment_spreads(node: SelectionSetNode) list[FragmentSpreadNode]
Get all fragment spreads contained in the given selection set.
This includes fragment spreads in nested selection sets, but not the ones inside the spread fragments themselves.
- Parameters:
node – The selection set node to inspect.
- Returns:
The fragment spreads found in the selection set.
>>> from graphql import parse >>> from graphql.validation import ASTValidationContext >>> document = parse('{ ...A viewer { ...B } }') >>> context = ASTValidationContext(document, print) >>> selection_set = document.definitions[0].selection_set >>> spreads = context.get_fragment_spreads(selection_set) >>> [spread.name.value for spread in spreads] ['A', 'B']
- get_recursively_referenced_fragments(operation: OperationDefinitionNode) list[FragmentDefinitionNode]
Get all fragments referenced by the operation, directly or indirectly.
- Parameters:
operation – The operation definition to inspect.
- Returns:
The fragment definitions reachable from the operation.
>>> from graphql import parse >>> from graphql.validation import ASTValidationContext >>> document = parse(''' ... { ...A } ... fragment A on Query { ...B } ... fragment B on Query { greeting } ... ''') >>> context = ASTValidationContext(document, print) >>> operation = document.definitions[0] >>> fragments = context.get_recursively_referenced_fragments(operation) >>> [fragment.name.value for fragment in fragments] ['A', 'B']
- get_recursively_referenced_fragments_for_operations(operations: Collection[OperationDefinitionNode]) list[FragmentDefinitionNode]
Get all fragments referenced by the operations, directly or indirectly.
- Parameters:
operations – The operation definitions to inspect.
- Returns:
The fragment definitions reachable from any of the operations.
>>> from graphql import parse >>> from graphql.validation import ASTValidationContext >>> document = parse(''' ... query One { ...A } ... query Two { ...B } ... fragment A on Query { greeting } ... fragment B on Query { farewell } ... fragment C on Query { greeting } ... ''') >>> context = ASTValidationContext(document, print) >>> operations = document.definitions[:2] >>> fragments = context.get_recursively_referenced_fragments_for_operations( ... operations) >>> sorted(fragment.name.value for fragment in fragments) ['A', 'B']
- on_error(error: GraphQLError) None
Handle a validation error.
This method is replaced with the
on_errorcallback passed to the constructor.- Parameters:
error – The validation error.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> context.on_error(GraphQLError('Example validation error.')) Example validation error.
- report_error(error: GraphQLError) None
Report a validation error.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext >>> errors = [] >>> context = ASTValidationContext(parse('{ greeting }'), errors.append) >>> context.report_error(GraphQLError('Example validation error.')) >>> errors[0].message 'Example validation error.'
- class graphql.validation.ASTValidationRule(context: ASTValidationContext)
Bases:
VisitorVisitor for validation of an AST.
This is the base class of all validation rules.
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import GraphQLError, parse, visit >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> class NoAnonymousOperationsRule(ASTValidationRule): ... def enter_operation_definition(self, node, *_args): ... if not node.name: ... self.report_error(GraphQLError('Name all operations.', node)) >>> document = parse('{ greeting }') >>> errors = [] >>> context = ASTValidationContext(document, errors.append) >>> _ = visit(document, NoAnonymousOperationsRule(context)) >>> print(errors[0].message) Name all operations.
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ASTValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
- class graphql.validation.SDLValidationContext(ast: DocumentNode, schema: GraphQLSchema | None, on_error: Callable[[GraphQLError], None])
Bases:
ASTValidationContextUtility class providing a context for validation of an SDL AST.
An instance of this class is passed as the context attribute to all Validators, allowing access to commonly useful contextual information from within a validation rule.
- Parameters:
ast – SDL document AST being validated.
schema – Schema being extended, if any.
on_error – Callback invoked for each validation error.
>>> from graphql import build_schema, parse >>> from graphql.validation import SDLValidationContext >>> schema = build_schema('type Query { greeting: String }') >>> document = parse('extend type Query { farewell: String }') >>> context = SDLValidationContext(document, schema, print) >>> context.schema is schema True >>> SDLValidationContext(document, None, print).schema is None True
- document
The document AST being validated.
- get_fragment(name: str) FragmentDefinitionNode | None
Get the fragment definition with the given name from the document.
- Parameters:
name – The name of the fragment.
- Returns:
The fragment definition, or
Noneif there is no such fragment.
>>> from graphql import parse >>> from graphql.validation import ASTValidationContext >>> document = parse('{ ...Greeting } fragment Greeting on Query { greeting }') >>> context = ASTValidationContext(document, print) >>> context.get_fragment('Greeting').type_condition.name.value 'Query' >>> context.get_fragment('Missing') is None True
- get_fragment_spreads(node: SelectionSetNode) list[FragmentSpreadNode]
Get all fragment spreads contained in the given selection set.
This includes fragment spreads in nested selection sets, but not the ones inside the spread fragments themselves.
- Parameters:
node – The selection set node to inspect.
- Returns:
The fragment spreads found in the selection set.
>>> from graphql import parse >>> from graphql.validation import ASTValidationContext >>> document = parse('{ ...A viewer { ...B } }') >>> context = ASTValidationContext(document, print) >>> selection_set = document.definitions[0].selection_set >>> spreads = context.get_fragment_spreads(selection_set) >>> [spread.name.value for spread in spreads] ['A', 'B']
- get_recursively_referenced_fragments(operation: OperationDefinitionNode) list[FragmentDefinitionNode]
Get all fragments referenced by the operation, directly or indirectly.
- Parameters:
operation – The operation definition to inspect.
- Returns:
The fragment definitions reachable from the operation.
>>> from graphql import parse >>> from graphql.validation import ASTValidationContext >>> document = parse(''' ... { ...A } ... fragment A on Query { ...B } ... fragment B on Query { greeting } ... ''') >>> context = ASTValidationContext(document, print) >>> operation = document.definitions[0] >>> fragments = context.get_recursively_referenced_fragments(operation) >>> [fragment.name.value for fragment in fragments] ['A', 'B']
- get_recursively_referenced_fragments_for_operations(operations: Collection[OperationDefinitionNode]) list[FragmentDefinitionNode]
Get all fragments referenced by the operations, directly or indirectly.
- Parameters:
operations – The operation definitions to inspect.
- Returns:
The fragment definitions reachable from any of the operations.
>>> from graphql import parse >>> from graphql.validation import ASTValidationContext >>> document = parse(''' ... query One { ...A } ... query Two { ...B } ... fragment A on Query { greeting } ... fragment B on Query { farewell } ... fragment C on Query { greeting } ... ''') >>> context = ASTValidationContext(document, print) >>> operations = document.definitions[:2] >>> fragments = context.get_recursively_referenced_fragments_for_operations( ... operations) >>> sorted(fragment.name.value for fragment in fragments) ['A', 'B']
- property hide_suggestions: bool
Whether validation error suggestions are hidden (always false for SDL).
- on_error(error: GraphQLError) None
Handle a validation error.
This method is replaced with the
on_errorcallback passed to the constructor.- Parameters:
error – The validation error.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> context.on_error(GraphQLError('Example validation error.')) Example validation error.
- report_error(error: GraphQLError) None
Report a validation error.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext >>> errors = [] >>> context = ASTValidationContext(parse('{ greeting }'), errors.append) >>> context.report_error(GraphQLError('Example validation error.')) >>> errors[0].message 'Example validation error.'
- schema: GraphQLSchema | None
The schema being extended, if any.
- class graphql.validation.SDLValidationRule(context: SDLValidationContext)
Bases:
ASTValidationRuleVisitor for validation of an SDL AST.
- Parameters:
context – The validation context used while checking the SDL document.
>>> from graphql import GraphQLError, parse, visit >>> from graphql.validation import SDLValidationContext, SDLValidationRule >>> class NoInterfacesRule(SDLValidationRule): ... def enter_interface_type_definition(self, node, *_args): ... self.report_error(GraphQLError('No interfaces allowed.', node)) >>> document = parse('interface Node { id: ID } type Query { node: Node }') >>> errors = [] >>> context = SDLValidationContext(document, None, errors.append) >>> _ = visit(document, NoInterfacesRule(context)) >>> print(errors[0].message) No interfaces allowed.
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: SDLValidationContext
The validation context used while checking the SDL document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
- class graphql.validation.ValidationContext(schema: GraphQLSchema, ast: DocumentNode, type_info: TypeInfo, on_error: Callable[[GraphQLError], None], hide_suggestions: bool = False, allow_empty_selection_sets: bool = True)
Bases:
ASTValidationContextUtility class providing a context for validation using a GraphQL schema.
An instance of this class is passed as the context attribute to all Validators, allowing access to commonly useful contextual information from within a validation rule.
- Parameters:
schema – Schema used to validate the document.
ast – Document AST being validated.
type_info – TypeInfo instance used to track traversal state.
on_error – Callback invoked for each validation error.
hide_suggestions – Whether suggestion text should be omitted from errors.
allow_empty_selection_sets – Whether selection sets on composite types may be empty (the default). Deprecated, since empty selection sets are now always allowed.
>>> from graphql import GraphQLError, TypeInfo, build_schema, parse >>> from graphql.validation import ValidationContext >>> schema = build_schema('type Query { greeting: String }') >>> document = parse('{ greeting }') >>> errors = [] >>> context = ValidationContext(schema, document, TypeInfo(schema), errors.append) >>> context.report_error(GraphQLError('Example validation error.')) >>> context.schema is schema True >>> errors[0].message 'Example validation error.'
- property allow_empty_selection_sets: bool
Whether empty selection sets on composite types are allowed.
Deprecated, since empty selection sets are now always allowed.
- document
The document AST being validated.
- 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) >>> from graphql.validation import ValidationContext >>> schema = build_schema('type Query { reviews(limit: Int): [String] }') >>> document = parse('{ reviews(limit: 5) }') >>> type_info = TypeInfo(schema) >>> context = ValidationContext( ... schema, document, type_info, lambda error: None) >>> class PrintVisitor(Visitor): ... def enter_argument(self, *_args): ... print(context.get_argument().type) >>> _ = visit(document, TypeInfoVisitor(type_info, PrintVisitor())) Int
- 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) >>> from graphql.validation import ValidationContext >>> schema = build_schema('type Query { greeting: String }') >>> document = parse('{ greeting @include(if: true) }') >>> type_info = TypeInfo(schema) >>> context = ValidationContext( ... schema, document, type_info, lambda error: None) >>> class PrintVisitor(Visitor): ... def enter_directive(self, *_args): ... print(context.get_directive().name) >>> _ = visit(document, TypeInfoVisitor(type_info, PrintVisitor())) 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) >>> from graphql.validation import ValidationContext >>> schema = build_schema(''' ... enum Sort { NEWEST OLDEST } ... type Query { reviews(sort: Sort): [String] } ... ''') >>> document = parse('{ reviews(sort: OLDEST) }') >>> type_info = TypeInfo(schema) >>> context = ValidationContext( ... schema, document, type_info, lambda error: None) >>> class PrintVisitor(Visitor): ... def enter_enum_value(self, *_args): ... print(context.get_enum_value().value) >>> _ = visit(document, TypeInfoVisitor(type_info, PrintVisitor())) 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) >>> from graphql.validation import ValidationContext >>> schema = build_schema('type Query { greeting: String }') >>> document = parse('{ greeting }') >>> type_info = TypeInfo(schema) >>> context = ValidationContext( ... schema, document, type_info, lambda error: None) >>> class PrintVisitor(Visitor): ... def enter_field(self, *_args): ... print(context.get_field_def().type) >>> _ = visit(document, TypeInfoVisitor(type_info, PrintVisitor())) String
- get_fragment(name: str) FragmentDefinitionNode | None
Get the fragment definition with the given name from the document.
- Parameters:
name – The name of the fragment.
- Returns:
The fragment definition, or
Noneif there is no such fragment.
>>> from graphql import parse >>> from graphql.validation import ASTValidationContext >>> document = parse('{ ...Greeting } fragment Greeting on Query { greeting }') >>> context = ASTValidationContext(document, print) >>> context.get_fragment('Greeting').type_condition.name.value 'Query' >>> context.get_fragment('Missing') is None True
- get_fragment_signature() FragmentSignature | None
Get the fragment signature referenced by the current fragment spread.
- Returns:
The referenced fragment signature, if available.
>>> from graphql import ( ... TypeInfo, TypeInfoVisitor, Visitor, build_schema, parse, visit) >>> from graphql.validation import ValidationContext >>> schema = build_schema('type Query { greeting: String }') >>> document = parse( ... '{ ...GreetingFields } fragment GreetingFields on Query { greeting }', ... experimental_fragment_arguments=True, ... ) >>> type_info = TypeInfo(schema) >>> context = ValidationContext( ... schema, document, type_info, lambda error: None) >>> class PrintVisitor(Visitor): ... def enter_fragment_spread(self, *_args): ... print(context.get_fragment_signature().definition.name.value) >>> _ = visit(document, TypeInfoVisitor(type_info, PrintVisitor())) GreetingFields
- get_fragment_signature_by_name() FragmentSignatureByNameFn
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) >>> from graphql.validation import ValidationContext >>> schema = build_schema('type Query { greeting: String }') >>> document = parse( ... '{ ...GreetingFields } fragment GreetingFields on Query { greeting }', ... experimental_fragment_arguments=True, ... ) >>> type_info = TypeInfo(schema) >>> context = ValidationContext( ... schema, document, type_info, lambda error: None) >>> class PrintVisitor(Visitor): ... def enter_document(self, *_args): ... get_fragment_signature = context.get_fragment_signature_by_name() ... signature = get_fragment_signature('GreetingFields') ... print(signature.definition.name.value) >>> _ = visit(document, TypeInfoVisitor(type_info, PrintVisitor())) GreetingFields
- get_fragment_spreads(node: SelectionSetNode) list[FragmentSpreadNode]
Get all fragment spreads contained in the given selection set.
This includes fragment spreads in nested selection sets, but not the ones inside the spread fragments themselves.
- Parameters:
node – The selection set node to inspect.
- Returns:
The fragment spreads found in the selection set.
>>> from graphql import parse >>> from graphql.validation import ASTValidationContext >>> document = parse('{ ...A viewer { ...B } }') >>> context = ASTValidationContext(document, print) >>> selection_set = document.definitions[0].selection_set >>> spreads = context.get_fragment_spreads(selection_set) >>> [spread.name.value for spread in spreads] ['A', 'B']
- get_input_type() GraphQLInputType | 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) >>> from graphql.validation import ValidationContext >>> schema = build_schema('type Query { reviews(limit: Int): [String] }') >>> document = parse('{ reviews(limit: 5) }') >>> type_info = TypeInfo(schema) >>> context = ValidationContext( ... schema, document, type_info, lambda error: None) >>> class PrintVisitor(Visitor): ... def enter_argument(self, *_args): ... print(context.get_input_type()) >>> _ = visit(document, TypeInfoVisitor(type_info, PrintVisitor())) Int
- get_parent_input_type() GraphQLInputType | 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) >>> from graphql.validation import ValidationContext >>> schema = build_schema(''' ... input ReviewFilter { stars: Int } ... type Query { reviews(filter: ReviewFilter): [String] } ... ''') >>> document = parse('{ reviews(filter: { stars: 5 }) }') >>> type_info = TypeInfo(schema) >>> context = ValidationContext( ... schema, document, type_info, lambda error: None) >>> class PrintVisitor(Visitor): ... def enter_object_field(self, *_args): ... print(context.get_parent_input_type()) >>> _ = visit(document, TypeInfoVisitor(type_info, PrintVisitor())) ReviewFilter
- get_parent_type() GraphQLCompositeType | 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) >>> from graphql.validation import ValidationContext >>> schema = build_schema('type Query { greeting: String }') >>> document = parse('{ greeting }') >>> type_info = TypeInfo(schema) >>> context = ValidationContext( ... schema, document, type_info, lambda error: None) >>> class PrintVisitor(Visitor): ... def enter_field(self, *_args): ... print(context.get_parent_type().name) >>> _ = visit(document, TypeInfoVisitor(type_info, PrintVisitor())) Query
- get_recursive_variable_usages(operation: OperationDefinitionNode) list[VariableUsage]
Get variable usages for an operation, including referenced fragments.
- Parameters:
operation – Operation definition to inspect.
- Returns:
Variable usages reachable from the operation.
>>> from graphql import TypeInfo, build_schema, parse >>> from graphql.validation import ValidationContext >>> schema = build_schema(''' ... type Query { viewer: User } ... type User { name(prefix: String): String } ... ''') >>> document = parse(''' ... query ($prefix: String) { viewer { ...UserName } } ... fragment UserName on User { name(prefix: $prefix) } ... ''') >>> operation = document.definitions[0] >>> context = ValidationContext( ... schema, document, TypeInfo(schema), lambda error: None) >>> usages = context.get_recursive_variable_usages(operation) >>> [usage.node.name.value for usage in usages] ['prefix']
- get_recursively_referenced_fragments(operation: OperationDefinitionNode) list[FragmentDefinitionNode]
Get all fragments referenced by the operation, directly or indirectly.
- Parameters:
operation – The operation definition to inspect.
- Returns:
The fragment definitions reachable from the operation.
>>> from graphql import parse >>> from graphql.validation import ASTValidationContext >>> document = parse(''' ... { ...A } ... fragment A on Query { ...B } ... fragment B on Query { greeting } ... ''') >>> context = ASTValidationContext(document, print) >>> operation = document.definitions[0] >>> fragments = context.get_recursively_referenced_fragments(operation) >>> [fragment.name.value for fragment in fragments] ['A', 'B']
- get_recursively_referenced_fragments_for_operations(operations: Collection[OperationDefinitionNode]) list[FragmentDefinitionNode]
Get all fragments referenced by the operations, directly or indirectly.
- Parameters:
operations – The operation definitions to inspect.
- Returns:
The fragment definitions reachable from any of the operations.
>>> from graphql import parse >>> from graphql.validation import ASTValidationContext >>> document = parse(''' ... query One { ...A } ... query Two { ...B } ... fragment A on Query { greeting } ... fragment B on Query { farewell } ... fragment C on Query { greeting } ... ''') >>> context = ASTValidationContext(document, print) >>> operations = document.definitions[:2] >>> fragments = context.get_recursively_referenced_fragments_for_operations( ... operations) >>> sorted(fragment.name.value for fragment in fragments) ['A', 'B']
- get_type() GraphQLOutputType | 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) >>> from graphql.validation import ValidationContext >>> schema = build_schema('type Query { greeting: String }') >>> document = parse('{ greeting }') >>> type_info = TypeInfo(schema) >>> context = ValidationContext( ... schema, document, type_info, lambda error: None) >>> class PrintVisitor(Visitor): ... def enter_field(self, *_args): ... print(context.get_type()) >>> _ = visit(document, TypeInfoVisitor(type_info, PrintVisitor())) String
- get_variable_usages(node: OperationDefinitionNode | FragmentDefinitionNode) list[VariableUsage]
Get variable usages found directly within the given node.
- Parameters:
node – The operation or fragment definition to inspect.
- Returns:
Variable usages found directly within this node.
>>> from graphql import TypeInfo, build_schema, parse >>> from graphql.validation import ValidationContext >>> schema = build_schema('type Query { greeting(name: String): String }') >>> document = parse('query ($name: String) { greeting(name: $name) }') >>> operation = document.definitions[0] >>> context = ValidationContext( ... schema, document, TypeInfo(schema), lambda error: None) >>> usages = context.get_variable_usages(operation) >>> usages[0].node.name.value 'name' >>> str(usages[0].type) 'String'
- property hide_suggestions: bool
Whether validation error suggestions are hidden.
- on_error(error: GraphQLError) None
Handle a validation error.
This method is replaced with the
on_errorcallback passed to the constructor.- Parameters:
error – The validation error.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> context.on_error(GraphQLError('Example validation error.')) Example validation error.
- report_error(error: GraphQLError) None
Report a validation error.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext >>> errors = [] >>> context = ASTValidationContext(parse('{ greeting }'), errors.append) >>> context.report_error(GraphQLError('Example validation error.')) >>> errors[0].message 'Example validation error.'
- schema: GraphQLSchema
The schema being validated against.
- class graphql.validation.ValidationRule(context: ValidationContext)
Bases:
ASTValidationRuleVisitor for validation using a GraphQL schema.
A validation rule creates an AST visitor for validating a GraphQL document. Custom validation rules can be created by subclassing this class and reporting errors with its
report_error()method.- Parameters:
context – The validation context used while checking the document.
>>> from graphql import GraphQLError, build_schema, parse, validate >>> from graphql.validation import ValidationRule >>> class NoAliasesRule(ValidationRule): ... def enter_field(self, node, *_args): ... if node.alias: ... self.report_error(GraphQLError('Aliases are not allowed.', node)) >>> schema = build_schema('type Query { name: String }') >>> document = parse('{ alias: name }') >>> errors = validate(schema, document, [NoAliasesRule]) >>> print(errors[0].message) Aliases are not allowed. >>> document = parse('{ name }') >>> validate(schema, document, [NoAliasesRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Rules
- graphql.validation.specified_rules
A tuple with all validation rules defined by the GraphQL specification
- graphql.validation.recommended_rules
A tuple with validation rules that are not part of the GraphQL specification, but recommended to be used, like limiting the depth of introspection queries
Spec Section: “Defer And Stream Directive Labels Are Unique”
- class graphql.validation.DeferStreamDirectiveLabel(context: ValidationContext)
Bases:
ASTValidationRuleDefer and stream directive labels are unique
A GraphQL document is only valid if defer and stream directives’ label argument is static and unique.
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import DeferStreamDirectiveLabel >>> schema = build_schema('type Query { friends: [String] }') >>> document = parse( ... '{ friends @stream(label: "friends")' ... ' other: friends @stream(label: "friends") }' ... ) >>> errors = validate(schema, document, [DeferStreamDirectiveLabel]) >>> print(errors[0].message) Defer/Stream directive label argument must be unique. >>> document = parse( ... '{ friends @stream(label: "friends")' ... ' other: friends @stream(label: "otherFriends") }' ... ) >>> validate(schema, document, [DeferStreamDirectiveLabel]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ASTValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Defer And Stream Directives Are Used On Valid Root Field”
- class graphql.validation.DeferStreamDirectiveOnRootField(context: ValidationContext)
Bases:
ValidationRuleDefer and stream directives are used on valid root field
A GraphQL document is only valid if defer directives are not used on root mutation or subscription types.
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import DeferStreamDirectiveOnRootField >>> schema = build_schema( ... 'type Query { message: String } type Mutation { updateMessage: String }' ... ) >>> document = parse('mutation { ... @defer { updateMessage } }') >>> errors = validate(schema, document, [DeferStreamDirectiveOnRootField]) >>> print(errors[0].message) Defer directive cannot be used on root mutation type 'Mutation'. >>> document = parse('{ ... @defer { message } }') >>> validate(schema, document, [DeferStreamDirectiveOnRootField]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Defer And Stream Directives Are Used On Valid Operations”
- class graphql.validation.DeferStreamDirectiveOnValidOperationsRule(context: ASTValidationContext)
Bases:
ASTValidationRuleDefer and stream directives are used on valid operations
Subscription operations must not use unconditional
@deferor@stream. Theirifargument must befalseor a variable, unless the selection or an enclosing selection can be skipped via@skipor@include.- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import DeferStreamDirectiveOnValidOperationsRule >>> schema = build_schema( ... 'type Query { message: Message } type Subscription { message: Message }' ... ' type Message { body: String }' ... ) >>> document = parse( ... 'subscription { message { ...MessageBody @defer } }' ... ' fragment MessageBody on Message { body }' ... ) >>> errors = validate( ... schema, document, [DeferStreamDirectiveOnValidOperationsRule] ... ) >>> print(errors[0].message) Defer directive not supported on subscription operations. Disable `@defer` by setting the `if` argument to `false`. >>> document = parse( ... 'subscription { message { ...MessageBody @defer(if: false) } }' ... ' fragment MessageBody on Message { body }' ... ) >>> validate(schema, document, [DeferStreamDirectiveOnValidOperationsRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ASTValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Executable Definitions”
- class graphql.validation.ExecutableDefinitionsRule(context: ASTValidationContext)
Bases:
ASTValidationRuleExecutable definitions
A GraphQL document is only valid for execution if all definitions are either operation or fragment definitions.
See https://spec.graphql.org/draft/#sec-Executable-Definitions
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import ExecutableDefinitionsRule >>> schema = build_schema('type Query { name: String }') >>> document = parse('type Extra { field: String }') >>> errors = validate(schema, document, [ExecutableDefinitionsRule]) >>> print(errors[0].message) The 'Extra' definition is not executable. >>> document = parse('{ name }') >>> validate(schema, document, [ExecutableDefinitionsRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ASTValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Field Selections on Objects, Interfaces, and Unions Types”
- class graphql.validation.FieldsOnCorrectTypeRule(context: ValidationContext)
Bases:
ValidationRuleFields on correct type
A GraphQL document is only valid if all fields selected are defined by the parent type, or are an allowed meta field such as
__typename.See https://spec.graphql.org/draft/#sec-Field-Selections
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import FieldsOnCorrectTypeRule >>> schema = build_schema('type Query { name: String }') >>> document = parse('{ missing }') >>> errors = validate(schema, document, [FieldsOnCorrectTypeRule]) >>> print(errors[0].message) Cannot query field 'missing' on type 'Query'. >>> document = parse('{ name }') >>> validate(schema, document, [FieldsOnCorrectTypeRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Fragments on Composite Types”
- class graphql.validation.FragmentsOnCompositeTypesRule(context: ValidationContext)
Bases:
ValidationRuleFragments on composite type
Fragments use a type condition to determine if they apply, since fragments can only be spread into a composite type (object, interface, or union), the type condition must also be a composite type.
See https://spec.graphql.org/draft/#sec-Fragments-On-Composite-Types
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import FragmentsOnCompositeTypesRule >>> schema = build_schema('type Query { name: String }') >>> document = parse('fragment Bad on String { length }') >>> errors = validate(schema, document, [FragmentsOnCompositeTypesRule]) >>> print(errors[0].message) Fragment 'Bad' cannot condition on non composite type 'String'. >>> document = parse('fragment Good on Query { name }') >>> validate(schema, document, [FragmentsOnCompositeTypesRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Argument Names”
- class graphql.validation.KnownArgumentNamesRule(context: ValidationContext)
Bases:
KnownArgumentNamesOnDirectivesRuleKnown argument names
A GraphQL field is only valid if all supplied arguments are defined by that field.
See https://spec.graphql.org/draft/#sec-Argument-Names See https://spec.graphql.org/draft/#sec-Directives-Are-In-Valid-Locations
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import KnownArgumentNamesRule >>> schema = build_schema('type Query { field(arg: String): String }') >>> document = parse('{ field(unknown: "1") }') >>> errors = validate(schema, document, [KnownArgumentNamesRule]) >>> print(errors[0].message) Unknown argument 'unknown' on field 'Query.field'. >>> document = parse('{ field(arg: "1") }') >>> validate(schema, document, [KnownArgumentNamesRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext
The validation context used while checking the document.
- enter_directive(directive_node: DirectiveNode, *_args: Any) VisitorActionEnum | None
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Directives Are Defined”
- class graphql.validation.KnownDirectivesRule(context: ValidationContext | SDLValidationContext)
Bases:
ASTValidationRuleKnown directives
A GraphQL document is only valid if all
@directivesare known by the schema and legally positioned.See https://spec.graphql.org/draft/#sec-Directives-Are-Defined
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import KnownDirectivesRule >>> schema = build_schema('type Query { name: String }') >>> document = parse('{ name @unknown }') >>> errors = validate(schema, document, [KnownDirectivesRule]) >>> print(errors[0].message) Unknown directive '@unknown'. >>> document = parse('{ name @include(if: true) }') >>> validate(schema, document, [KnownDirectivesRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext | SDLValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Fragment spread target defined”
- class graphql.validation.KnownFragmentNamesRule(context: ValidationContext)
Bases:
ValidationRuleKnown fragment names
A GraphQL document is only valid if all
...Fragmentfragment spreads refer to fragments defined in the same document.See https://spec.graphql.org/draft/#sec-Fragment-spread-target-defined
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import KnownFragmentNamesRule >>> schema = build_schema('type Query { name: String }') >>> document = parse('{ ...Missing }') >>> errors = validate(schema, document, [KnownFragmentNamesRule]) >>> print(errors[0].message) Unknown fragment 'Missing'. >>> document = parse( ... 'fragment NameFields on Query { name } query { ...NameFields }' ... ) >>> validate(schema, document, [KnownFragmentNamesRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Operation Type Existence”
- class graphql.validation.KnownOperationTypesRule(context: ValidationContext)
Bases:
ValidationRuleKnown Operation Types
A GraphQL document is only valid if when it contains an operation, the root type for the operation exists within the schema.
See https://spec.graphql.org/draft/#sec-Operation-Type-Existence
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import KnownOperationTypesRule >>> schema = build_schema('type Query { greeting: String }') >>> document = parse('mutation { greeting }') >>> errors = validate(schema, document, [KnownOperationTypesRule]) >>> print(errors[0].message) The mutation operation is not supported by the schema. >>> document = parse('{ greeting }') >>> validate(schema, document, [KnownOperationTypesRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Fragment Spread Type Existence”
- class graphql.validation.KnownTypeNamesRule(context: ValidationContext | SDLValidationContext)
Bases:
ASTValidationRuleKnown type names
A GraphQL document is only valid if referenced types (specifically variable definitions and fragment conditions) are defined by the type schema.
See https://spec.graphql.org/draft/#sec-Fragment-Spread-Type-Existence
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import KnownTypeNamesRule >>> schema = build_schema('type Query { name: String }') >>> document = parse('fragment Bad on Missing { name }') >>> errors = validate(schema, document, [KnownTypeNamesRule]) >>> print(errors[0].message) Unknown type 'Missing'. >>> document = parse('fragment Good on Query { name }') >>> validate(schema, document, [KnownTypeNamesRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext | SDLValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Lone Anonymous Operation”
- class graphql.validation.LoneAnonymousOperationRule(context: ASTValidationContext)
Bases:
ASTValidationRuleLone anonymous operation
A GraphQL document is only valid if when it contains an anonymous operation (the query short-hand) that it contains only that one operation definition.
See https://spec.graphql.org/draft/#sec-Lone-Anonymous-Operation
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import LoneAnonymousOperationRule >>> schema = build_schema('type Query { name: String }') >>> document = parse('query { name } query Other { name }') >>> errors = validate(schema, document, [LoneAnonymousOperationRule]) >>> print(errors[0].message) This anonymous operation must be the only defined operation. >>> document = parse('{ name }') >>> validate(schema, document, [LoneAnonymousOperationRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ASTValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Fragments must not form cycles”
- class graphql.validation.NoFragmentCyclesRule(context: ASTValidationContext)
Bases:
ASTValidationRuleNo fragment cycles
The graph of fragment spreads must not form any cycles including spreading itself. Otherwise an operation could infinitely spread or infinitely execute on cycles in the underlying data.
See https://spec.graphql.org/draft/#sec-Fragment-spreads-must-not-form-cycles
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import NoFragmentCyclesRule >>> schema = build_schema('type Query { name: String }') >>> document = parse( ... 'fragment A on Query { ...B } fragment B on Query { ...A } query { ...A }' ... ) >>> errors = validate(schema, document, [NoFragmentCyclesRule]) >>> print(errors[0].message) Cannot spread fragment 'A' within itself via 'B'. >>> document = parse('fragment A on Query { name } query { ...A }') >>> validate(schema, document, [NoFragmentCyclesRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ASTValidationContext
The validation context used while checking the document.
- enter_leave_map: dict[str, EnterLeaveVisitor]
Cache of the enter and leave methods of this visitor per node kind.
- static enter_operation_definition(*_args: Any) VisitorActionEnum | None
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “All Variable Used Defined”
- class graphql.validation.NoUndefinedVariablesRule(context: ValidationContext)
Bases:
ValidationRuleNo undefined variables
A GraphQL operation is only valid if all variables encountered, both directly and via fragment spreads, are defined by that operation.
See https://spec.graphql.org/draft/#sec-All-Variable-Uses-Defined
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import NoUndefinedVariablesRule >>> schema = build_schema('type Query { field(arg: ID): String }') >>> document = parse('query ($id: ID) { field(arg: $missing) }') >>> errors = validate(schema, document, [NoUndefinedVariablesRule]) >>> print(errors[0].message) Variable '$missing' is not defined. >>> document = parse('query ($id: ID) { field(arg: $id) }') >>> validate(schema, document, [NoUndefinedVariablesRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Fragments must be used”
- class graphql.validation.NoUnusedFragmentsRule(context: ASTValidationContext)
Bases:
ASTValidationRuleNo unused fragments
A GraphQL document is only valid if all fragment definitions are spread within operations, or spread within other fragments spread within operations.
See https://spec.graphql.org/draft/#sec-Fragments-Must-Be-Used
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import NoUnusedFragmentsRule >>> schema = build_schema('type Query { name: String }') >>> document = parse('fragment Unused on Query { name } query { name }') >>> errors = validate(schema, document, [NoUnusedFragmentsRule]) >>> print(errors[0].message) Fragment 'Unused' is never used. >>> document = parse('fragment Used on Query { name } query { ...Used }') >>> validate(schema, document, [NoUnusedFragmentsRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ASTValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “All Variables Used”
- class graphql.validation.NoUnusedVariablesRule(context: ValidationContext)
Bases:
ValidationRuleNo unused variables
A GraphQL operation is only valid if all variables defined by an operation are used, either directly or within a spread fragment.
See https://spec.graphql.org/draft/#sec-All-Variables-Used
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import NoUnusedVariablesRule >>> schema = build_schema('type Query { field(arg: ID): String name: String }') >>> document = parse('query ($id: ID) { name }') >>> errors = validate(schema, document, [NoUnusedVariablesRule]) >>> print(errors[0].message) Variable '$id' is never used. >>> document = parse('query ($id: ID) { field(arg: $id) }') >>> validate(schema, document, [NoUnusedVariablesRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Field Selection Merging”
- class graphql.validation.OverlappingFieldsCanBeMergedRule(context: ValidationContext)
Bases:
ValidationRuleOverlapping fields can be merged
A selection set is only valid if all fields (including spreading any fragments) either correspond to distinct response names or can be merged without ambiguity.
See https://spec.graphql.org/draft/#sec-Field-Selection-Merging
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import OverlappingFieldsCanBeMergedRule >>> sdl = 'type Query { dog: Dog } type Dog { name: String barkVolume: Int }' >>> schema = build_schema(sdl) >>> document = parse('{ dog { value: barkVolume value: name } }') >>> errors = validate(schema, document, [OverlappingFieldsCanBeMergedRule]) >>> print(errors[0].message) Fields 'value' conflict because 'barkVolume' and 'name' are different fields. Use different aliases on the fields to fetch both if this was intentional. >>> document = parse('{ dog { barkVolume name } }') >>> validate(schema, document, [OverlappingFieldsCanBeMergedRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Fragment spread is possible”
- class graphql.validation.PossibleFragmentSpreadsRule(context: ValidationContext)
Bases:
ValidationRulePossible fragment spread
A fragment spread is only valid if the type condition could ever possibly be true: if there is a non-empty intersection of the possible parent types, and possible types which pass the type condition.
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import PossibleFragmentSpreadsRule >>> sdl = ( ... 'type Query { dog: Dog } type Dog { barkVolume: Int }' ... ' type Cat { meowVolume: Int }' ... ) >>> schema = build_schema(sdl) >>> document = parse('{ dog { ... on Cat { meowVolume } } }') >>> errors = validate(schema, document, [PossibleFragmentSpreadsRule]) >>> print(errors[0].message) Fragment cannot be spread here as objects of type 'Dog' can never be of type 'Cat'. >>> document = parse('{ dog { ... on Dog { barkVolume } } }') >>> validate(schema, document, [PossibleFragmentSpreadsRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Argument Optionality”
- class graphql.validation.ProvidedRequiredArgumentsRule(context: ValidationContext)
Bases:
ProvidedRequiredArgumentsOnDirectivesRuleProvided required arguments
A field or directive is only valid if all required (non-null without a default value) field arguments have been provided.
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import ProvidedRequiredArgumentsRule >>> schema = build_schema('type Query { field(required: String!): String }') >>> document = parse('{ field }') >>> errors = validate(schema, document, [ProvidedRequiredArgumentsRule]) >>> print(errors[0].message) Argument 'Query.field(required:)' of type 'String!' is required, but it was not provided. >>> document = parse('{ field(required: "x") }') >>> validate(schema, document, [ProvidedRequiredArgumentsRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext
The validation context used while checking the document.
- enter_leave_map
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
- leave_directive(directive_node: DirectiveNode, *_args: Any) None
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Leaf Field Selections”
- class graphql.validation.ScalarLeafsRule(context: ValidationContext)
Bases:
ValidationRuleScalar leafs
A GraphQL document is valid only if all leaf fields (fields without sub selections) are of scalar or enum types.
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import ScalarLeafsRule >>> schema = build_schema('type Query { name: String }') >>> document = parse('{ name { length } }') >>> errors = validate(schema, document, [ScalarLeafsRule]) >>> print(errors[0].message) Field 'name' must not have a selection since type 'String' has no subfields. >>> document = parse('{ name }') >>> validate(schema, document, [ScalarLeafsRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Subscriptions with Single Root Field”
- class graphql.validation.SingleFieldSubscriptionsRule(context: ValidationContext)
Bases:
ValidationRuleSubscriptions must only include a single non-introspection field.
A GraphQL subscription is valid only if it contains a single root field and that root field is not an introspection field.
See https://spec.graphql.org/draft/#sec-Single-root-field
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import SingleFieldSubscriptionsRule >>> sdl = 'type Query { name: String } type Subscription { a: String b: String }' >>> schema = build_schema(sdl) >>> document = parse('subscription { a b }') >>> errors = validate(schema, document, [SingleFieldSubscriptionsRule]) >>> print(errors[0].message) Anonymous Subscription must select only one top level field. >>> document = parse('subscription { a }') >>> validate(schema, document, [SingleFieldSubscriptionsRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Stream Directives Are Used On List Fields”
- class graphql.validation.StreamDirectiveOnListField(context: ASTValidationContext)
Bases:
ASTValidationRuleStream directives are used on list fields
A GraphQL document is only valid if stream directives are used on list fields.
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import StreamDirectiveOnListField >>> schema = build_schema('type Query { name: String friends: [String] }') >>> document = parse('{ name @stream(initialCount: 0) }') >>> errors = validate(schema, document, [StreamDirectiveOnListField]) >>> print(errors[0].message) Stream directive cannot be used on non-list field 'name' on type 'Query'. >>> document = parse('{ friends @stream(initialCount: 0) }') >>> validate(schema, document, [StreamDirectiveOnListField]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ASTValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Argument Uniqueness”
- class graphql.validation.UniqueArgumentNamesRule(context: ASTValidationContext)
Bases:
ASTValidationRuleUnique argument names
A GraphQL field or directive is only valid if all supplied arguments are uniquely named.
See https://spec.graphql.org/draft/#sec-Argument-Names
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import UniqueArgumentNamesRule >>> schema = build_schema('type Query { field(arg: String): String }') >>> document = parse('{ field(arg: "1", arg: "2") }') >>> errors = validate(schema, document, [UniqueArgumentNamesRule]) >>> print(errors[0].message) There can be only one argument named 'arg'. >>> document = parse('{ field(arg: "1") }') >>> validate(schema, document, [UniqueArgumentNamesRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ASTValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Directives Are Unique Per Location”
- class graphql.validation.UniqueDirectivesPerLocationRule(context: ValidationContext | SDLValidationContext)
Bases:
ASTValidationRuleUnique directive names per location
A GraphQL document is only valid if all non-repeatable directives at a given location are uniquely named.
See https://spec.graphql.org/draft/#sec-Directives-Are-Unique-Per-Location
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import UniqueDirectivesPerLocationRule >>> schema = build_schema('type Query { name: String }') >>> document = parse('{ name @include(if: true) @include(if: false) }') >>> errors = validate(schema, document, [UniqueDirectivesPerLocationRule]) >>> print(errors[0].message) The directive '@include' can only be used once at this location. >>> document = parse('{ name @include(if: true) }') >>> validate(schema, document, [UniqueDirectivesPerLocationRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext | SDLValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Fragment Name Uniqueness”
- class graphql.validation.UniqueFragmentNamesRule(context: ASTValidationContext)
Bases:
ASTValidationRuleUnique fragment names
A GraphQL document is only valid if all defined fragments have unique names.
See https://spec.graphql.org/draft/#sec-Fragment-Name-Uniqueness
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import UniqueFragmentNamesRule >>> schema = build_schema('type Query { name: String }') >>> document = parse( ... 'fragment A on Query { name } fragment A on Query { name } query { ...A }' ... ) >>> errors = validate(schema, document, [UniqueFragmentNamesRule]) >>> print(errors[0].message) There can be only one fragment named 'A'. >>> document = parse('fragment A on Query { name } query { ...A }') >>> validate(schema, document, [UniqueFragmentNamesRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ASTValidationContext
The validation context used while checking the document.
- enter_leave_map: dict[str, EnterLeaveVisitor]
Cache of the enter and leave methods of this visitor per node kind.
- static enter_operation_definition(*_args: Any) VisitorActionEnum | None
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Input Object Field Uniqueness”
- class graphql.validation.UniqueInputFieldNamesRule(context: ASTValidationContext)
Bases:
ASTValidationRuleUnique input field names
A GraphQL input object value is only valid if all supplied fields are uniquely named.
See https://spec.graphql.org/draft/#sec-Input-Object-Field-Uniqueness
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import UniqueInputFieldNamesRule >>> sdl = ( ... 'input Filter { name: String }' ... ' type Query { search(filter: Filter): String }' ... ) >>> schema = build_schema(sdl) >>> document = parse('{ search(filter: { name: "a", name: "b" }) }') >>> errors = validate(schema, document, [UniqueInputFieldNamesRule]) >>> print(errors[0].message) There can be only one input field named 'name'. >>> document = parse('{ search(filter: { name: "a" }) }') >>> validate(schema, document, [UniqueInputFieldNamesRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context
The validation context used while checking the document.
- enter_leave_map
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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Operation Name Uniqueness”
- class graphql.validation.UniqueOperationNamesRule(context: ASTValidationContext)
Bases:
ASTValidationRuleUnique operation names
A GraphQL document is only valid if all defined operations have unique names.
See https://spec.graphql.org/draft/#sec-Operation-Name-Uniqueness
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import UniqueOperationNamesRule >>> schema = build_schema('type Query { name: String }') >>> document = parse('query Same { name } query Same { name }') >>> errors = validate(schema, document, [UniqueOperationNamesRule]) >>> print(errors[0].message) There can be only one operation named 'Same'. >>> document = parse('query One { name } query Two { name }') >>> validate(schema, document, [UniqueOperationNamesRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ASTValidationContext
The validation context used while checking the document.
- static enter_fragment_definition(*_args: Any) VisitorActionEnum | None
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Variable Uniqueness”
- class graphql.validation.UniqueVariableNamesRule(context: ASTValidationContext)
Bases:
ASTValidationRuleUnique variable names
A GraphQL operation is only valid if all its variables are uniquely named.
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import UniqueVariableNamesRule >>> schema = build_schema('type Query { field(arg: ID): String }') >>> document = parse('query ($id: ID, $id: ID) { field(arg: $id) }') >>> errors = validate(schema, document, [UniqueVariableNamesRule]) >>> print(errors[0].message) There can be only one variable named '$id'. >>> document = parse('query ($id: ID) { field(arg: $id) }') >>> validate(schema, document, [UniqueVariableNamesRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ASTValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Value Type Correctness”
- class graphql.validation.ValuesOfCorrectTypeRule(context: ValidationContext)
Bases:
ValidationRuleValue literals of correct type
A GraphQL document is only valid if all value literals are of the type expected at their position.
See https://spec.graphql.org/draft/#sec-Values-of-Correct-Type
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import ValuesOfCorrectTypeRule >>> schema = build_schema('type Query { count(limit: Int): Int }') >>> document = parse('{ count(limit: "many") }') >>> errors = validate(schema, document, [ValuesOfCorrectTypeRule]) >>> print(errors[0].message) Int cannot represent non-integer value: "many" >>> document = parse('{ count(limit: 1) }') >>> validate(schema, document, [ValuesOfCorrectTypeRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “Variables are Input Types”
- class graphql.validation.VariablesAreInputTypesRule(context: ValidationContext)
Bases:
ValidationRuleVariables are input types
A GraphQL operation is only valid if all the variables it defines are of input types (scalar, enum, or input object).
See https://spec.graphql.org/draft/#sec-Variables-Are-Input-Types
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import VariablesAreInputTypesRule >>> sdl = 'type Query { field(arg: ID): String } type User { name: String }' >>> schema = build_schema(sdl) >>> document = parse('query ($user: User) { field(arg: "1") }') >>> errors = validate(schema, document, [VariablesAreInputTypesRule]) >>> print(errors[0].message) Variable '$user' cannot be non-input type 'User'. >>> document = parse('query ($id: ID) { field(arg: $id) }') >>> validate(schema, document, [VariablesAreInputTypesRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Spec Section: “All Variable Usages Are Allowed”
- class graphql.validation.VariablesInAllowedPositionRule(context: ValidationContext)
Bases:
ValidationRuleVariables in allowed position
Variable usages must be compatible with the arguments they are passed to.
See https://spec.graphql.org/draft/#sec-All-Variable-Usages-are-Allowed
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import VariablesInAllowedPositionRule >>> schema = build_schema('type Query { field(arg: ID!): String }') >>> document = parse('query ($id: String) { field(arg: $id) }') >>> errors = validate(schema, document, [VariablesInAllowedPositionRule]) >>> print(errors[0].message) Variable '$id' of type 'String' used in position expecting type 'ID!'. >>> document = parse('query ($id: ID!) { field(arg: $id) }') >>> validate(schema, document, [VariablesInAllowedPositionRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
No spec section: “Maximum introspection depth”
- class graphql.validation.MaxIntrospectionDepthRule(context: ValidationContext)
Bases:
ASTValidationRuleChecks maximum introspection depth
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import MaxIntrospectionDepthRule >>> schema = build_schema('type Query { name: String }') >>> document = parse( ... '{ __schema { types { fields { type { fields {' ... ' type { fields { name } } } } } } } }' ... ) >>> errors = validate(schema, document, [MaxIntrospectionDepthRule]) >>> print(errors[0].message) Maximum introspection depth exceeded >>> document = parse('{ __schema { queryType { name } } }') >>> validate(schema, document, [MaxIntrospectionDepthRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ASTValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
SDL-specific validation rules
- class graphql.validation.LoneSchemaDefinitionRule(context: SDLValidationContext)
Bases:
SDLValidationRuleLone Schema definition
A GraphQL document is only valid if it contains only one schema definition.
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema >>> from graphql.validation import LoneSchemaDefinitionRule >>> from graphql.validation.specified_rules import specified_sdl_rules >>> LoneSchemaDefinitionRule in specified_sdl_rules True >>> sdl = ( ... 'schema { query: Query } schema { query: Query }' ... ' type Query { name: String }' ... ) >>> build_schema(sdl) Traceback (most recent call last): ... TypeError: Must provide only one schema definition. There can be only one query type in schema. >>> sdl = 'schema { query: Query } type Query { name: String }' >>> schema = build_schema(sdl)
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: SDLValidationContext
The validation context used while checking the SDL document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
- class graphql.validation.UniqueOperationTypesRule(context: SDLValidationContext)
Bases:
SDLValidationRuleUnique operation types
A GraphQL document is only valid if it has only one type per operation.
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema >>> from graphql.validation import UniqueOperationTypesRule >>> from graphql.validation.specified_rules import specified_sdl_rules >>> UniqueOperationTypesRule in specified_sdl_rules True >>> sdl = ( ... 'schema { query: Query query: Other } type Query { name: String }' ... ' type Other { name: String }' ... ) >>> build_schema(sdl) Traceback (most recent call last): ... TypeError: There can be only one query type in schema. >>> sdl = 'schema { query: Query } type Query { name: String }' >>> schema = build_schema(sdl)
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context
The validation context used while checking the SDL document.
- enter_leave_map
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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
- class graphql.validation.UniqueTypeNamesRule(context: SDLValidationContext)
Bases:
SDLValidationRuleUnique type names
A GraphQL document is only valid if all defined types have unique names.
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema >>> from graphql.validation import UniqueTypeNamesRule >>> from graphql.validation.specified_rules import specified_sdl_rules >>> UniqueTypeNamesRule in specified_sdl_rules True >>> sdl = 'type Query { name: String } type Query { other: String }' >>> build_schema(sdl) Traceback (most recent call last): ... TypeError: There can be only one type named 'Query'. >>> sdl = 'type Query { name: String } type Other { name: String }' >>> schema = build_schema(sdl)
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: SDLValidationContext
The validation context used while checking the SDL document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
- class graphql.validation.UniqueEnumValueNamesRule(context: SDLValidationContext)
Bases:
SDLValidationRuleUnique enum value names
A GraphQL enum type is only valid if all its values are uniquely named.
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema >>> from graphql.validation import UniqueEnumValueNamesRule >>> from graphql.validation.specified_rules import specified_sdl_rules >>> UniqueEnumValueNamesRule in specified_sdl_rules True >>> sdl = 'enum Status { ACTIVE ACTIVE } type Query { status: Status }' >>> build_schema(sdl) Traceback (most recent call last): ... TypeError: Enum value 'Status.ACTIVE' can only be defined once. >>> sdl = 'enum Status { ACTIVE INACTIVE } type Query { status: Status }' >>> schema = build_schema(sdl)
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: SDLValidationContext
The validation context used while checking the SDL document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
- class graphql.validation.UniqueFieldDefinitionNamesRule(context: SDLValidationContext)
Bases:
SDLValidationRuleUnique field definition names
A GraphQL complex type is only valid if all its fields are uniquely named.
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema >>> from graphql.validation import UniqueFieldDefinitionNamesRule >>> from graphql.validation.specified_rules import specified_sdl_rules >>> UniqueFieldDefinitionNamesRule in specified_sdl_rules True >>> sdl = 'type Query { name: String name: String }' >>> build_schema(sdl) Traceback (most recent call last): ... TypeError: Field 'Query.name' can only be defined once. >>> sdl = 'type Query { name: String other: String }' >>> schema = build_schema(sdl)
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: SDLValidationContext
The validation context used while checking the SDL document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
- class graphql.validation.UniqueArgumentDefinitionNamesRule(context: SDLValidationContext)
Bases:
SDLValidationRuleUnique argument definition names
A GraphQL Object or Interface type is only valid if all its fields have uniquely named arguments. A GraphQL Directive is only valid if all its arguments are uniquely named.
See https://spec.graphql.org/draft/#sec-Argument-Uniqueness
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema >>> from graphql.validation import UniqueArgumentDefinitionNamesRule >>> from graphql.validation.specified_rules import specified_sdl_rules >>> UniqueArgumentDefinitionNamesRule in specified_sdl_rules True >>> sdl = 'type Query { field(arg: String, arg: Int): String }' >>> build_schema(sdl) Traceback (most recent call last): ... TypeError: Argument 'Query.field(arg:)' can only be defined once. >>> sdl = 'type Query { field(arg: String): String }' >>> schema = build_schema(sdl)
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: SDLValidationContext
The validation context used while checking the SDL document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
- class graphql.validation.UniqueDirectiveNamesRule(context: SDLValidationContext)
Bases:
SDLValidationRuleUnique directive names
A GraphQL document is only valid if all defined directives have unique names.
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema >>> from graphql.validation import UniqueDirectiveNamesRule >>> from graphql.validation.specified_rules import specified_sdl_rules >>> UniqueDirectiveNamesRule in specified_sdl_rules True >>> sdl = ( ... 'directive @tag on FIELD directive @tag on QUERY' ... ' type Query { name: String }' ... ) >>> build_schema(sdl) Traceback (most recent call last): ... TypeError: There can be only one directive named '@tag'. >>> sdl = 'directive @tag on FIELD type Query { name: String }' >>> schema = build_schema(sdl)
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: SDLValidationContext
The validation context used while checking the SDL document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
- class graphql.validation.PossibleTypeExtensionsRule(context: SDLValidationContext)
Bases:
SDLValidationRulePossible type extension
A type extension is only valid if the type is defined and has the same kind.
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema >>> from graphql.validation import PossibleTypeExtensionsRule >>> from graphql.validation.specified_rules import specified_sdl_rules >>> PossibleTypeExtensionsRule in specified_sdl_rules True >>> sdl = 'extend type Missing { name: String } type Query { name: String }' >>> build_schema(sdl) Traceback (most recent call last): ... TypeError: Cannot extend type 'Missing' because it is not defined. >>> sdl = 'type Query { name: String } extend type Query { other: String }' >>> schema = build_schema(sdl)
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: SDLValidationContext
The validation context used while checking the SDL document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
Custom validation rules (not part of the specification)
- class graphql.validation.NoDeprecatedCustomRule(context: ValidationContext)
Bases:
ValidationRuleNo deprecated
A GraphQL document is only valid if all selected fields and all used enum values have not been deprecated.
Note: This rule is optional and is not part of the Validation section of the GraphQL Specification. The main purpose of this rule is detection of deprecated usages and not necessarily to forbid their use when querying a service.
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import ( ... GraphQLField, GraphQLObjectType, GraphQLSchema, GraphQLString, ... parse, validate) >>> from graphql.validation import NoDeprecatedCustomRule >>> schema = GraphQLSchema( ... query=GraphQLObjectType('Query', { ... 'name': GraphQLField(GraphQLString), ... 'oldName': GraphQLField( ... GraphQLString, deprecation_reason='Use name instead.'), ... })) >>> document = parse('{ oldName }') >>> errors = validate(schema, document, [NoDeprecatedCustomRule]) >>> print(errors[0].message) The field Query.oldName is deprecated. Use name instead. >>> document = parse('{ name }') >>> validate(schema, document, [NoDeprecatedCustomRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.
- class graphql.validation.NoSchemaIntrospectionCustomRule(context: ValidationContext)
Bases:
ValidationRuleProhibit introspection queries
A GraphQL document is only valid if all fields selected are not fields that return an introspection type.
Note: This rule is optional and is not part of the Validation section of the GraphQL Specification. This rule effectively disables introspection, which does not reflect best practices and should only be done if absolutely necessary.
- Parameters:
context – The validation context used while checking the document.
>>> from graphql import build_schema, parse, validate >>> from graphql.validation import NoSchemaIntrospectionCustomRule >>> schema = build_schema('type Query { name: String }') >>> document = parse('{ __schema { queryType { name } } }') >>> errors = validate(schema, document, [NoSchemaIntrospectionCustomRule]) >>> for error in errors: ... print(error.message) GraphQL introspection has been disabled, but the requested query contained the field '__schema'. GraphQL introspection has been disabled, but the requested query contained the field 'queryType'. >>> document = parse('{ name }') >>> validate(schema, document, [NoSchemaIntrospectionCustomRule]) []
- BREAK = True
- IDLE = None
- REMOVE = Ellipsis
- SKIP = False
- context: ValidationContext
The validation context used while checking the document.
- 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
- report_error(error: GraphQLError) None
Report a validation error to the validation context.
- Parameters:
error – The validation error to report.
>>> from graphql import GraphQLError, parse >>> from graphql.validation import ASTValidationContext, ASTValidationRule >>> context = ASTValidationContext(parse('{ greeting }'), print) >>> rule = ASTValidationRule(context) >>> rule.report_error(GraphQLError('Example validation error.')) Example validation error.