py_gql.schema#
The py_gql.schema
module exposes all the necessary classes and
functions for programmatically 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, description=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. - description (
Optional
[str
]) – Schema description. - 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]
-
get_possible_types
(abstract_type)[source]# Get the possible implementations of an abstract type.
Parameters: abstract_type ( GraphQLAbstractType
) – Abstract type to check.Raises: TypeError
– when the input type is not an abstract type.Return type: Sequence
[ObjectType
]Returns: List of possible types.
-
get_type
(name)[source]# Get a type by name.
Parameters: name ( str
) – Requested type nameReturns: Type instance Return type: py_gql.schema.NamedType Raises: UnknownType
– ifdefault
is not set and the type is not found.
-
get_type_from_literal
(ast_node)[source]# Return a
py_gql.schema.Type
instance for an AST type node.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 foundReturn type: GraphQLType
-
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: bool
-
is_subtype
(type_, super_type)[source]# Check if a type is either equal or a subset of a super type (covariant).
Parameters: - type (py_gql.schema.Type) – Target type.
- super_type (py_gql.schema.Type) – Super type.
Returns: Return type:
-
register_default_resolver
(typename, resolver, *, allow_override=False)[source]# Register a callable as a default resolver for a given type.
Parameters: Raises: ValueError
– If the resolver has already been defined andallow_override
wasFalse
.Return type: None
-
register_resolver
(typename, fieldname, resolver, *, allow_override=False)[source]# Register a function as a resolver.
Parameters: Raises: ValueError
– If the resolver has already been defined andallow_override
wasFalse
.Return type: None
-
register_subscription
(typename, fieldname, resolver, *, allow_override=False)[source]# Register a function as a subscription resolver.
Parameters: Raises: ValueError
– If the resolver has already been defined andallow_override
wasFalse
.Return type: None
-
register_type_resolver
(typename, resolver, *, allow_override=False)[source]# Register a function as a type resolver.
Parameters: Raises: ValueError
– If the resolver has already been defined andallow_override
wasFalse
.Return type: None
-
to_string
(indent=4, include_descriptions=True, include_introspection=False, include_custom_schema_directives=False)[source]# Format the schema as an SDL string.
Return type: str
-
types_overlap
(rhs, lhs)[source]# Determine if two composite types “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
-
validate
()[source]# Check that the schema is valid.
Raises: SchemaError
if the schema is invalid.
- query_type (
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 – Wrapped type
- node (
Optional
[NonNullType
]) – 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.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: 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, python_name=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
# Value 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, python_name=None)[source]# Member of a composite type.
Parameters: - name (
str
) – Field name - type – 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
-
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: 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]
- name (
-
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 name - fields (
Union
[Sequence
[Field
],Callable
[[],Sequence
[Field
]]]) – Fields - interfaces (
Union
[Sequence
[InterfaceType
],Callable
[[],Sequence
[InterfaceType
]],None
]) – Implemented interfaces - default_resolver (
Optional
[Callable
[…,Any
]]) – - description (
Optional
[str
]) – Type description - 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, ]]
- name (
-
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 name - fields (
Union
[Sequence
[Field
],Callable
[[],Sequence
[Field
]]]) – Fields - resolve_type (
Optional
[Callable
[[Any
,Any
,ForwardRef
],Union
[ForwardRef
,str
,None
]]]) – Type resolver - description (
Optional
[str
]) – Type description - nodes (
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, ]]
- name (
-
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 name - types (
Union
[Sequence
[ObjectType
],Callable
[[],Sequence
[ObjectType
]]]) – Member types - resolve_type (
Optional
[Callable
[[Any
,Any
,ForwardRef
],Union
[ForwardRef
,str
,None
]]]) – Type resolver - description (
Optional
[str
]) – Type description - nodes (
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, ]]
- name (
-
class
py_gql.schema.
InputField
(name, type_, default_value=<object object>, description=None, node=None, python_name=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
# Value 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: -
nodes
# Source nodes used when building type from the SDL
Type: List[ Union[ py_gql.lang.ast.InputObjectTypeDefinition, py_gql.lang.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
-
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]
- name (
-
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 (
str
) – Enum name - values (
Iterable
[Union
[EnumValue
,str
,Tuple
[str
,Any
]]]) – List of enum value definition supported by EnumValue.from_def - description (
Optional
[str
]) – Enum description - nodes (
Optional
[List
[Union
[EnumTypeDefinition
,EnumTypeExtension
]]]) – Source nodes used when building type from the SDL
-
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_name
(value)[source]# Extract the name for a given value.
Parameters: value ( Any
) – Value of the value to extract, must be hashableReturns: The corresponding EnumValue Return type: py_gql.schema.EnumValue
Raises: UnknownEnumValue
– when the value is unknown
-
get_value
(name)[source]# Extract the value for a given name.
Parameters: name ( str
) – Name of the value to extractReturns: The corresponding EnumValue. Return type: py_gql.schema.EnumValue
Raises: UnknownEnumValue
– when the name is unknown.
- name (
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 name - serialize (
Callable
[[Any
],Union
[str
,int
,float
,bool
,None
]]) –Type serializer.
This function will receive a Python value and must output JSON serializable scalars.
Raise
ScalarSerializationError
,ValueError
orTypeError
to signify that the value cannot be serialized. - parse (
Callable
[[Union
[str
,int
,float
,bool
,None
]],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.
- description (
Optional
[str
]) – Type description - 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 ( Union
[str
,int
,float
,bool
,None
]) – JSON scalarReturn type: Any
Returns: Python level value Raises: ScalarParsingError
– when the type’s parser fail with ValueError or TypeError (other exceptions bubble up).
-
parse_literal
(node, variables=None)[source]# Transform an AST node in a valid Python value
Parameters: - node (
Union
[IntValue
,FloatValue
,StringValue
,BooleanValue
]) – Parse node - variables (
Optional
[Mapping
[str
,Any
]]) – Raw, JSON decoded variables parsed from the request
Return type: Returns: Python level value
Raises: ScalarParsingError
– when the type’s parser fail with ValueError or TypeError (other exceptions bubble up).- node (
-
serialize
(value)[source]# Transform a Python value in a JSON serializable one.
Parameters: value ( Any
) – Python level valueReturn type: Union
[str
,int
,float
,bool
,None
]Returns: JSON scalar Raises: ScalarSerializationError
– when the type’s serializer fail with ValueError or TypeError (other exceptions bubble up).
- name (
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#
See py_gql.exts.scalars
.
Directives#
-
class
py_gql.schema.
Directive
(name, locations, args=None, repeatable=False, 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 (
str
) – Directive name. - locations (
Sequence
[str
]) – Possible locations for that directive. - args (
Optional
[List
[Argument
]]) – Argument definitions. - repeatable (
bool
) – Specify that the directive can be applied multiple times to the same target. Repeatable directives are often useful when the same directive should be used with different arguments at a single location, especially in cases where additional information needs to be provided to a type or schema extension via a directive. - description (
Optional
[str
]) – Directive description. - node (
Optional
[DirectiveDefinition
]) – Source node used when building type from the SDL.
-
arguments
# Directive arguments.
Type: List[py_gql.schema.Argument]
-
argument_map
# Directive arguments in indexed form.
Type: Dict[str, py_gql.schema.Argument]
-
repeatable
# Specify that the directive can be applied multiple times to the same target. Repeatable directives are often useful when the same directive should be used with different arguments at a single location, especially in cases where additional information needs to be provided to a type or schema extension via a directive.
-
node
# Source node used when building type from the SDL.
Type: Optional[py_gql.lang.ast.DirectiveDefinition]
- name (
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 behavior. Do not forget to call the superclass methods as it usually encodes how child elements such as field, enum values, etc. are processed.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
.Specified types (scalars, introspection) and directives are ignored.
-
on_argument_definition
= functools.partial(<function update_wrapper>, wrapped=<function deprecated.<locals>.decorator.<locals>.deprecated_fn>, assigned=('__module__', '__name__', '__qualname__', '__doc__', '__annotations__'), updated=('__dict__',))#
-
on_field_definition
= functools.partial(<function update_wrapper>, wrapped=<function deprecated.<locals>.decorator.<locals>.deprecated_fn>, assigned=('__module__', '__name__', '__qualname__', '__doc__', '__annotations__'), updated=('__dict__',))#
-
on_input_field_definition
= functools.partial(<function update_wrapper>, wrapped=<function deprecated.<locals>.decorator.<locals>.deprecated_fn>, assigned=('__module__', '__name__', '__qualname__', '__doc__', '__annotations__'), updated=('__dict__',))#
-