Type

GraphQL Type System

The graphql.type package is responsible for defining GraphQL types and schema.

Definition

Predicates

graphql.type.is_composite_type(type_: Any) → bool
graphql.type.is_enum_type(type_: Any) → bool
graphql.type.is_input_object_type(type_: Any) → bool
graphql.type.is_input_type(type_: Any) → bool
graphql.type.is_interface_type(type_: Any) → bool
graphql.type.is_leaf_type(type_: Any) → bool
graphql.type.is_list_type(type_: Any) → bool
graphql.type.is_named_type(type_: Any) → bool
graphql.type.is_non_null_type(type_: Any) → bool
graphql.type.is_nullable_type(type_: Any) → bool
graphql.type.is_object_type(type_: Any) → bool
graphql.type.is_output_type(type_: Any) → bool
graphql.type.is_scalar_type(type_: Any) → bool
graphql.type.is_type(type_: Any) → bool
graphql.type.is_union_type(type_: Any) → bool
graphql.type.is_wrapping_type(type_: Any) → bool

Assertions

graphql.type.assert_abstract_type(type_: Any) → Union[graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType]
graphql.type.assert_composite_type(type_: Any) → graphql.type.definition.GraphQLType
graphql.type.assert_enum_type(type_: Any) → graphql.type.definition.GraphQLEnumType
graphql.type.assert_input_object_type(type_: Any) → graphql.type.definition.GraphQLInputObjectType
graphql.type.assert_input_type(type_: Any) → Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLInputObjectType, graphql.type.definition.GraphQLWrappingType]
graphql.type.assert_interface_type(type_: Any) → graphql.type.definition.GraphQLInterfaceType
graphql.type.assert_leaf_type(type_: Any) → Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLEnumType]
graphql.type.assert_list_type(type_: Any) → graphql.type.definition.GraphQLList
graphql.type.assert_named_type(type_: Any) → graphql.type.definition.GraphQLNamedType
graphql.type.assert_non_null_type(type_: Any) → graphql.type.definition.GraphQLNonNull
graphql.type.assert_nullable_type(type_: Any) → Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLObjectType, graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLInputObjectType, graphql.type.definition.GraphQLList]
graphql.type.assert_object_type(type_: Any) → graphql.type.definition.GraphQLObjectType
graphql.type.assert_output_type(type_: Any) → Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLObjectType, graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLWrappingType]
graphql.type.assert_scalar_type(type_: Any) → graphql.type.definition.GraphQLScalarType
graphql.type.assert_type(type_: Any) → graphql.type.definition.GraphQLType
graphql.type.assert_union_type(type_: Any) → graphql.type.definition.GraphQLUnionType
graphql.type.assert_wrapping_type(type_: Any) → graphql.type.definition.GraphQLWrappingType

Un-modifiers

graphql.type.get_nullable_type(type_)

Unwrap possible non-null type

graphql.type.get_named_type(type_)

Unwrap possible wrapping type

Definitions

class graphql.type.GraphQLEnumType(name: str, values: Union[Dict[str, GraphQLEnumValue], Dict[str, Any], Type[enum.Enum]], description: str = None, extensions: Dict[str, Any] = None, ast_node: graphql.language.ast.EnumTypeDefinitionNode = None, extension_ast_nodes: Sequence[graphql.language.ast.EnumTypeExtensionNode] = None)

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 type, often integers. They can also be provided as a Python Enum.

Example:

RGBType = GraphQLEnumType('RGB', {
    'RED': 0,
    'GREEN': 1,
    'BLUE': 2
})

Example using a Python Enum:

class RGBEnum(enum.Enum):
    RED = 0
    GREEN = 1
    BLUE = 2

RGBType = GraphQLEnumType('RGB', enum.Enum)

Instead of raw values, you can also specify GraphQLEnumValue objects with more detail like description or deprecation information.

Note: If a value is not provided in a definition, the name of the enum value will be used as its internal value when the value is serialized.

class graphql.type.GraphQLInputObjectType(name: str, fields: Union[Callable[[], Dict[str, GraphQLInputField]], Dict[str, GraphQLInputField]], description: str = None, out_type: Callable[[Dict[str, Any]], Any] = None, extensions: Dict[str, Any] = None, ast_node: graphql.language.ast.InputObjectTypeDefinitionNode = None, extension_ast_nodes: Sequence[graphql.language.ast.InputObjectTypeExtensionNode] = None)

Input Object Type Definition

An input object defines a structured collection of fields which may be supplied to a field argument.

Using NonNull will ensure that a value must be provided by the query.

Example:

NonNullFloat = GraphQLNonNull(GraphQLFloat())

class GeoPoint(GraphQLInputObjectType):
    name = 'GeoPoint'
    fields = {
        'lat': GraphQLInputField(NonNullFloat),
        'lon': GraphQLInputField(NonNullFloat),
        'alt': GraphQLInputField(
                  GraphQLFloat(), default_value=0)
    }

The outbound values will be Python dictionaries by default, but you can have them converted to other types by specifying an out_type function or class.

class graphql.type.GraphQLInterfaceType(name: str, fields: Union[Callable[[], Dict[str, graphql.type.definition.GraphQLField]], Dict[str, graphql.type.definition.GraphQLField]] = None, resolve_type: Callable[[Any, graphql.type.definition.GraphQLResolveInfo, GraphQLAbstractType], Union[Awaitable[Union[GraphQLObjectType, str, None]], GraphQLObjectType, str, None]] = None, description: str = None, extensions: Dict[str, Any] = None, ast_node: graphql.language.ast.InterfaceTypeDefinitionNode = None, extension_ast_nodes: Sequence[graphql.language.ast.InterfaceTypeExtensionNode] = None)

Interface Type Definition

When a field can return one of a heterogeneous set of types, an 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.

Example:

EntityType = GraphQLInterfaceType('Entity', {
        'name': GraphQLField(GraphQLString),
    })
class graphql.type.GraphQLObjectType(name: str, fields: Union[Callable[[], Dict[str, graphql.type.definition.GraphQLField]], Dict[str, graphql.type.definition.GraphQLField]], interfaces: Union[Callable[[], Sequence[GraphQLInterfaceType]], Sequence[GraphQLInterfaceType]] = None, is_type_of: Callable[[Any, graphql.type.definition.GraphQLResolveInfo], Union[Awaitable[bool], bool]] = None, extensions: Dict[str, Any] = None, description: str = None, ast_node: graphql.language.ast.ObjectTypeDefinitionNode = None, extension_ast_nodes: Sequence[graphql.language.ast.ObjectTypeExtensionNode] = None)

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.

Example:

AddressType = GraphQLObjectType('Address', {
    'street': GraphQLField(GraphQLString),
    'number': GraphQLField(GraphQLInt),
    'formatted': GraphQLField(GraphQLString,
        lambda obj, info, **args: f'{obj.number} {obj.street}')
})

When two types need to refer to each other, or a type needs to refer to itself in a field, you can use a lambda function with no arguments (a so-called “thunk”) to supply the fields lazily.

Example:

PersonType = GraphQLObjectType('Person', lambda: {
    'name': GraphQLField(GraphQLString),
    'bestFriend': GraphQLField(PersonType)
})
class graphql.type.GraphQLScalarType(name: str, serialize: Callable = None, parse_value: Callable = None, parse_literal: Callable = None, description: str = None, extensions: Dict[str, Any] = None, ast_node: graphql.language.ast.ScalarTypeDefinitionNode = None, extension_ast_nodes: Sequence[graphql.language.ast.ScalarTypeExtensionNode] = None)

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.

If a type’s serialize function does not return a value (i.e. it returns None), then no error will be included in the response.

Example:

def serialize_odd(value):
if value % 2 == 1:
return value

odd_type = GraphQLScalarType(‘Odd’, serialize=serialize_odd)

class graphql.type.GraphQLUnionType(name, types: Union[Callable[[], Sequence[graphql.type.definition.GraphQLObjectType]], Sequence[graphql.type.definition.GraphQLObjectType]], resolve_type: Callable[[Any, graphql.type.definition.GraphQLResolveInfo, GraphQLAbstractType], Union[Awaitable[Union[GraphQLObjectType, str, None]], GraphQLObjectType, str, None]] = None, description: str = None, extensions: Dict[str, Any] = None, ast_node: graphql.language.ast.UnionTypeDefinitionNode = None, extension_ast_nodes: Sequence[graphql.language.ast.UnionTypeExtensionNode] = None)

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.

Example:

class PetType(GraphQLUnionType):

name = ‘Pet’ types = [DogType, CatType]

def resolve_type(self, value, _type):
if isinstance(value, Dog):
return DogType()
if isinstance(value, Cat):
return CatType()

Type Wrappers

class graphql.type.GraphQLList(type_: GT)

List Type Wrapper

A list is a wrapping type which points to another type. Lists are often created within the context of defining the fields of an object type.

Example:

class PersonType(GraphQLObjectType):
    name = 'Person'

    @property
    def fields(self):
        return {
            'parents': GraphQLField(GraphQLList(PersonType())),
            'children': GraphQLField(GraphQLList(PersonType())),
        }
class graphql.type.GraphQLNonNull(type_: GNT)

Non-Null Type Wrapper

A non-null 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.

Example:

class RowType(GraphQLObjectType):
    name = 'Row'
    fields = {
        'id': GraphQLField(GraphQLNonNull(GraphQLString()))
    }

Note: the enforcement of non-nullability occurs within the executor.

Types

graphql.type.GraphQLAbstractType
class graphql.type.GraphQLArgument(type_: Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLInputObjectType, graphql.type.definition.GraphQLWrappingType], default_value: Any = <INVALID>, description: str = None, out_name: str = None, extensions: Dict[str, Any] = None, ast_node: graphql.language.ast.InputValueDefinitionNode = None)

Definition of a GraphQL argument

graphql.type.GraphQLArgumentMap
graphql.type.GraphQLCompositeType
class graphql.type.GraphQLEnumValue(value: Any = None, description: str = None, deprecation_reason: str = None, extensions: Dict[str, Any] = None, ast_node: graphql.language.ast.EnumValueDefinitionNode = None)
graphql.type.GraphQLEnumValueMap
class graphql.type.GraphQLField(type_: Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLObjectType, graphql.type.definition.GraphQLInterfaceType, graphql.type.definition.GraphQLUnionType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLWrappingType], args: Dict[str, GraphQLArgument] = None, resolve: Optional[Callable[[...], Any]] = None, subscribe: Optional[Callable[[...], Any]] = None, description: str = None, deprecation_reason: str = None, extensions: Dict[str, Any] = None, ast_node: graphql.language.ast.FieldDefinitionNode = None)

Definition of a GraphQL field

graphql.type.GraphQLFieldMap
class graphql.type.GraphQLInputField(type_: Union[graphql.type.definition.GraphQLScalarType, graphql.type.definition.GraphQLEnumType, graphql.type.definition.GraphQLInputObjectType, graphql.type.definition.GraphQLWrappingType], default_value: Any = <INVALID>, description: str = None, out_name: str = None, extensions: Dict[str, Any] = None, ast_node: graphql.language.ast.InputValueDefinitionNode = None)

Definition of a GraphQL input field

graphql.type.GraphQLInputFieldMap
graphql.type.GraphQLInputType
graphql.type.GraphQLLeafType
class graphql.type.GraphQLNamedType(name: str, description: str = None, extensions: Dict[str, Any] = None, ast_node: graphql.language.ast.TypeDefinitionNode = None, extension_ast_nodes: Sequence[graphql.language.ast.TypeExtensionNode] = None)

Base class for all GraphQL named types

graphql.type.GraphQLNullableType
graphql.type.GraphQLOutputType
class graphql.type.GraphQLType

Base class for all GraphQL types

class graphql.type.GraphQLWrappingType(type_: GT)

Base class for all GraphQL wrapping types

graphql.type.Thunk

Resolvers

graphql.type.GraphQLFieldResolver
graphql.type.GraphQLIsTypeOfFn
class graphql.type.GraphQLResolveInfo

Collection of information passed to the resolvers.

This is always passed as the first argument to the resolvers.

Note that contrary to the JavaScript implementation, the context (commonly used to represent an authenticated user, or request-specific caches) is included here and not passed as an additional argument.

graphql.type.GraphQLTypeResolver

Directives

Predicates

graphql.type.is_directive(directive: Any) → bool

Test if the given value is a GraphQL directive.

graphql.type.is_specified_directive(directive: Any) → bool

Check whether the given directive is one of the specified directives.

Definitions

class graphql.type.GraphQLDirective(name: str, locations: Sequence[graphql.language.directive_locations.DirectiveLocation], args: Dict[str, graphql.type.definition.GraphQLArgument] = None, is_repeatable: bool = False, description: str = None, extensions: Dict[str, Any] = None, ast_node: graphql.language.ast.DirectiveDefinitionNode = None)

GraphQL Directive

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

graphql.type.GraphQLIncludeDirective
graphql.type.GraphQLSkipDirective
graphql.type.GraphQLDeprecatedDirective
graphql.type.specified_directives = [<GraphQLDirective(@include)>, <GraphQLDirective(@skip)>, <GraphQLDirective(@deprecated)>]

The full list of specified directives.

graphql.type.DEFAULT_DEPRECATION_REASON = 'No longer supported'

String constant that can be used as the default value for deprecation_reason.

Introspection

Predicates

graphql.type.is_introspection_type(type_: Any) → bool

Definitions

class graphql.type.TypeKind

An enumeration.

graphql.type.TypeMetaFieldDef
graphql.type.TypeNameMetaFieldDef
graphql.type.SchemaMetaFieldDef
graphql.type.introspection_types = {'__Directive': <GraphQLObjectType '__Directive'>, '__DirectiveLocation': <GraphQLEnumType '__DirectiveLocation'>, '__EnumValue': <GraphQLObjectType '__EnumValue'>, '__Field': <GraphQLObjectType '__Field'>, '__InputValue': <GraphQLObjectType '__InputValue'>, '__Schema': <GraphQLObjectType '__Schema'>, '__Type': <GraphQLObjectType '__Type'>, '__TypeKind': <GraphQLEnumType '__TypeKind'>}

A dictionary containing all introspection types.

Scalars

Predicates

graphql.type.is_specified_scalar_type(type_: Any) → bool

Definitions

graphql.type.GraphQLBoolean
graphql.type.GraphQLFloat
graphql.type.GraphQLID
graphql.type.GraphQLInt
graphql.type.GraphQLString

The list of all specified directives is available as specified_directives.

Schema

Predicates

graphql.type.is_schema(schema: Any) → bool

Test if the given value is a GraphQL schema.

Definitions

class graphql.type.GraphQLSchema(query: graphql.type.definition.GraphQLObjectType = None, mutation: graphql.type.definition.GraphQLObjectType = None, subscription: graphql.type.definition.GraphQLObjectType = None, types: Sequence[graphql.type.definition.GraphQLNamedType] = None, directives: Sequence[graphql.type.directives.GraphQLDirective] = None, extensions: Dict[str, Any] = None, ast_node: graphql.language.ast.SchemaDefinitionNode = None, extension_ast_nodes: Sequence[graphql.language.ast.SchemaExtensionNode] = None, assume_valid: bool = False)

Schema Definition

A Schema is created by supplying the root types of each type of operation, query and mutation (optional). A schema definition is then supplied to the validator and executor.

Example:

MyAppSchema = GraphQLSchema(
  query=MyAppQueryRootType,
  mutation=MyAppMutationRootType)

Note: When the schema is constructed, by default only the types that are reachable by traversing the root types are included, other types must be explicitly referenced.

Example:

character_interface = GraphQLInterfaceType('Character', ...)

human_type = GraphQLObjectType(
    'Human', interfaces=[character_interface], ...)

droid_type = GraphQLObjectType(
    'Droid', interfaces: [character_interface], ...)

schema = GraphQLSchema(
    query=GraphQLObjectType('Query',
        fields={'hero': GraphQLField(character_interface, ....)}),
    ...
    # Since this schema references only the `Character` interface it's
    # necessary to explicitly list the types that implement it if
    # you want them to be included in the final schema.
    types=[human_type, droid_type])

Note: If a list of directives are provided to GraphQLSchema, that will be the exact list of directives represented and allowed. If directives is not provided, then a default set of the specified directives (e.g. @include and @skip) will be used. If you wish to provide additional directives to these specified directives, you must explicitly declare them. Example:

MyAppSchema = GraphQLSchema(
  ...
  directives=specified_directives + [my_custom_directive])

Validate

Functions:

graphql.type.validate_schema(schema: graphql.type.schema.GraphQLSchema) → List[graphql.error.graphql_error.GraphQLError]

Validate a GraphQL schema.

Implements the “Type Validation” sub-sections of the specification’s “Type System” section.

Validation runs synchronously, returning a list of encountered errors, or an empty list if no errors were encountered and the Schema is valid.

Assertions

graphql.type.assert_valid_schema(schema: graphql.type.schema.GraphQLSchema) → None

Utility function which asserts a schema is valid.

Throws a TypeError if the schema is invalid.