py_gql.utilities#

Mixed bag of exposed utility functions and classes.

These are used internally and can be useful if you are building custom GraphQL tooling on top of this library.

py_gql.utilities.ast_node_from_value(value, input_type)[source]#

Infer an input value ast Node from a Python value given an input type.

Parameters:
  • value (Any) – Any python value that can be transformed into a node
  • input_type (GraphQLType) – Input type used to disambiguate between node types.
Return type:

Value

Returns:

Inferred value node

Raises:
  • ValueError – When coercion into a node fails
  • TypeError – When input_type is not an input type
py_gql.utilities.coerce_argument_values(definition, node, variables=None)[source]#

Prepare a dict of argument values given a definition and a node.

Warning

Missing arguments (according to the definition) will not be present in the resulting dictionary unless they have a default value.

Parameters:
  • definition (Union[Field, Directive]) – Field or Directive definition from which to extract argument definitions.
  • node (Union[Field, Directive]) – Parse node
  • variables (Optional[Mapping[str, Any]]) – Coerced variable values
Return type:

Dict[str, Any]

Returns:

Coerced arguments

Raises:

CoercionError – If any argument fails to coerce, is missing, etc.

py_gql.utilities.coerce_value(value, type_, node=None, path=None)[source]#

Coerce a Python value given a GraphQL Type.

Parameters:
  • value (Any) – Value to coerce
  • type – Expected type
  • node (Optional[Node]) – Relevant node
  • path (Optional[List[Union[int, str]]]) – Path into the value for nested values (lists, objects). Should only be set on recursive calls.
Return type:

Any

Returns:

The coerced value

Raises:

CoercionError – if coercion fails

py_gql.utilities.coerce_variable_values(schema, operation, variables)[source]#

Validate and extract variables from arbitrary JSON objects.

Prepare an object map of variable values of the correct type based on the provided operation definition and arbitrary JSON input. If the input cannot be parsed to match the variable definitions, an ExecutionError will be thrown. The returned value is a plain dict since it is exposed to user code.

Extra variables are ignored and filtered out.

Parameters:
  • schema (Schema) – GraphQL Schema to consider
  • operation (OperationDefinition) – Operation definition containing the variable definitions
  • variables (Mapping[str, Any]) – Provided raw variables
Return type:

Dict[str, Any]

Returns:

Coerced variables

Raises:

VariablesCoercionError – If any variable cannot be coerced.

py_gql.utilities.selected_fields(field, *, fragments, variables, maxdepth=1, pattern=None, _path=None)[source]#

Extract a list of field paths from an object field and provided fragments.

If maxdepth is 0 or higher than 1, subfields will be traversed recursively and exposed as a / separated path. For example, considering the root field of the following document:

query {
    field {
        foo {
            bar {
                baz
            }
        }
    }
}

Calling selected_fields(..., maxdepth=0) will yield ['foo', 'foo/bar', 'foo/bar/baz'].

Parameters:
  • field (Field) – Root field
  • fragments (Mapping[str, FragmentDefinition]) – Document fragments
  • variables (Mapping[str, Any]) – Operation variables
  • maxdepth (Optional[int]) – Control how deep the traversal should go. If set to 0, then traversal will proceed as deep as possible.
  • pattern (Union[str, Pattern, None]) – Filter string used to control which fields are returned. If this is passed as a string, it will be compiled into a regex through the fnmatch module.
  • _path (Optional[List[str]]) – Already traversed path, used for recursive calls.
Return type:

List[str]

Returns:

List of selected field paths.

py_gql.utilities.directive_arguments(definition, node, variables=None)[source]#

Extract first directive arguments given node and a directive definition.

Warning

This extracts at most a single set of arguments which may not be suitable for repeatable directives. In that case py_gql.utilities. all_directive_arguments. should be preferred.

Parameters:
Return type:

Optional[Dict[str, Any]]

Returns:

Coerced directive arguments, None if the directive is not present on the node.

Raises:

CoercionError – If any argument fails to coerce, is missing, etc.

py_gql.utilities.all_directive_arguments(definition, node, variables=None)[source]#

Extract all directive arguments given node and a directive definition.

Parameters:
Return type:

List[Dict[str, Any]]

Returns:

List of coerced directive arguments for all occurrences of the directive. If the directive is not present the list is empty, otherwise this returns one or more (for repeatable directives) dictionnaries of arguments in the order they appear on the node.

Raises:

CoercionError – If any argument fails to coerce, is missing, etc.

py_gql.utilities.introspection_query(description=True)[source]#

Return a generic introspection query to be used by GraphQL clients.

Parameters:description (bool) – If True the query will require descriptions.
Return type:str
Returns:Canonical introspection query
py_gql.utilities.untyped_value_from_ast(node, variables=None)[source]#

Convert an ast value node into a valid python value without type validation.

Warning

No validation is done with regard to the variable values which are assumed to have been validated before.

Parameters:
Return type:

Any

Returns:

Extracted value

Raises:
  • TypeError – when node is not a value node
  • UnknownVariable – if a variable is required and doesn’t exist
py_gql.utilities.value_from_ast(node, type_, variables=None)[source]#

Convert an ast Value node into a valid python value given a schema type.

Warning

No validation is done with regard to the variable values which are assumed to have been validated before.

Parameters:
Return type:

Any

Returns:

Extracted value

Raises:
  • TypeError – when node is not a value node
  • InvalidValue – if the value cannot be converted
  • UnknownVariable – if a variable is required and doesn’t exist
class py_gql.utilities.MaxDepthValidationRule(max_depth, *, operation_name=None)[source]#

Bases: object

Validate that a given document doesn’t exceed a given query depth.

Query depth is calculated as nesting levels into object types, traversing fragments. For example, given the following document:

{
    hero {
        name
        friends {
            ... friendsData
        }
    }
}

fragment friendsData on Character {
    friends {
        name
        friends {
            name
        }
    }
}

the depth of the query would be 4.

Parameters:
  • max_depth (int) – Depth limit (inclusive).
  • operation_name (Optional[str]) – If set this will only consider the operation matching the provided name, if not this will collect errors for all operation definitions.