py_gql.schema#

The py_gql.schema module exposes all the necessary classes and functions for programatically creating, validating and inspecting GraphQL schemas against which you can execute queries.

The schema class#

class py_gql.schema.Schema(query_type=None, mutation_type=None, subscription_type=None, directives=None, types=None, nodes=None)[source]#

A GraphQL schema definition.

A GraphQL schema definition. This is the main container for a GraphQL schema and its related types.

Parameters
  • query_type (Optional[ObjectType]) – The root query type for the schema

  • mutation_type (Optional[ObjectType]) – The root mutation type for the schema

  • subscription_type (Optional[ObjectType]) – The root subscription type for the schema

  • directives (Optional[List[Directive]]) – List of possible directives to use. The default, specified directives (@include, @skip) will always be included.

  • types (Optional[List[NamedType]]) – List of additional supported types. This only necessary for types that cannot be inferred by traversing the root types.

  • nodes (Optional[List[Union[SchemaDefinition, SchemaExtension]]]) – AST node for the schema if applicable, i.e. when creating the schema from a GraphQL (SDL) document.

query_type#

The root query type for the schema (required).

Type

Optional[ObjectType]

mutation_type#

The root mutation type for the schema (optional).

Type

Optional[ObjectType]

subscription_type#

The root subscription type for the schema (optional).

Type

Optional[ObjectType]

nodes#

AST node for the schema if applicable, i.e. when creating the schema from a GraphQL (SDL) document.

Type

List[Union[_ast.SchemaDefinition, _ast.SchemaExtension]]

types#

Mapping type name -> Type instance of all types used in the schema, excluding directives.

Type

Dict[str, GraphQLType]

directives#

Mapping directive name -> Directive instance of all directives used in the schema.

Type

Dict[str, py_gql.schema.Directive]

implementations#

Mapping of interface name -> [implementing object types].

Type

Dict[str, ObjectType]

validate()[source]#

Check that the schema is valid.

:raises SchemaError if the schema is invalid.:

get_type(name)[source]#

Get a type by name.

Parameters

name (str) – Requested type name

Returns

Type instance

Return type

py_gql.schema.Type

:raises UnknownType: if default is not set and the type is not found

has_type(name)[source]#

Check if the schema contains a type with the given name.

Return type

bool

get_type_from_literal(ast_node)[source]#

Given an AST node describing a type, return a corresponding py_gql.schema.Type instance.

For example, if provided the parsed AST node for [User], a py_gql.schema.ListType instance will be returned, containing the type called User found in the schema. If a type called User is not found in the schema, then UnknownType will be raised.

:raises UnknownType: if any named type is not found

Return type

GraphQLType

get_possible_types(abstract_type)[source]#

Get the possible implementations of an abstract type.

Parameters

type_ – Abstract type to check.

Returns: List of possible implementations.

Return type

Sequence[ObjectType]

is_possible_type(abstract_type, type_)[source]#

Check that type_ is a possible realization of abstract_type.

Returns: True if type_ is valid for abstract_type

Return type

bool

is_subtype(type_, super_type)[source]#

Provided a type and a super type, return true if the first type is either equal or a subset of the second super type (covariant).

Parameters
  • type_ (py_gql.schema.Type) –

  • super_type (py_gql.schema.Type) –

Returns

Return type

bool

types_overlap(rhs, lhs)[source]#

Provided two composite types, determine if they “overlap”. Two composite types overlap when the Sets of possible concrete types for each intersect.

This is often used to determine if a fragment of a given type could possibly be visited in a context of another type. This function is commutative.

Return type

bool

to_string(indent=4, include_descriptions=True, include_introspection=False, use_legacy_comment_descriptions=False, include_custom_directives=False)[source]#

Format the schema as an SDL string.

Refer to py_gql.utilities.ASTSchemaPrinter for details.

Return type

str

assign_resolver(fieldpath, func, allow_override=False)[source]#

Register a resolver against a type in the schema.

Parameters
  • fieldpath (str) – Field path in the form {Typename}.{Fieldname}.

  • func (Callable[…, Any]) – The resolver function.

  • allow_override (bool) – By default this function will raise ValueError if the field already has a resolver defined. Set this to True to allow overriding.

Raises

ValueError

Warning

This will update the type inline and as such is expected to be used after having used py_gql.build_schema.

Return type

Schema

resolver(fieldpath)[source]#

Decorator version of assign_resolver().

schema = ...

@schema.resolver("Query.foo")
def resolve_foo(obj, ctx, info):
    return "foo"
Parameters

fieldpath (str) – Field path in the form {Typename}.{Fieldname}.

Return type

Callable[[Callable[…, Any]], Callable[…, Any]]

assign_subscription_resolver(fieldname, func, allow_override=False)[source]#

Register a subscription resolver against a field of the schema’s subscription type.

Parameters
  • fieldname (str) – Field name.

  • func (Callable[…, Any]) – The resolver function.

  • allow_override (bool) – By default this function will raise ValueError if the field already has a resolver defined. Set this to True to allow overriding.

Raises

ValueError

Warning

This will update the type inline and as such is expected to be used after having used py_gql.build_schema.

Return type

None

subscription(fieldname)[source]#

Decorator version of assign_subscription_resolver().

Parameters

fieldname – Field name.

Defining Types#

Types are defined as instances of GraphQLType and its subclasses.

class py_gql.schema.GraphQLType[source]#

Base type class.

All types used in a py_gql.schema.Schema should be instances of this class.

class py_gql.schema.NamedType[source]#

Named type base class.

Warning

Named types must be unique across a single Schema instance.

name#

Type name.

Type

str

class py_gql.schema.NonNullType(type_, node=None)[source]#

Non nullable wrapping type.

A non-null type is a wrapping type which points to another type.

Non-null types enforce that their values are never null and can ensure an error is raised if this ever occurs during a request. It is useful for fields which you can make a strong guarantee on non-nullability, for example usually the id field of a database row will never be null.

Parameters
type#

Wrapped type

Type

GraphQLType

node#

Source node used when building type from the SDL

Type

Optional[py_gql.lang.ast.NonNullType]

class py_gql.schema.ListType(type_, node=None)[source]#

List wrapping type.

A list type is a wrapping type which points to another type.

Lists are often created within the context of defining the fields of an object type.

Parameters
  • type_ (Union[GraphQLType, Callable[[], GraphQLType]]) – Wrapped type

  • node (Optional[ListType]) – Source node used when building type from the SDL

type#

Wrapped type

Type

GraphQLType

node#

Source node used when building type from the SDL

Type

Optional[py_gql.lang.ast.ListType]

class py_gql.schema.Argument(name, type_, default_value=<object object>, description=None, node=None)[source]#

Argument definition for use in field or directives.

Warning

As None is a valid default value, in order to define an argument without any default value, the default_value argument must be omitted.

Parameters
  • name (str) – Argument name

  • type_ (Union[GraphQLType, Callable[[], GraphQLType]]) – Argument type (must be input type)

  • default_value (Any) – Default value

  • description (Optional[str]) – Argument description

  • node (Optional[InputValueDefinition]) – Source node used when building type from the SDL

name#

Argument name

Type

str

description#

Argument description

Type

Optional[str]

has_default_value#

True if default value is set

Type

bool

default_value#

Default value if it was set. Accessing this attribute raises an AttributeError if default value wasn’t set.

Type

Any

type#

Vaue type.

Type

GraphQLType

required#

Whether this argument is required (non nullable and does not have any default value)

Type

bool

node#

Source node used when building type from the SDL

Type

Optional[py_gql.lang.ast.InputValueDefinition]

class py_gql.schema.Field(name, type_, args=None, description=None, deprecation_reason=None, resolver=None, subscription_resolver=None, node=None)[source]#

Member of an py_gql.schema.ObjectType or py_gql.schema.InterfaceType.

Parameters
  • name (str) – Field name

  • type_ (Union[GraphQLType, Callable[[], GraphQLType]]) – Field type (must be output type)

  • args (Union[Sequence[Argument], Callable[[], Sequence[Argument]], None]) – Field arguments

  • description (Optional[str]) – Field description

  • deprecation_reason (Optional[str]) – If set, the field will be marked as deprecated and the introspection layer will expose this to consumers.

  • resolver (Optional[Callable[…, Any]]) – Resolver function.

  • node (Optional[FieldDefinition]) – Source node used when building type from the SDL

name#

Field name

Type

str

description#

Field description

Type

Optional[str]

deprecation_reason#

If set, the field will be marked as deprecated and the introspection layer will expose this to consumers.

Type

Optional[str]

deprecated#

True if deprecation_reason is set.

type#

Field type.

Type

GraphQLType

arguments#

Field arguments.

Type

List[py_gql.schema.Argument]

argument_map#

Field arguments in indexed form.

Type

Dict[str, py_gql.schema.Argument]

resolver#

Field resolver.

Type

callable

subscription_resolver#

Field resolver for subscriptions.

Type

callable

node#

Source node used when building type from the SDL

Type

Optional[py_gql.lang.ast.FieldDefinition]

class py_gql.schema.ObjectType(name, fields, interfaces=None, default_resolver=None, description=None, nodes=None)[source]#

Object Type Definition

Almost all of the GraphQL types you define will be object types. Object types have a name, but most importantly describe their fields.

Parameters
name#

Type name

Type

str

description#

Type description

Type

Optional[str]

interfaces#

Implemented interfaces.

Type

Sequence[InterfaceType]

fields#

Object fields.

Type

Sequence[py_gql.schema.Field]

field_map#

Object fields as a map.

Type

Dict[str, py_gql.schema.Field]

default_resolver#
Type

Optional[Callable[.., Any]]

nodes#

Source nodes used when building type from the SDL

Type

List[Union[ py_gql.lang.ast.ObjectTypeDefinition, py_gql.lang.ast.ObjectTypeExtension, ]]

class py_gql.schema.InterfaceType(name, fields, resolve_type=None, description=None, nodes=None)[source]#

Interface Type Definition.

When a field can return one of a heterogeneous set of types, a Interface type is used to describe what types are possible, what fields are in common across all types, as well as a function to determine which type is actually used when the field is resolved.

Parameters
name#

Type name

Type

str

description#

Type description

Type

Optional[str]

fields#

Object fields.

Type

Sequence[py_gql.schema.Field]

field_map#

Object fields as a map.

Type

Dict[str, py_gql.schema.Field]

resolve_type#

Type resolver

Type

Optional[callable]

nodes#

Source nodes used when building type from the SDL

Type

List[Union[ py_gql.lang.ast.InterfaceTypeDefinition, py_gql.lang.ast.InterfaceTypeExtension, ]]

class py_gql.schema.UnionType(name, types, resolve_type=None, description=None, nodes=None)[source]#

Union Type Definition

When a field can return one of a heterogeneous set of types, a Union type is used to describe what types are possible as well as providing a function to determine which type is actually used when the field is resolved.

Parameters
name#

Type name

Type

str

description#

Type description

Type

Optional[str]

resolve_type#

Type resolver

Type

Optional[callable]

types#

Member types.

Type

Sequence[ObjectType]

nodes#

Source nodes used when building type from the SDL

Type

List[Union[ py_gql.lang.ast.UnionTypeDefinition, py_gql.lang.ast.UnionTypeExtension, ]]

class py_gql.schema.InputField(name, type_, default_value=<object object>, description=None, node=None)[source]#

Member of an py_gql.schema.InputObjectType.

Warning

As None is a valid default value, in order to define an argument without any default value, the default_value argument must be omitted.

Parameters
  • name (str) – Field name

  • type_ (Union[GraphQLType, Callable[[], GraphQLType]]) – Field type (must be input type)

  • default_value (Any) – Default value

  • description (Optional[str]) – Field description

  • node (Optional[InputValueDefinition]) – Source node used when building type from the SDL

name#

Field name

Type

str

description#

Field description

Type

Optional[str]

has_default_value#

True if default value is set

Type

bool

default_value#

Default value if it was set. Accessing this attribute raises an AttributeError if default value wasn’t set.

Type

Any

type#

Vaue type.

Type

GraphQLType

required#

Whether this field is required (non nullable and does not have any default value)

Type

bool

node#

Source node used when building type from the SDL

Type

Optional[py_gql.lang.ast.InputValueDefinition]

class py_gql.schema.InputObjectType(name, fields, description=None, nodes=None)[source]#

Input Object Type Definition

An input object defines a structured collection of fields which can be supplied as a field or directive argument.

Parameters
name#

Type name

Type

str

description#

Type description

Type

Optional[str]

nodes#

Source nodes used when building type from the SDL

Type

List[ Union[ py_gql.lanf.ast.InputObjectTypeDefinition, py_gql.lanf.ast.InputObjectTypeExtension, ] ]

fields#

Object fields.

Type

Sequence[InputField]

field_map#

Object fields as a map.

Type

Dict[str, InputField]

class py_gql.schema.EnumValue(name, value=<object object>, deprecation_reason=None, description=None, node=None)[source]#

Enum value definition.

Parameters
  • name (str) – Name of the value

  • value (Any) –

    Python value. Defaults to name if omitted.

    Warning

    Must be hashable to support reverse lookups when coercing python values into enum values

  • deprecation_reason (Optional[str]) – If set, the value will be marked as deprecated and the introspection layer will expose this to consumers.

  • description (Optional[str]) – Enum value description

  • node (Optional[EnumValueDefinition]) – Source node used when building type from the SDL

name#

Enum value name

Type

str

value#

Enum value value

Type

str

description#

Enum value description

Type

Optional[str]

deprecation_reason#

If set, the value will be marked as deprecated and the introspection layer will expose this to consumers.

Type

Optional[str]

deprecated#

True if deprecation_reason is set.

node#

Source node used when building type from the SDL

Type

Optional[py_gql.lang.ast.EnumValueDefinition]

classmethod from_def(definition)[source]#

Create an enum value from various source objects.

This supports existing EnumValue instances, strings, (name, value) tuples and dictionnaries matching the signature of EnumValue.__init__.

Return type

~_EV

class py_gql.schema.EnumType(name, values, description=None, nodes=None)[source]#

Enum Type Definition

Some leaf values of requests and input values are Enums. GraphQL serializes Enum values as strings, however internally Enums can be represented by any kind of Python type.

Parameters
name#

Enum name

Type

str

values#

Values by name

Type

Dict[str, py_gql.schema.EnumValue]

reverse_values#

(Dict[H, EnumValue]): Values by value

description#

Enum description

Type

Optional[str]

nodes#

Source nodes used when building type from the SDL

Type

List[Union[ py_gql.lang.ast.EnumTypeDefinition, py_gql.lang.ast.EnumTypeExtension, ]]

classmethod from_python_enum(enum, description=None, nodes=None)[source]#

Create a GraphQL Enum type from a Python enum

get_value(name)[source]#

Extract the value for a given name.

Parameters

name (str) – Name of the value to extract

Returns

The corresponding EnumValue

Return type

py_gql.schema.EnumValue

:raises UnknownEnumValue when the name is unknown:

get_name(value)[source]#

Extract the name for a given value.

Parameters

value (Any) – Value of the value to extract, must be hashable

Returns

The corresponding EnumValue

Return type

py_gql.schema.EnumValue

:raises UnknownEnumValue when the value is unknown:

Scalar Types#

class py_gql.schema.ScalarType(name, serialize, parse, parse_literal=None, description=None, nodes=None)[source]#

Scalar Type Definition

The leaf values of any request and input values to arguments are Scalars (or Enums) and are defined with a name and a series of functions used to parse input from ast or variables and to ensure validity.

To define custom scalars, you can either instantiate this class with the corresponding arguments (that is how Int, Float, etc. are implemented) or subclass this class and implement serialize(), parse() and parse_literal() (this is how RegexType is implemented).

Parameters
name#

Type name

Type

str

description#

Type description

Type

Optional[str]

nodes#

Source nodes used when building type from the SDL

Type

List[Union[ py_gql.lang.ast.ScalarTypeDefinition, py_gql.lang.ast.ScalarTypeExtension ]]

serialize(value)[source]#

Transform a Python value in a JSON serializable one.

Parameters

value (Any) – Python level value

Return type

Union[str, int, float, bool, None]

Returns

JSON scalar

Raises

ScalarParsingError

parse(value)[source]#

Transform a GraphQL value in a valid Python value

Parameters

value (Any) – JSON scalar

Return type

Any

Returns

Python level value

Raises

ScalarParsingError

parse_literal(node, variables=None)[source]#

Transform an AST node in a valid Python value

Parameters

value – Parse node

Return type

Any

Returns

Python level value

Raises

ScalarParsingError

Specified scalar types#

The following types are part of the specification and should always be available in any compliant GraphQL server (although they may not be used).

schema.Boolean#

The Boolean scalar type represents true or false.

schema.Int#

The Int scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.

schema.Float#

The Float scalar type represents signed double-precision fractional values as specified by IEEE 754.

schema.String#

The String scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.

schema.ID#

The ID scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as “4”) or integer (such as 4) input value will be accepted as an ID.

schema.SPECIFIED_SCALAR_TYPES#

Tuple of all specified scalar types.

Extra scalar types#

The following types and classes are provided for convenience as they are quite common. They will not always be present in GraphQL servers and need to be included manually when using py_gql.build_schema.

schema.UUID#

The UUID scalar type represents a UUID as specified in RFC 4122.

class py_gql.schema.RegexType(name, regex, description=None)[source]#

Scalar typeclass to validate regex patterns.

Parameters
  • name – Type name

  • regex – Regular expression

  • description – Type description

name#

Type name

Type

str

description#

Type description

Type

str

Directives#

class py_gql.schema.Directive(name, locations, args=None, description=None, node=None)[source]#

Directive definition

Directives are used by the GraphQL runtime as a way of modifying execution behavior. Type system creators will usually not create these directly.

Parameters
name#

Directive name

Type

str

description#

Directive description

Type

Optional[str]

locations#

Possible locations for that directive

Type

List[str]

arguments#

Directive arguments.

Type

List[py_gql.schema.Argument]

argument_map#

Directive arguments in indexed form.

Type

Dict[str, py_gql.schema.Argument]

node#

Source node used when building type from the SDL

Type

Optional[py_gql.lang.ast.DirectiveDefinition]

The following py_gql.schema.Directive instances are part of the specification and should always be available in any compliant GraphQL server.

schema.IncludeDirective#

Directs the server to include this field or fragment only when the if argument is true.

directive @include(if: Boolean!)
on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT
schema.SkipDirective#
directive @skip(if: Boolean!)
on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT

Directs the server to skip this field or fragment when the if argument is true.

schema.DeprecatedDirective#
directive @deprecated(
    reason: String = "No longer supported"
) on FIELD_DEFINITION | ENUM_VALUE

Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted in Markdown.

schema.SPECIFIED_DIRECTIVES#

Tuple of all specified directives.

Schema Visitor#

class py_gql.schema.SchemaVisitor[source]#

Base class encoding schema traversal and modifications.

Subclass and override the on_* methods to implement custom behaviour.

All methods must return the modified value; returning None will drop the respective values from their context, e.g. returning None from on_field() will result in the field being dropped from the parent py_gql.schema.ObjectType. However, types and directives are never from the schema, even if not in use anymore.

For most uses cases, do not forget to call the method from the parent class as it ususally encodes how child elements such as field, enum values, etc. are processed.

on_schema(schema)[source]#

Process the whole schema. You should not override this in most cases.

Parameters

schema (Schema) – Original schema.

Return type

Schema

on_scalar(scalar_type)[source]#
Parameters

scalar – Original type.

Return type

Optional[ScalarType]

on_object(object_type)[source]#
Parameters

object_type (ObjectType) – Original type.

Return type

Optional[ObjectType]

on_field_definition(field)[source]#
Parameters

field (Field) – Original object field.

Return type

Optional[Field]

on_argument_definition(argument)[source]#
Parameters

field – Original argument.

Return type

Optional[Argument]

on_interface(interface_type)[source]#
Parameters

interface_type (InterfaceType) – Original type.

Return type

Optional[InterfaceType]

on_union(union_type)[source]#
Parameters

union_type (UnionType) – Original type.

Return type

Optional[UnionType]

on_enum(enum_type)[source]#
Parameters

enum_type (EnumType) – Original type.

Return type

Optional[EnumType]

on_enum_value(enum_value)[source]#
Parameters

enum_value (EnumValue) – Original enum value.

Return type

Optional[EnumValue]

on_input_object(input_object_type)[source]#
Parameters

input_object_type (InputObjectType) – Original type.

Return type

Optional[InputObjectType]

on_input_field_definition(field)[source]#
Parameters

field (InputField) – Original input object field.

Return type

Optional[InputField]

on_directive(directive)[source]#

Note

This does not correspond to a directive location but is necessary to completely cover schema traversal.

Parameters

directive (Directive) – Original directive

Return type

Directive