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 schemamutation_type (
Optional
[ObjectType
]) – The root mutation type for the schemasubscription_type (
Optional
[ObjectType
]) – The root subscription type for the schemadirectives (
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
: ifdefault
is not set and the type is not found
-
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]
, apy_gql.schema.ListType
instance will be returned, containing the type calledUser
found in the schema. If a type calledUser
is not found in the schema, thenUnknownType
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 ofabstract_type
.Returns:
True
iftype_
is valid forabstract_type
- Return type
-
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
-
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
-
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
-
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}
.allow_override (
bool
) – By default this function will raiseValueError
if the field already has a resolver defined. Set this toTrue
to allow overriding.
- Raises
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"
-
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.allow_override (
bool
) – By default this function will raiseValueError
if the field already has a resolver defined. Set this toTrue
to allow overriding.
- Raises
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.
-
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_ (
Union
[GraphQLType
,Callable
[[],GraphQLType
]]) – Wrapped typenode (
Optional
[NonNullType
]) – Source node used when building type from the SDL
-
type
# Wrapped type
- Type
-
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
# Wrapped type
- Type
-
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, thedefault_value
argument must be omitted.- Parameters
-
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
-
required
# Whether this argument is required (non nullable and does not have any default value)
- Type
-
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
orpy_gql.schema.InterfaceType
.- Parameters
name (
str
) – Field nametype_ (
Union
[GraphQLType
,Callable
[[],GraphQLType
]]) – Field type (must be output type)args (
Union
[Sequence
[Argument
],Callable
[[],Sequence
[Argument
]],None
]) – Field argumentsdeprecation_reason (
Optional
[str
]) – If set, the field will be marked as deprecated and the introspection layer will expose this to consumers.node (
Optional
[FieldDefinition
]) – Source node used when building type from the SDL
-
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
ifdeprecation_reason
is set.
-
type
# Field type.
- Type
-
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 (
str
) – Type namefields (
Union
[Sequence
[Field
],Callable
[[],Sequence
[Field
]]]) – Fieldsinterfaces (
Union
[Sequence
[InterfaceType
],Callable
[[],Sequence
[InterfaceType
]],None
]) – Implemented interfacesdefault_resolver (
Optional
[Callable
[[Any
,Any
,ForwardRef('ResolveInfo')
],Any
]]) –nodes (
Optional
[List
[Union
[ObjectTypeDefinition
,ObjectTypeExtension
]]]) – Source nodes used when building type from the SDL
-
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 (
str
) – Type namefields (
Union
[Sequence
[Field
],Callable
[[],Sequence
[Field
]]]) – Fieldsresolve_type (
Optional
[Callable
[[Any
,Any
,ForwardRef('ResolveInfo')
],ForwardRef('Union
]]) – Type resolvernodes (
Optional
[List
[Union
[InterfaceTypeDefinition
,InterfaceTypeExtension
]]]) – Source nodes used when building type from the SDL
-
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 (
str
) – Type nametypes (
Union
[Sequence
[ObjectType
],Callable
[[],Sequence
[ObjectType
]]]) – Member typesresolve_type (
Optional
[Callable
[[Any
,Any
,ForwardRef('ResolveInfo')
],ForwardRef('Union
]]) – Type resolvernodes (
Optional
[List
[Union
[UnionTypeDefinition
,UnionTypeExtension
]]]) – Source nodes used when building type from the SDL
-
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, thedefault_value
argument must be omitted.- Parameters
-
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
-
required
# Whether this field is required (non nullable and does not have any default value)
- Type
-
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
-
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 valuevalue (
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.node (
Optional
[EnumValueDefinition
]) – Source node used when building type from the SDL
-
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
ifdeprecation_reason
is set.
-
node
# Source node used when building type from the SDL
- Type
Optional[py_gql.lang.ast.EnumValueDefinition]
-
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
-
values
# Values by name
- Type
Dict[str, py_gql.schema.EnumValue]
-
reverse_values
# (Dict[H, EnumValue]): Values by value
-
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
: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
: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()
andparse_literal()
(this is how RegexType is implemented).- Parameters
name (
str
) – Type nameserialize (
Callable
[[Any
],Union
[str
,int
,float
,bool
,None
]]) –Type serializer.
This function will receive a Python value and must output JSON serialisable scalars.
Raise
ScalarSerializationError
,ValueError
orTypeError
to signify that the value cannot be serialized.parse (
Callable
[[Any
],Any
]) –Type de-serializer.
This function will receive JSON scalars and can outputs any Python value.
Raise
ScalarParsingError
,ValueError
orTypeError
to signify that the value cannot be parsed.parse_literal (
Optional
[Callable
[[Union
[IntValue
,FloatValue
,StringValue
,BooleanValue
],Mapping
[str
,Any
]],Any
]]) –Type de-serializer for value nodes.
This function receives a
py_gql.lang.ast.Value
and can outputs any Python value.Raise
ScalarParsingError
,ValueError
orTypeError
to signify that the value cannot be parsed.If not provided, the execution layer will extract the node’s value as a string and pass it to parse.
nodes (
Optional
[List
[Union
[ScalarTypeDefinition
,ScalarTypeExtension
]]]) – Source nodes used when building type from the SDL
-
nodes
# Source nodes used when building type from the SDL
- Type
List[Union[ py_gql.lang.ast.ScalarTypeDefinition, py_gql.lang.ast.ScalarTypeExtension ]]
-
parse
(value)[source]# Transform a GraphQL value in a valid Python value
- Parameters
value (
Any
) – JSON scalar- Return type
- Returns
Python level value
- Raises
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
orfalse
.
-
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.
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
-
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. returningNone
fromon_field()
will result in the field being dropped from the parentpy_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_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
]
-