Type

GraphQL Type System

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

Definition

Predicates

graphql.type.is_abstract_type(type_: Any) → TypeGuard[GraphQLAbstractType]

Check whether the given value is a GraphQL interface or union type.

Parameters:

type – the value to inspect

Returns:

whether the value is a GraphQL interface or union type

>>> from graphql import build_schema, is_abstract_type
>>> schema = build_schema('''
...     interface Node {
...       id: ID!
...     }
...
...     type User implements Node {
...       id: ID!
...     }
...
...     union SearchResult = User
...
...     type Query {
...       node: Node
...       search: [SearchResult]
...     }
... ''')
>>> is_abstract_type(schema.get_type('Node'))
True
>>> is_abstract_type(schema.get_type('SearchResult'))
True
>>> is_abstract_type(schema.get_type('User'))
False
graphql.type.is_argument(arg: Any) → TypeGuard[GraphQLArgument]

Check whether this is a GraphQL argument.

Parameters:

arg – the value to inspect

Returns:

whether the value is a GraphQLArgument

>>> from graphql import build_schema, is_argument
>>> schema = build_schema('type Query { greeting(name: String): String }')
>>> arg = schema.query_type.fields['greeting'].args['name']
>>> is_argument(arg)
True
>>> is_argument(schema.query_type)
False
graphql.type.is_composite_type(type_: Any) → TypeGuard[GraphQLCompositeType]

Check whether the given value is a GraphQL object, interface, or union type.

Parameters:

type – the value to inspect

Returns:

whether the value is a GraphQL object, interface, or union type

>>> from graphql import build_schema, is_composite_type
>>> schema = build_schema('''
...     interface Node {
...       id: ID!
...     }
...
...     type User implements Node {
...       id: ID!
...     }
...
...     union SearchResult = User
...
...     type Query {
...       node: Node
...       search: [SearchResult]
...     }
... ''')
>>> is_composite_type(schema.get_type('User'))
True
>>> is_composite_type(schema.get_type('Node'))
True
>>> is_composite_type(schema.get_type('SearchResult'))
True
>>> is_composite_type(schema.get_type('String'))
False
graphql.type.is_enum_type(type_: Any) → TypeGuard[GraphQLEnumType]

Check whether the given value is a GraphQLEnumType.

Parameters:

type – the value to inspect

Returns:

whether the value is a GraphQLEnumType

>>> from graphql import build_schema, is_enum_type
>>> schema = build_schema('''
...     enum Episode {
...       NEW_HOPE
...       EMPIRE
...     }
...
...     type Query {
...       favoriteEpisode: Episode
...     }
... ''')
>>> is_enum_type(schema.get_type('Episode'))
True
>>> is_enum_type(schema.get_type('Query'))
False
graphql.type.is_enum_value(value: Any) → TypeGuard[GraphQLEnumValue]

Check whether this is a GraphQL enum value.

Parameters:

value – the value to inspect

Returns:

whether the value is a GraphQLEnumValue

>>> from graphql import assert_enum_type, build_schema, is_enum_value
>>> schema = build_schema(
...     'enum Episode { NEW_HOPE } type Query { episode: Episode }')
>>> enum_value = assert_enum_type(schema.get_type('Episode')).values['NEW_HOPE']
>>> is_enum_value(enum_value)
True
>>> is_enum_value(schema.get_type('Episode'))
False
graphql.type.is_field(field: Any) → TypeGuard[GraphQLField]

Check whether this is a GraphQL field.

Parameters:

field – the value to inspect

Returns:

whether the value is a GraphQLField

>>> from graphql import build_schema, is_field
>>> schema = build_schema('type Query { greeting: String }')
>>> field = schema.query_type.fields['greeting']
>>> is_field(field)
True
>>> is_field(schema.query_type)
False
graphql.type.is_input_field(field: Any) → TypeGuard[GraphQLInputField]

Check whether this is a GraphQL input field.

Parameters:

field – the value to inspect

Returns:

whether the value is a GraphQLInputField

>>> from graphql import assert_input_object_type, build_schema, is_input_field
>>> schema = build_schema(
...     'input ReviewInput { stars: Int } type Query { ok: Boolean }')
>>> input_field = assert_input_object_type(
...     schema.get_type('ReviewInput')).fields['stars']
>>> is_input_field(input_field)
True
>>> is_input_field(schema.query_type)
False
graphql.type.is_input_object_type(type_: Any) → TypeGuard[GraphQLInputObjectType]

Check whether the given value is a GraphQLInputObjectType.

Parameters:

type – the value to inspect

Returns:

whether the value is a GraphQLInputObjectType

>>> from graphql import build_schema, is_input_object_type
>>> schema = build_schema('''
...     input ReviewInput {
...       stars: Int!
...     }
...
...     type Review {
...       stars: Int!
...     }
...
...     type Query {
...       review(input: ReviewInput): Review
...     }
... ''')
>>> is_input_object_type(schema.get_type('ReviewInput'))
True
>>> is_input_object_type(schema.get_type('Review'))
False
graphql.type.is_input_type(type_: Any) → TypeGuard[GraphQLInputType]

Check whether the given value can be used as a GraphQL input type.

Parameters:

type – the value to inspect

Returns:

whether the value can be used as a GraphQL input type

>>> from graphql import build_schema, is_input_type
>>> schema = build_schema('''
...     input ReviewInput {
...       stars: Int!
...     }
...
...     type Review {
...       stars: Int!
...     }
...
...     type Query {
...       review(input: ReviewInput): Review
...     }
... ''')
>>> is_input_type(schema.get_type('ReviewInput'))
True
>>> is_input_type(schema.get_type('Review'))
False
graphql.type.is_interface_type(type_: Any) → TypeGuard[GraphQLInterfaceType]

Check whether the given value is a GraphQLInterfaceType.

Parameters:

type – the value to inspect

Returns:

whether the value is a GraphQLInterfaceType

>>> from graphql import build_schema, is_interface_type
>>> schema = build_schema('''
...     interface Node {
...       id: ID!
...     }
...
...     type User implements Node {
...       id: ID!
...     }
...
...     type Query {
...       node: Node
...     }
... ''')
>>> is_interface_type(schema.get_type('Node'))
True
>>> is_interface_type(schema.get_type('User'))
False
graphql.type.is_leaf_type(type_: Any) → TypeGuard[GraphQLLeafType]

Check whether the given value is a GraphQL scalar or enum type.

Parameters:

type – the value to inspect

Returns:

whether the value is a GraphQL scalar or enum type

>>> from graphql import build_schema, is_leaf_type
>>> schema = build_schema('''
...     enum Episode {
...       NEW_HOPE
...     }
...
...     type Review {
...       stars: Int!
...     }
...
...     type Query {
...       episode: Episode
...       review: Review
...     }
... ''')
>>> is_leaf_type(schema.get_type('Episode'))
True
>>> is_leaf_type(schema.get_type('String'))
True
>>> is_leaf_type(schema.get_type('Review'))
False
graphql.type.is_list_type(type_: Any) → TypeGuard[GraphQLList]

Check whether the given value is a GraphQLList.

Parameters:

type – the value to inspect

Returns:

whether the value is a GraphQLList

>>> from graphql import (
...     build_schema, get_nullable_type, GraphQLList, GraphQLString, is_list_type)
>>> schema = build_schema('''
...     type Query {
...       tags: [String!]!
...     }
... ''')
>>> tags_field = schema.query_type.fields['tags']
>>> is_list_type(GraphQLList(GraphQLString))
True
>>> is_list_type(GraphQLString)
False
>>> is_list_type(tags_field.type)
False
>>> is_list_type(get_nullable_type(tags_field.type))
True
>>> is_list_type('[String]')
False
>>> is_list_type(None)
False
graphql.type.is_named_type(type_: Any) → TypeGuard[GraphQLNamedType]

Check whether the given value is a GraphQL named type.

Parameters:

type – the value to inspect

Returns:

whether the value is a GraphQL named type

>>> from graphql import GraphQLList, GraphQLString, is_named_type
>>> is_named_type(GraphQLString)
True
>>> is_named_type(GraphQLList(GraphQLString))
False
>>> is_named_type(None)
False
graphql.type.is_non_null_type(type_: Any) → TypeGuard[GraphQLNonNull]

Check whether the given value is a GraphQLNonNull.

Parameters:

type – the value to inspect

Returns:

whether the value is a GraphQLNonNull

>>> from graphql import (
...     build_schema, GraphQLNonNull, GraphQLString, is_non_null_type)
>>> schema = build_schema('''
...     type Query {
...       name: String!
...       nickname: String
...     }
... ''')
>>> fields = schema.query_type.fields
>>> is_non_null_type(GraphQLNonNull(GraphQLString))
True
>>> is_non_null_type(fields['name'].type)
True
>>> is_non_null_type(fields['nickname'].type)
False
>>> is_non_null_type('String!')
False
>>> is_non_null_type(None)
False
graphql.type.is_nullable_type(type_: Any) → TypeGuard[GraphQLNullableType]

Check whether the given value is a GraphQL type that can accept null.

Parameters:

type – the value to inspect

Returns:

whether the value is a GraphQL type that can accept null

>>> from graphql import GraphQLNonNull, GraphQLString, is_nullable_type
>>> is_nullable_type(GraphQLString)
True
>>> is_nullable_type(GraphQLNonNull(GraphQLString))
False
>>> is_nullable_type(None)
False
graphql.type.is_object_type(type_: Any) → TypeGuard[GraphQLObjectType]

Check whether the given value is a GraphQLObjectType.

Parameters:

type – the value to inspect

Returns:

whether the value is a GraphQLObjectType

>>> from graphql import build_schema, is_object_type
>>> schema = build_schema('''
...     input ReviewInput {
...       stars: Int!
...     }
...
...     type User {
...       name: String
...     }
...
...     type Query {
...       user: User
...     }
... ''')
>>> is_object_type(schema.get_type('User'))
True
>>> is_object_type(schema.get_type('ReviewInput'))
False
graphql.type.is_output_type(type_: Any) → TypeGuard[GraphQLOutputType]

Check whether the given value can be used as a GraphQL output type.

Parameters:

type – the value to inspect

Returns:

whether the value can be used as a GraphQL output type

>>> from graphql import build_schema, is_output_type
>>> schema = build_schema('''
...     input ReviewInput {
...       stars: Int!
...     }
...
...     type Review {
...       stars: Int!
...     }
...
...     type Query {
...       review(input: ReviewInput): Review
...     }
... ''')
>>> is_output_type(schema.get_type('Review'))
True
>>> is_output_type(schema.get_type('ReviewInput'))
False
graphql.type.is_required_argument(arg: GraphQLArgument | GraphQLVariableSignature) → bool

Check whether the argument is non-null and has no default value.

Parameters:

arg – the argument definition to inspect

Returns:

whether the argument is non-null and has no default value

>>> from graphql import (
...     GraphQLArgument, GraphQLDefaultInput, GraphQLInt, GraphQLNonNull,
...     GraphQLString, is_required_argument)
>>> required_argument = GraphQLArgument(GraphQLNonNull(GraphQLInt))
>>> optional_argument = GraphQLArgument(GraphQLString)
>>> argument_with_default = GraphQLArgument(
...     GraphQLNonNull(GraphQLInt), default=GraphQLDefaultInput(10))
>>> is_required_argument(required_argument)
True
>>> is_required_argument(optional_argument)
False
>>> is_required_argument(argument_with_default)
False
graphql.type.is_required_input_field(field: GraphQLInputField) → bool

Check whether the input field is non-null and has no default value.

Parameters:

field – the input field definition to inspect

Returns:

whether the input field is non-null and has no default value

>>> from graphql import (
...     GraphQLDefaultInput, GraphQLInputField, GraphQLInt, GraphQLNonNull,
...     GraphQLString, is_required_input_field)
>>> required_field = GraphQLInputField(GraphQLNonNull(GraphQLInt))
>>> optional_field = GraphQLInputField(GraphQLString)
>>> field_with_default = GraphQLInputField(
...     GraphQLNonNull(GraphQLInt), default=GraphQLDefaultInput(10))
>>> is_required_input_field(required_field)
True
>>> is_required_input_field(optional_field)
False
>>> is_required_input_field(field_with_default)
False
graphql.type.is_scalar_type(type_: Any) → TypeGuard[GraphQLScalarType]

Check whether the given value is a GraphQLScalarType.

Parameters:

type – the value to inspect

Returns:

whether the value is a GraphQLScalarType

>>> from graphql import build_schema, is_scalar_type
>>> schema = build_schema('''
...     scalar DateTime
...
...     type Query {
...       createdAt: DateTime
...     }
... ''')
>>> is_scalar_type(schema.get_type('DateTime'))
True
>>> is_scalar_type(schema.get_type('Query'))
False
graphql.type.is_type(type_: Any) → TypeGuard[GraphQLType]

Check whether the given value is any GraphQL type.

Parameters:

type – the value to inspect

Returns:

whether the value is any GraphQL type

>>> from graphql import build_schema, GraphQLList, GraphQLString, is_type
>>> schema = build_schema('''
...     type Query {
...       name: String
...     }
... ''')
>>> is_type(GraphQLString)
True
>>> is_type(GraphQLList(GraphQLString))
True
>>> is_type(schema.get_type('Query'))
True
>>> is_type('String')
False
graphql.type.is_union_type(type_: Any) → TypeGuard[GraphQLUnionType]

Check whether the given value is a GraphQLUnionType.

Parameters:

type – the value to inspect

Returns:

whether the value is a GraphQLUnionType

>>> from graphql import build_schema, is_union_type
>>> schema = build_schema('''
...     type Photo {
...       url: String!
...     }
...
...     type Video {
...       url: String!
...     }
...
...     union Media = Photo | Video
...
...     type Query {
...       media: [Media]
...     }
... ''')
>>> is_union_type(schema.get_type('Media'))
True
>>> is_union_type(schema.get_type('Photo'))
False
graphql.type.is_wrapping_type(type_: Any) → TypeGuard[GraphQLWrappingType]

Check whether the given value is a GraphQL list or non-null wrapper type.

Parameters:

type – the value to inspect

Returns:

whether the value is a GraphQL list or non-null wrapper type

>>> from graphql import (
...     GraphQLList, GraphQLNonNull, GraphQLString, is_wrapping_type)
>>> is_wrapping_type(GraphQLList(GraphQLString))
True
>>> is_wrapping_type(GraphQLNonNull(GraphQLString))
True
>>> is_wrapping_type(GraphQLString)
False

Assertions

graphql.type.assert_abstract_type(type_: Any) → GraphQLInterfaceType | GraphQLUnionType

Return the value as a GraphQL abstract type, or raise a TypeError otherwise.

Parameters:

type – the value to inspect

Returns:

the value typed as a GraphQL abstract type

>>> from graphql import build_schema, assert_abstract_type
>>> schema = build_schema('''
...     interface Node {
...       id: ID!
...     }
...
...     type User implements Node {
...       id: ID!
...     }
...
...     type Query {
...       node: Node
...     }
... ''')
>>> node_type = assert_abstract_type(schema.get_type('Node'))
>>> str(node_type)
'Node'
>>> assert_abstract_type(schema.get_type('User'))
Traceback (most recent call last):
...
TypeError: Expected User to be a GraphQL abstract type.
graphql.type.assert_argument(arg: Any) → GraphQLArgument

Return the value as a GraphQLArgument, or raise a TypeError otherwise.

Parameters:

arg – the value to inspect

Returns:

the value typed as a GraphQLArgument

>>> from graphql import assert_argument, build_schema
>>> schema = build_schema('type Query { greeting(name: String): String }')
>>> arg = assert_argument(schema.query_type.fields['greeting'].args['name'])
>>> arg.type
<GraphQLScalarType 'String'>
>>> assert_argument(schema.query_type)
Traceback (most recent call last):
...
TypeError: Expected Query to be a GraphQL argument.
graphql.type.assert_composite_type(type_: Any) → GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType

Return the value as a GraphQL composite type, or raise a TypeError otherwise.

Parameters:

type – the value to inspect

Returns:

the value typed as a GraphQL composite type

>>> from graphql import build_schema, assert_composite_type
>>> schema = build_schema('''
...     interface Node {
...       id: ID!
...     }
...
...     type User implements Node {
...       id: ID!
...     }
...
...     type Query {
...       node: Node
...     }
... ''')
>>> user_type = assert_composite_type(schema.get_type('User'))
>>> str(user_type)
'User'
>>> assert_composite_type(schema.get_type('String'))
Traceback (most recent call last):
...
TypeError: Expected String to be a GraphQL composite type.
graphql.type.assert_enum_type(type_: Any) → GraphQLEnumType

Return the value as a GraphQLEnumType, or raise a TypeError otherwise.

Parameters:

type – the value to inspect

Returns:

the value typed as a GraphQLEnumType

>>> from graphql import build_schema, assert_enum_type
>>> schema = build_schema('''
...     enum Episode {
...       NEW_HOPE
...       EMPIRE
...     }
...
...     type Query {
...       favoriteEpisode: Episode
...     }
... ''')
>>> episode_type = assert_enum_type(schema.get_type('Episode'))
>>> list(episode_type.values)
['NEW_HOPE', 'EMPIRE']
>>> assert_enum_type(schema.get_type('Query'))
Traceback (most recent call last):
...
TypeError: Expected Query to be a GraphQL Enum type.
graphql.type.assert_enum_value(value: Any) → GraphQLEnumValue

Return the value as a GraphQLEnumValue, or raise a TypeError otherwise.

Parameters:

value – the value to inspect

Returns:

the value typed as a GraphQLEnumValue

>>> from graphql import assert_enum_type, assert_enum_value, build_schema
>>> schema = build_schema(
...     'enum Episode { NEW_HOPE } type Query { episode: Episode }')
>>> enum_value = assert_enum_value(
...     assert_enum_type(schema.get_type('Episode')).values['NEW_HOPE'])
>>> enum_value.value
'NEW_HOPE'
>>> assert_enum_value(schema.get_type('Episode'))
Traceback (most recent call last):
...
TypeError: Expected Episode to be a GraphQL Enum value.
graphql.type.assert_field(field: Any) → GraphQLField

Return the value as a GraphQLField, or raise a TypeError otherwise.

Parameters:

field – the value to inspect

Returns:

the value typed as a GraphQLField

>>> from graphql import assert_field, build_schema
>>> schema = build_schema('type Query { greeting: String }')
>>> field = assert_field(schema.query_type.fields['greeting'])
>>> field.type
<GraphQLScalarType 'String'>
>>> assert_field(schema.query_type)
Traceback (most recent call last):
...
TypeError: Expected Query to be a GraphQL field.
graphql.type.assert_input_field(field: Any) → GraphQLInputField

Return the value as a GraphQLInputField, or raise a TypeError otherwise.

Parameters:

field – the value to inspect

Returns:

the value typed as a GraphQLInputField

>>> from graphql import (
...     assert_input_field, assert_input_object_type, build_schema)
>>> schema = build_schema(
...     'input ReviewInput { stars: Int } type Query { ok: Boolean }')
>>> input_field = assert_input_field(
...     assert_input_object_type(schema.get_type('ReviewInput')).fields['stars'])
>>> input_field.type
<GraphQLScalarType 'Int'>
>>> assert_input_field(schema.query_type)
Traceback (most recent call last):
...
TypeError: Expected Query to be a GraphQL input field.
graphql.type.assert_input_object_type(type_: Any) → GraphQLInputObjectType

Return the value as a GraphQLInputObjectType, or raise a TypeError otherwise.

Parameters:

type – the value to inspect

Returns:

the value typed as a GraphQLInputObjectType

>>> from graphql import build_schema, assert_input_object_type
>>> schema = build_schema('''
...     input ReviewInput {
...       stars: Int!
...     }
...
...     type Review {
...       stars: Int!
...     }
...
...     type Query {
...       review(input: ReviewInput): Review
...     }
... ''')
>>> input_type = assert_input_object_type(schema.get_type('ReviewInput'))
>>> list(input_type.fields)
['stars']
>>> assert_input_object_type(schema.get_type('Review'))
Traceback (most recent call last):
...
TypeError: Expected Review to be a GraphQL Input Object type.
graphql.type.assert_input_type(type_: Any) → GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList | GraphQLNonNull[GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList]

Return the value as a GraphQL input type, or raise a TypeError otherwise.

Parameters:

type – the value to inspect

Returns:

the value typed as a GraphQL input type

>>> from graphql import build_schema, assert_input_type
>>> schema = build_schema('''
...     input ReviewInput {
...       stars: Int!
...     }
...
...     type Review {
...       stars: Int!
...     }
...
...     type Query {
...       review(input: ReviewInput): Review
...     }
... ''')
>>> input_type = assert_input_type(schema.get_type('ReviewInput'))
>>> str(input_type)
'ReviewInput'
>>> assert_input_type(schema.get_type('Review'))
Traceback (most recent call last):
...
TypeError: Expected Review to be a GraphQL input type.
graphql.type.assert_interface_type(type_: Any) → GraphQLInterfaceType

Return the value as a GraphQLInterfaceType, or raise a TypeError otherwise.

Parameters:

type – the value to inspect

Returns:

the value typed as a GraphQLInterfaceType

>>> from graphql import build_schema, assert_interface_type
>>> schema = build_schema('''
...     interface Node {
...       id: ID!
...     }
...
...     type User implements Node {
...       id: ID!
...     }
...
...     type Query {
...       node: Node
...     }
... ''')
>>> node_type = assert_interface_type(schema.get_type('Node'))
>>> node_type.name
'Node'
>>> assert_interface_type(schema.get_type('User'))
Traceback (most recent call last):
...
TypeError: Expected User to be a GraphQL Interface type.
graphql.type.assert_leaf_type(type_: Any) → GraphQLScalarType | GraphQLEnumType

Return the value as a GraphQL leaf type, or raise a TypeError otherwise.

Parameters:

type – the value to inspect

Returns:

the value typed as a GraphQL leaf type

>>> from graphql import build_schema, assert_leaf_type
>>> schema = build_schema('''
...     enum Episode {
...       NEW_HOPE
...     }
...
...     type Review {
...       stars: Int!
...     }
...
...     type Query {
...       episode: Episode
...       review: Review
...     }
... ''')
>>> episode_type = assert_leaf_type(schema.get_type('Episode'))
>>> str(episode_type)
'Episode'
>>> assert_leaf_type(schema.get_type('Review'))
Traceback (most recent call last):
...
TypeError: Expected Review to be a GraphQL leaf type.
graphql.type.assert_list_type(type_: Any) → GraphQLList

Return the value as a GraphQLList, or raise a TypeError otherwise.

Parameters:

type – the value to inspect

Returns:

the value typed as a GraphQLList

>>> from graphql import GraphQLList, GraphQLString, assert_list_type
>>> list_type = assert_list_type(GraphQLList(GraphQLString))
>>> list_type.of_type
<GraphQLScalarType 'String'>
>>> assert_list_type(GraphQLString)
Traceback (most recent call last):
...
TypeError: Expected String to be a GraphQL List type.
graphql.type.assert_named_type(type_: Any) → GraphQLNamedType

Return the value as a GraphQL named type, or raise a TypeError otherwise.

Parameters:

type – the value to inspect

Returns:

the value typed as a GraphQL named type

>>> from graphql import GraphQLList, GraphQLString, assert_named_type
>>> named_type = assert_named_type(GraphQLString)
>>> named_type.name
'String'
>>> assert_named_type(GraphQLList(GraphQLString))
Traceback (most recent call last):
...
TypeError: Expected [String] to be a GraphQL named type.
graphql.type.assert_non_null_type(type_: Any) → GraphQLNonNull

Return the value as a GraphQLNonNull, or raise a TypeError otherwise.

Parameters:

type – the value to inspect

Returns:

the value typed as a GraphQLNonNull

>>> from graphql import GraphQLNonNull, GraphQLString, assert_non_null_type
>>> non_null_type = assert_non_null_type(GraphQLNonNull(GraphQLString))
>>> non_null_type.of_type
<GraphQLScalarType 'String'>
>>> assert_non_null_type(GraphQLString)
Traceback (most recent call last):
...
TypeError: Expected String to be a GraphQL Non-Null type.
graphql.type.assert_nullable_type(type_: Any) → GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList

Return the value as a nullable GraphQL type, or raise a TypeError otherwise.

Parameters:

type – the value to inspect

Returns:

the value typed as a nullable GraphQL type

>>> from graphql import GraphQLNonNull, GraphQLString, assert_nullable_type
>>> assert_nullable_type(GraphQLString)
<GraphQLScalarType 'String'>
>>> assert_nullable_type(GraphQLNonNull(GraphQLString))
Traceback (most recent call last):
...
TypeError: Expected String! to be a GraphQL nullable type.
graphql.type.assert_object_type(type_: Any) → GraphQLObjectType

Return the value as a GraphQLObjectType, or raise a TypeError otherwise.

Parameters:

type – the value to inspect

Returns:

the value typed as a GraphQLObjectType

>>> from graphql import build_schema, assert_object_type
>>> schema = build_schema('''
...     input ReviewInput {
...       stars: Int!
...     }
...
...     type User {
...       name: String
...     }
...
...     type Query {
...       user: User
...     }
... ''')
>>> user_type = assert_object_type(schema.get_type('User'))
>>> list(user_type.fields)
['name']
>>> assert_object_type(schema.get_type('ReviewInput'))
Traceback (most recent call last):
...
TypeError: Expected ReviewInput to be a GraphQL Object type.
graphql.type.assert_output_type(type_: Any) → GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLList | GraphQLNonNull[GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLList]

Return the value as a GraphQL output type, or raise a TypeError otherwise.

Parameters:

type – the value to inspect

Returns:

the value typed as a GraphQL output type

>>> from graphql import build_schema, assert_output_type
>>> schema = build_schema('''
...     input ReviewInput {
...       stars: Int!
...     }
...
...     type Review {
...       stars: Int!
...     }
...
...     type Query {
...       review(input: ReviewInput): Review
...     }
... ''')
>>> output_type = assert_output_type(schema.get_type('Review'))
>>> str(output_type)
'Review'
>>> assert_output_type(schema.get_type('ReviewInput'))
Traceback (most recent call last):
...
TypeError: Expected ReviewInput to be a GraphQL output type.
graphql.type.assert_scalar_type(type_: Any) → GraphQLScalarType

Return the value as a GraphQLScalarType, or raise a TypeError otherwise.

Parameters:

type – the value to inspect

Returns:

the value typed as a GraphQLScalarType

>>> from graphql import build_schema, assert_scalar_type
>>> schema = build_schema('''
...     scalar DateTime
...
...     type Query {
...       createdAt: DateTime
...     }
... ''')
>>> date_time_type = assert_scalar_type(schema.get_type('DateTime'))
>>> date_time_type.name
'DateTime'
>>> assert_scalar_type(schema.get_type('Query'))
Traceback (most recent call last):
...
TypeError: Expected Query to be a GraphQL Scalar type.
graphql.type.assert_type(type_: Any) → GraphQLType

Return the value as a GraphQL type, or raise a TypeError if it is not one.

Parameters:

type – the value to inspect

Returns:

the value typed as a GraphQL type

>>> from graphql import build_schema, assert_type
>>> schema = build_schema('''
...     type Query {
...       name: String
...     }
... ''')
>>> query_type = assert_type(schema.get_type('Query'))
>>> str(query_type)
'Query'
>>> assert_type('Query')
Traceback (most recent call last):
...
TypeError: Expected Query to be a GraphQL type.
graphql.type.assert_union_type(type_: Any) → GraphQLUnionType

Return the value as a GraphQLUnionType, or raise a TypeError otherwise.

Parameters:

type – the value to inspect

Returns:

the value typed as a GraphQLUnionType

>>> from graphql import build_schema, assert_union_type
>>> schema = build_schema('''
...     type Photo {
...       url: String!
...     }
...
...     type Video {
...       url: String!
...     }
...
...     union Media = Photo | Video
...
...     type Query {
...       media: [Media]
...     }
... ''')
>>> media_type = assert_union_type(schema.get_type('Media'))
>>> [type_.name for type_ in media_type.types]
['Photo', 'Video']
>>> assert_union_type(schema.get_type('Photo'))
Traceback (most recent call last):
...
TypeError: Expected Photo to be a GraphQL Union type.
graphql.type.assert_wrapping_type(type_: Any) → GraphQLWrappingType

Return the value as a GraphQL wrapping type, or raise a TypeError otherwise.

Parameters:

type – the value to inspect

Returns:

the value typed as a GraphQL wrapping type

>>> from graphql import GraphQLList, GraphQLString, assert_wrapping_type
>>> wrapping_type = assert_wrapping_type(GraphQLList(GraphQLString))
>>> str(wrapping_type)
'[String]'
>>> assert_wrapping_type(GraphQLString)
Traceback (most recent call last):
...
TypeError: Expected String to be a GraphQL wrapping type.

Un-modifiers

graphql.type.get_nullable_type(type_: None) → None
graphql.type.get_nullable_type(type_: GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList) → GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList
graphql.type.get_nullable_type(type_: GraphQLNonNull) → GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList

Unwrap possible non-null type

Parameters:

type – the GraphQL type to inspect

Returns:

the nullable type after removing one non-null wrapper, if present

>>> from graphql import (
...     GraphQLList, GraphQLNonNull, GraphQLString, get_nullable_type)
>>> get_nullable_type(GraphQLNonNull(GraphQLString))
<GraphQLScalarType 'String'>
>>> string_list = GraphQLList(GraphQLString)
>>> get_nullable_type(string_list) is string_list
True
>>> str(get_nullable_type(GraphQLNonNull(GraphQLList(GraphQLString))))
'[String]'
>>> get_nullable_type(None) is None
True
graphql.type.get_named_type(type_: None) → None
graphql.type.get_named_type(type_: GraphQLType) → GraphQLNamedType

Unwrap possible wrapping type

Parameters:

type – the GraphQL type to inspect

Returns:

the named type after unwrapping all list and non-null wrappers, or None if None was passed

>>> from graphql import (
...     build_schema, get_named_type, GraphQLList, GraphQLNonNull, GraphQLString)
>>> schema = build_schema('''
...     input ReviewInput {
...       stars: Int!
...     }
...
...     type User {
...       name: String
...     }
...
...     type Query {
...       review(input: [ReviewInput!]!): Boolean
...       users: [User!]!
...     }
... ''')
>>> fields = schema.query_type.fields
>>> str(get_named_type(fields['review'].args['input'].type))
'ReviewInput'
>>> str(get_named_type(fields['users'].type))
'User'
>>> get_named_type(GraphQLNonNull(GraphQLList(GraphQLNonNull(GraphQLString))))
<GraphQLScalarType 'String'>
>>> get_named_type(None) is None
True

Definitions

class graphql.type.GraphQLEnumType(name: str, *_args: Any, **_kwargs: Any)

Bases: GraphQLNamedType

Enum Type Definition

Enum types define leaf values whose serialized form is one of a fixed set of GraphQL enum names. Internally, enum values can map to any runtime value, often integers. They can also be provided as a Python Enum. In this case, the flag names_as_values determines what will be used as internal representation. The default value of False will use the enum values, the value True will use the enum names, and the value None will use the members themselves.

>>> from graphql import GraphQLEnumType
>>> rgb_type = GraphQLEnumType('RGB', {'RED': 0, 'GREEN': 1, 'BLUE': 2})
>>> rgb_type.values['GREEN'].value
1

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.

Parameters:
  • name – the GraphQL name for this enum type

  • values – values contained in this enum, as a dictionary with value names as keys and GraphQLEnumValue instances or internal values as values, or as a Python Enum, or a thunk returning one of these

  • names_as_values – what to use as internal values when the values are given as a Python Enum: False uses the enum values, True the enum names, and None the enum members themselves (extension of GraphQL.js)

  • description – human-readable description for this type, if provided

  • extensions – custom extensions for this type

  • ast_node – AST node from which this type was built, if available

  • extension_ast_nodes – AST extension nodes applied to this type

>>> from graphql import GraphQLEnumType, GraphQLEnumValue, parse
>>> document = parse('''
...     enum Episode {
...       NEW_HOPE
...       EMPIRE
...       JEDI
...     }
...
...     extend enum Episode {
...       FORCE_AWAKENS
...     }
... ''')
>>> definition = document.definitions[0]
>>> episode_type = GraphQLEnumType(
...     'Episode',
...     description='A Star Wars film episode.',
...     values={
...         'NEW_HOPE': GraphQLEnumValue(
...             4,
...             description='Released in 1977.',
...             extensions={'trilogy': 'original'},
...             ast_node=definition.values[0],
...         ),
...         'EMPIRE': GraphQLEnumValue(5, ast_node=definition.values[1]),
...         'JEDI': GraphQLEnumValue(
...             6,
...             deprecation_reason='Use RETURN_OF_THE_JEDI.',
...             ast_node=definition.values[2],
...         ),
...     },
...     extensions={'catalog': 'films'},
...     ast_node=definition,
...     extension_ast_nodes=[document.definitions[1]],
... )
>>> episode_type.description
'A Star Wars film episode.'
>>> episode_type.coerce_output_value(5)
'EMPIRE'
>>> episode_type.coerce_input_value('JEDI')
6
>>> episode_type.values['JEDI'].deprecation_reason
'Use RETURN_OF_THE_JEDI.'
>>> episode_type.extensions
{'catalog': 'films'}

This variant uses a Python Enum and shows the effect of names_as_values:

>>> from enum import Enum
>>> class RGBEnum(Enum):
...     RED = 0
...     GREEN = 1
...     BLUE = 2
>>> GraphQLEnumType('RGB', RGBEnum).coerce_input_value('GREEN')
1
>>> GraphQLEnumType(
...     'RGB', RGBEnum, names_as_values=True).coerce_input_value('GREEN')
'GREEN'
>>> GraphQLEnumType(
...     'RGB', RGBEnum, names_as_values=None).coerce_input_value('GREEN')
<RGBEnum.GREEN: 1>
ast_node: EnumTypeDefinitionNode | None

AST node from which this schema element was built, if available.

coerce_input_literal(value_node: IntValueNode | FloatValueNode | StringValueNode | BooleanValueNode | NullValueNode | EnumValueNode | ConstListValueNode | ConstObjectValueNode, hide_suggestions: bool = False) → Any

Coerce an enum value AST node to its internal runtime value.

Parameters:
  • value_node – enum value AST node to coerce

  • hide_suggestions – whether suggestion text should be omitted from errors

Returns:

the internal runtime value for the enum literal

>>> from graphql import GraphQLEnumType, parse_const_value
>>> rgb_type = GraphQLEnumType('RGB', {'RED': 0, 'GREEN': 1, 'BLUE': 2})
>>> rgb_type.coerce_input_literal(parse_const_value('RED'))
0
>>> rgb_type.coerce_input_literal(parse_const_value('"RED"'), True)
Traceback (most recent call last):
...
graphql.error.graphql_error.GraphQLError: Enum 'RGB' cannot represent ...
coerce_input_value(input_value: str, hide_suggestions: bool = False) → Any

Coerce an external enum name to its internal runtime value.

Parameters:
  • input_value – external enum name to coerce

  • hide_suggestions – whether suggestion text should be omitted from errors

Returns:

the internal runtime value for the enum name

>>> from graphql import GraphQLEnumType
>>> rgb_type = GraphQLEnumType('RGB', {'RED': 0, 'GREEN': 1, 'BLUE': 2})
>>> rgb_type.coerce_input_value('BLUE')
2
>>> rgb_type.coerce_input_value('PURPLE')
Traceback (most recent call last):
...
graphql.error.graphql_error.GraphQLError: Value 'PURPLE' does not exist ...
>>> rgb_type.coerce_input_value(2)
Traceback (most recent call last):
...
graphql.error.graphql_error.GraphQLError: Enum 'RGB' cannot represent ...
coerce_output_value(output_value: Any) → str

Coerce a runtime enum value to a GraphQL enum name.

Parameters:

output_value – runtime enum value to coerce

Returns:

the GraphQL enum name for the runtime value

>>> from graphql import GraphQLEnumType
>>> rgb_type = GraphQLEnumType('RGB', {'RED': 0, 'GREEN': 1, 'BLUE': 2})
>>> rgb_type.coerce_output_value(1)
'GREEN'
>>> rgb_type.coerce_output_value(3)
Traceback (most recent call last):
...
graphql.error.graphql_error.GraphQLError: Enum 'RGB' cannot represent value: 3
description: str | None

Human-readable description for this schema element, if provided.

extension_ast_nodes: tuple[EnumTypeExtensionNode, ...]

AST extension nodes applied to this schema element.

extensions: dict[str, Any]

Custom extension fields reserved for users.

name: str

The GraphQL name for this schema element.

parse_literal(value_node: ValueNode, _variables: dict[str, Any] | None = None, hide_suggestions: bool = False) → Any

Parse literal value.

Legacy enum parser for externally provided input literals.

Deprecated since version 3.3: Use coerce_input_literal() instead. parse_literal() will be removed in a future version.

Parameters:
  • value_node – enum value AST node to parse

  • _variables – deprecated variable values parameter that is no longer used

  • hide_suggestions – whether suggestion text should be omitted from errors

Returns:

the internal runtime value for the enum literal

>>> from graphql import GraphQLEnumType, parse_value
>>> rgb_type = GraphQLEnumType('RGB', {'RED': 0, 'GREEN': 1, 'BLUE': 2})
>>> rgb_type.parse_literal(parse_value('RED'))
0
>>> rgb_type.parse_literal(parse_value('"RED"'))
Traceback (most recent call last):
...
graphql.error.graphql_error.GraphQLError: Enum 'RGB' cannot represent ...
parse_value(input_value: str, hide_suggestions: bool = False) → Any

Parse an enum value.

Legacy enum parser for externally provided input values.

Deprecated since version 3.3: Use coerce_input_value() instead. parse_value() will be removed in a future version.

Parameters:
  • input_value – external enum name to parse

  • hide_suggestions – whether suggestion text should be omitted from errors

Returns:

the internal runtime value for the enum name

>>> from graphql import GraphQLEnumType
>>> rgb_type = GraphQLEnumType('RGB', {'RED': 0, 'GREEN': 1, 'BLUE': 2})
>>> rgb_type.parse_value('BLUE')
2
>>> rgb_type.parse_value('PURPLE', True)
Traceback (most recent call last):
...
graphql.error.graphql_error.GraphQLError: Value 'PURPLE' does not exist ...
reserved_types: Mapping[str, GraphQLNamedType] = {'Boolean': <GraphQLScalarType 'Boolean'>, 'Float': <GraphQLScalarType 'Float'>, 'ID': <GraphQLScalarType 'ID'>, 'Int': <GraphQLScalarType 'Int'>, 'String': <GraphQLScalarType 'String'>, '__Directive': <GraphQLObjectType '__Directive'>, '__DirectiveLocation': <GraphQLEnumType '__DirectiveLocation'>, '__EnumValue': <GraphQLObjectType '__EnumValue'>, '__Field': <GraphQLObjectType '__Field'>, '__InputValue': <GraphQLObjectType '__InputValue'>, '__Schema': <GraphQLObjectType '__Schema'>, '__Type': <GraphQLObjectType '__Type'>, '__TypeKind': <GraphQLEnumType '__TypeKind'>}

Registry of reserved types (standard scalars and introspection types).

Named types with these names cannot be redefined.

serialize(output_value: Any) → str

Serialize a runtime enum value as a GraphQL enum name.

Deprecated since version 3.3: Use coerce_output_value() instead. serialize() will be removed in a future version.

Parameters:

output_value – runtime enum value to serialize

Returns:

the GraphQL enum name for the runtime value

>>> from graphql import GraphQLEnumType
>>> rgb_type = GraphQLEnumType('RGB', {'RED': 0, 'GREEN': 1, 'BLUE': 2})
>>> rgb_type.serialize(1)
'GREEN'
>>> rgb_type.serialize(3)
Traceback (most recent call last):
...
graphql.error.graphql_error.GraphQLError: Enum 'RGB' cannot represent value: 3
to_kwargs() → GraphQLEnumTypeKwargs

Get the keyword arguments that can be used to recreate this type.

Returns:

a dictionary with the constructor arguments for this type

>>> from graphql import GraphQLEnumType
>>> rgb_type = GraphQLEnumType('RGB', {'RED': 0, 'GREEN': 1, 'BLUE': 2})
>>> kwargs = rgb_type.to_kwargs()
>>> rgb_type_copy = GraphQLEnumType(**kwargs)
>>> kwargs['values']['GREEN'].value
1
>>> rgb_type_copy.serialize(2)
'BLUE'
value_to_literal(value: Any) → IntValueNode | FloatValueNode | StringValueNode | BooleanValueNode | NullValueNode | EnumValueNode | ConstListValueNode | ConstObjectValueNode | None

Convert an external enum value to a GraphQL enum value AST node.

Parameters:

value – external enum value (the enum name) to convert

Returns:

enum value AST node, or None if the value is invalid

>>> from graphql import GraphQLEnumType, print_ast
>>> rgb_type = GraphQLEnumType('RGB', {'RED': 0, 'GREEN': 1, 'BLUE': 2})
>>> print_ast(rgb_type.value_to_literal('BLUE'))
'BLUE'
>>> rgb_type.value_to_literal(3) is None
True
property values: dict[str, GraphQLEnumValue]

Get provided values, wrapping them as GraphQLEnumValues if needed.

Returns:

the enum value definitions keyed by value name, in schema order

>>> from graphql import assert_enum_type, build_schema
>>> schema = build_schema('''
...     enum Episode {
...       NEW_HOPE
...       EMPIRE
...       JEDI
...     }
...
...     type Query {
...       episode: Episode
...     }
... ''')
>>> episode_type = assert_enum_type(schema.get_type('Episode'))
>>> list(episode_type.values)
['NEW_HOPE', 'EMPIRE', 'JEDI']
>>> episode_type.values.get('JEDI') is not None
True
>>> episode_type.values.get('FORCE_AWAKENS') is None
True
class graphql.type.GraphQLInputObjectType(name: str, *_args: Any, **_kwargs: Any)

Bases: GraphQLNamedType

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)

GeoPoint = GraphQLInputObjectType('GeoPoint', {
    'lat': GraphQLInputField(NonNullFloat),
    'lon': GraphQLInputField(NonNullFloat),
    'alt': GraphQLInputField(GraphQLFloat, default=GraphQLDefaultInput(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.

Parameters:
  • name – the GraphQL name for this input object type

  • fields – fields declared by this input object type, as a dictionary with field names as keys and GraphQLInputField instances (or input types) as values, or a thunk returning such a dictionary

  • description – human-readable description for this type, if provided

  • out_type – function or class used to transform outbound values (extension of GraphQL.js)

  • extensions – custom extensions for this type

  • ast_node – AST node from which this type was built, if available

  • extension_ast_nodes – AST extension nodes applied to this type

  • is_one_of – whether this input object uses the experimental OneOf input object semantics

>>> from graphql import (
...     GraphQLDefaultInput, GraphQLID, GraphQLInputField, GraphQLInputObjectType,
...     GraphQLInt, GraphQLNonNull, GraphQLString, parse)
>>> document = parse('''
...     input ReviewInput {
...       stars: Int!
...       commentary: String
...     }
...
...     extend input ReviewInput {
...       body: String
...     }
... ''')
>>> definition = document.definitions[0]
>>> review_input_type = GraphQLInputObjectType(
...     'ReviewInput',
...     description='Input collected when reviewing a product.',
...     fields={
...         'stars': GraphQLInputField(
...             GraphQLNonNull(GraphQLInt),
...             description='Star rating from one to five.',
...             extensions={'min': 1, 'max': 5},
...             ast_node=definition.fields[0],
...         ),
...         'commentary': GraphQLInputField(
...             GraphQLString,
...             default=GraphQLDefaultInput(''),
...             deprecation_reason='Use body.',
...             ast_node=definition.fields[1],
...         ),
...     },
...     extensions={'form': 'review'},
...     ast_node=definition,
...     extension_ast_nodes=[document.definitions[1]],
...     is_one_of=False,
... )
>>> search_by_type = GraphQLInputObjectType(
...     'SearchBy',
...     fields={
...         'id': GraphQLInputField(GraphQLID),
...         'slug': GraphQLInputField(GraphQLString),
...     },
...     is_one_of=True,
... )
>>> fields = review_input_type.fields
>>> review_input_type.description
'Input collected when reviewing a product.'
>>> str(fields['stars'].type)
'Int!'
>>> fields['stars'].extensions
{'min': 1, 'max': 5}
>>> fields['commentary'].default.value
''
>>> fields['commentary'].deprecation_reason
'Use body.'
>>> review_input_type.is_one_of
False
>>> search_by_type.is_one_of
True

This variant converts the outbound values using an out_type:

>>> geo_point_type = GraphQLInputObjectType(
...     'GeoPoint',
...     {
...         'lat': GraphQLInputField(GraphQLInt),
...         'lon': GraphQLInputField(GraphQLInt),
...     },
...     out_type=lambda value: (value['lat'], value['lon']),
... )
>>> geo_point_type.out_type({'lat': 52, 'lon': 13})
(52, 13)
ast_node: InputObjectTypeDefinitionNode | None

AST node from which this schema element was built, if available.

description: str | None

Human-readable description for this schema element, if provided.

extension_ast_nodes: tuple[InputObjectTypeExtensionNode, ...]

AST extension nodes applied to this schema element.

extensions: dict[str, Any]

Custom extension fields reserved for users.

property fields: dict[str, GraphQLInputField]

Get provided fields, wrap them as GraphQLInputField if needed.

Returns:

the fields keyed by field name

>>> from graphql import assert_input_object_type, build_schema, print_ast
>>> schema = build_schema('''
...     input ReviewInput {
...       stars: Int!
...       commentary: String = ""
...     }
...
...     type Query {
...       reviews(filter: ReviewInput): [String]
...     }
... ''')
>>> review_input_type = assert_input_object_type(
...     schema.get_type('ReviewInput'))
>>> fields = review_input_type.fields
>>> list(fields)
['stars', 'commentary']
>>> print_ast(fields['commentary'].default.literal)
'""'
is_one_of: bool

Whether this input object uses the experimental OneOf input object semantics.

name: str

The GraphQL name for this schema element.

static out_type(value: dict[str, Any]) → Any

Transform outbound values (this is an extension of GraphQL.js).

This default implementation passes values unaltered as dictionaries.

Parameters:

value – the coerced input object value as a dictionary

Returns:

the transformed value

reserved_types: Mapping[str, GraphQLNamedType] = {'Boolean': <GraphQLScalarType 'Boolean'>, 'Float': <GraphQLScalarType 'Float'>, 'ID': <GraphQLScalarType 'ID'>, 'Int': <GraphQLScalarType 'Int'>, 'String': <GraphQLScalarType 'String'>, '__Directive': <GraphQLObjectType '__Directive'>, '__DirectiveLocation': <GraphQLEnumType '__DirectiveLocation'>, '__EnumValue': <GraphQLObjectType '__EnumValue'>, '__Field': <GraphQLObjectType '__Field'>, '__InputValue': <GraphQLObjectType '__InputValue'>, '__Schema': <GraphQLObjectType '__Schema'>, '__Type': <GraphQLObjectType '__Type'>, '__TypeKind': <GraphQLEnumType '__TypeKind'>}

Registry of reserved types (standard scalars and introspection types).

Named types with these names cannot be redefined.

to_kwargs() → GraphQLInputObjectTypeKwargs

Get the keyword arguments that can be used to recreate this type.

Returns:

a dictionary with the constructor arguments for this type

>>> from graphql import (
...     GraphQLInputField, GraphQLInputObjectType, GraphQLInt, GraphQLNonNull)
>>> review_input_type = GraphQLInputObjectType(
...     'ReviewInput', {'stars': GraphQLInputField(GraphQLNonNull(GraphQLInt))})
>>> kwargs = review_input_type.to_kwargs()
>>> review_input_type_copy = GraphQLInputObjectType(**kwargs)
>>> str(kwargs['fields']['stars'].type)
'Int!'
>>> str(review_input_type_copy.fields['stars'].type)
'Int!'
class graphql.type.GraphQLInterfaceType(name: str, *_args: Any, **_kwargs: Any)

Bases: GraphQLNamedType

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),
    })
Parameters:
  • name – the GraphQL name for this interface type

  • fields – fields declared by this interface type, as a dictionary with field names as keys and GraphQLField instances (or output types) as values, or a thunk returning such a dictionary

  • interfaces – interfaces implemented by this interface type, or a thunk returning these

  • resolve_type – optionally provide a custom type resolver function. If one is not provided, the default implementation will call is_type_of on each implementing Object type.

  • description – human-readable description for this type, if provided

  • extensions – custom extensions for this type

  • ast_node – AST node from which this type was built, if available

  • extension_ast_nodes – AST extension nodes applied to this type

>>> from graphql import (
...     GraphQLField, GraphQLID, GraphQLInterfaceType, GraphQLNonNull, parse)
>>> document = parse('''
...     interface Node {
...       id: ID!
...     }
...
...     interface Resource implements Node {
...       id: ID!
...     }
...
...     extend interface Resource {
...       url: String
...     }
... ''')
>>> node_type = GraphQLInterfaceType(
...     'Node', {'id': GraphQLField(GraphQLNonNull(GraphQLID))})
>>> resource_type = GraphQLInterfaceType(
...     'Resource',
...     description='An addressable resource.',
...     interfaces=[node_type],
...     fields={'id': GraphQLField(GraphQLNonNull(GraphQLID))},
...     resolve_type=lambda value, _info, _type: (
...         'WebPage' if isinstance(value, dict) and 'url' in value else None),
...     extensions={'abstract': True},
...     ast_node=document.definitions[1],
...     extension_ast_nodes=[document.definitions[2]],
... )
>>> resource_type.name
'Resource'
>>> resource_type.interfaces
(<GraphQLInterfaceType 'Node'>,)
>>> list(resource_type.fields)
['id']
>>> resource_type.extensions
{'abstract': True}
ast_node: InterfaceTypeDefinitionNode | None

AST node from which this schema element was built, if available.

description: str | None

Human-readable description for this schema element, if provided.

extension_ast_nodes: tuple[InterfaceTypeExtensionNode, ...]

AST extension nodes applied to this schema element.

extensions: dict[str, Any]

Custom extension fields reserved for users.

property fields: dict[str, GraphQLField]

Get provided fields, wrapping them as GraphQLFields if needed.

Returns:

the fields keyed by field name

>>> from graphql import assert_interface_type, build_schema
>>> schema = build_schema('''
...     interface Node {
...       id: ID!
...     }
...
...     type User implements Node {
...       id: ID!
...     }
...
...     type Query {
...       node: Node
...     }
... ''')
>>> node_type = assert_interface_type(schema.get_type('Node'))
>>> fields = node_type.fields
>>> list(fields)
['id']
>>> str(fields['id'].type)
'ID!'
property interfaces: tuple[GraphQLInterfaceType, ...]

Get provided interfaces.

Returns:

the implemented interfaces

>>> from graphql import assert_interface_type, build_schema
>>> schema = build_schema('''
...     interface Resource {
...       url: String!
...     }
...
...     interface Image implements Resource {
...       url: String!
...       width: Int
...     }
...
...     type Photo implements Resource & Image {
...       url: String!
...       width: Int
...     }
...
...     type Query {
...       image: Image
...     }
... ''')
>>> image_type = assert_interface_type(schema.get_type('Image'))
>>> [type_.name for type_ in image_type.interfaces]
['Resource']
name: str

The GraphQL name for this schema element.

reserved_types: Mapping[str, GraphQLNamedType] = {'Boolean': <GraphQLScalarType 'Boolean'>, 'Float': <GraphQLScalarType 'Float'>, 'ID': <GraphQLScalarType 'ID'>, 'Int': <GraphQLScalarType 'Int'>, 'String': <GraphQLScalarType 'String'>, '__Directive': <GraphQLObjectType '__Directive'>, '__DirectiveLocation': <GraphQLEnumType '__DirectiveLocation'>, '__EnumValue': <GraphQLObjectType '__EnumValue'>, '__Field': <GraphQLObjectType '__Field'>, '__InputValue': <GraphQLObjectType '__InputValue'>, '__Schema': <GraphQLObjectType '__Schema'>, '__Type': <GraphQLObjectType '__Type'>, '__TypeKind': <GraphQLEnumType '__TypeKind'>}

Registry of reserved types (standard scalars and introspection types).

Named types with these names cannot be redefined.

resolve_type: Callable[[Any, GraphQLResolveInfo, GraphQLInterfaceType | GraphQLUnionType], Awaitable[str | None] | str | None] | None

Function that resolves the concrete object type for this abstract type.

to_kwargs() → GraphQLInterfaceTypeKwargs

Get the keyword arguments that can be used to recreate this type.

Returns:

a dictionary with the constructor arguments for this type

>>> from graphql import (
...     GraphQLField, GraphQLID, GraphQLInterfaceType, GraphQLNonNull)
>>> node_type = GraphQLInterfaceType(
...     'Node', {'id': GraphQLField(GraphQLNonNull(GraphQLID))})
>>> kwargs = node_type.to_kwargs()
>>> node_type_copy = GraphQLInterfaceType(**kwargs)
>>> str(kwargs['fields']['id'].type)
'ID!'
>>> str(node_type_copy.fields['id'].type)
'ID!'
class graphql.type.GraphQLObjectType(name: str, *_args: Any, **_kwargs: Any)

Bases: GraphQLNamedType

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,
        resolve=lambda obj, info: 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)
})
Parameters:
  • name – the GraphQL name for this object type

  • fields – fields declared by this object type, as a dictionary with field names as keys and GraphQLField instances (or output types) as values, or a thunk returning such a dictionary

  • interfaces – interfaces implemented by this object type, or a thunk returning these

  • is_type_of – predicate used to determine whether a runtime value belongs to this object type

  • extensions – custom extensions for this type

  • description – human-readable description for this type, if provided

  • ast_node – AST node from which this type was built, if available

  • extension_ast_nodes – AST extension nodes applied to this type

Configure an object type with interfaces, fields, arguments, and metadata:

>>> from graphql import (
...     GraphQLArgument, GraphQLDefaultInput, GraphQLField, GraphQLID,
...     GraphQLInterfaceType, GraphQLNonNull, GraphQLObjectType, GraphQLString,
...     parse)
>>> document = parse('''
...     type User implements Node {
...       id: ID!
...       name(format: String = "short"): String
...     }
...
...     extend type User {
...       displayName: String
...     }
... ''')
>>> definition = document.definitions[0]
>>> name_field = definition.fields[1]
>>> format_arg = name_field.arguments[0]
>>> node_type = GraphQLInterfaceType(
...     'Node', {'id': GraphQLField(GraphQLNonNull(GraphQLID))})
>>> user_type = GraphQLObjectType(
...     'User',
...     description='A registered user.',
...     interfaces=[node_type],
...     fields={
...         'id': GraphQLField(GraphQLNonNull(GraphQLID)),
...         'name': GraphQLField(
...             GraphQLString,
...             description='The formatted user name.',
...             args={
...                 'format': GraphQLArgument(
...                     GraphQLString,
...                     description='Controls the name format.',
...                     default=GraphQLDefaultInput('short'),
...                     deprecation_reason='Use locale instead.',
...                     extensions={'public': True},
...                     ast_node=format_arg,
...                 ),
...             },
...             resolve=lambda user, _info, format: (
...                 user['full_name'] if format == 'long' else user['name']),
...             deprecation_reason='Use displayName.',
...             extensions={'cacheSeconds': 60},
...             ast_node=name_field,
...         ),
...     },
...     is_type_of=lambda value, _info: isinstance(value, dict) and 'id' in value,
...     extensions={'entity': 'User'},
...     ast_node=definition,
...     extension_ast_nodes=[document.definitions[1]],
... )
>>> user_type.name
'User'
>>> user_type.interfaces
(<GraphQLInterfaceType 'Node'>,)
>>> list(user_type.fields)
['id', 'name']
>>> user_type.fields['name'].args['format'].default.value
'short'
>>> user_type.extensions
{'entity': 'User'}

This variant configures a subscription field with subscribe and resolve functions:

>>> async def subscribe_greeting(_obj, _info):
...     yield {'greeting': 'Hello!'}
>>> subscription_type = GraphQLObjectType(
...     'Subscription',
...     fields={
...         'greeting': GraphQLField(
...             GraphQLString,
...             subscribe=subscribe_greeting,
...             resolve=lambda event, _info: event['greeting'],
...         ),
...     },
... )
>>> callable(subscription_type.fields['greeting'].subscribe)
True
ast_node: ObjectTypeDefinitionNode | None

AST node from which this schema element was built, if available.

description: str | None

Human-readable description for this schema element, if provided.

extension_ast_nodes: tuple[ObjectTypeExtensionNode, ...]

AST extension nodes applied to this schema element.

extensions: dict[str, Any]

Custom extension fields reserved for users.

property fields: dict[str, GraphQLField]

Get provided fields, wrapping them as GraphQLFields if needed.

Returns:

the fields keyed by field name

>>> from graphql import assert_object_type, build_schema
>>> schema = build_schema('''
...     type User {
...       id: ID!
...       name: String
...     }
...
...     type Query {
...       viewer: User
...     }
... ''')
>>> user_type = assert_object_type(schema.get_type('User'))
>>> fields = user_type.fields
>>> list(fields)
['id', 'name']
>>> str(fields['id'].type)
'ID!'
property interfaces: tuple[GraphQLInterfaceType, ...]

Get provided interfaces.

Returns:

the implemented interfaces

>>> from graphql import assert_object_type, build_schema
>>> schema = build_schema('''
...     interface Node {
...       id: ID!
...     }
...
...     type User implements Node {
...       id: ID!
...     }
...
...     type Query {
...       viewer: User
...     }
... ''')
>>> user_type = assert_object_type(schema.get_type('User'))
>>> [type_.name for type_ in user_type.interfaces]
['Node']
is_type_of: Callable[[Any, GraphQLResolveInfo], Awaitable[bool] | bool] | None

Predicate used to determine whether a runtime value belongs to this type.

name: str

The GraphQL name for this schema element.

reserved_types: Mapping[str, GraphQLNamedType] = {'Boolean': <GraphQLScalarType 'Boolean'>, 'Float': <GraphQLScalarType 'Float'>, 'ID': <GraphQLScalarType 'ID'>, 'Int': <GraphQLScalarType 'Int'>, 'String': <GraphQLScalarType 'String'>, '__Directive': <GraphQLObjectType '__Directive'>, '__DirectiveLocation': <GraphQLEnumType '__DirectiveLocation'>, '__EnumValue': <GraphQLObjectType '__EnumValue'>, '__Field': <GraphQLObjectType '__Field'>, '__InputValue': <GraphQLObjectType '__InputValue'>, '__Schema': <GraphQLObjectType '__Schema'>, '__Type': <GraphQLObjectType '__Type'>, '__TypeKind': <GraphQLEnumType '__TypeKind'>}

Registry of reserved types (standard scalars and introspection types).

Named types with these names cannot be redefined.

to_kwargs() → GraphQLObjectTypeKwargs

Get the keyword arguments that can be used to recreate this type.

Returns:

a dictionary with the constructor arguments for this type

>>> from graphql import GraphQLField, GraphQLObjectType, GraphQLString
>>> user_type = GraphQLObjectType(
...     'User', {'name': GraphQLField(GraphQLString)})
>>> kwargs = user_type.to_kwargs()
>>> user_type_copy = GraphQLObjectType(**kwargs)
>>> kwargs['fields']['name'].type
<GraphQLScalarType 'String'>
>>> user_type_copy.fields['name'].type
<GraphQLScalarType 'String'>
class graphql.type.GraphQLScalarType(name: str, *_args: Any, **_kwargs: Any)

Bases: GraphQLNamedType

Scalar Type Definition

Scalar types define the leaf values of a GraphQL response and the input values accepted by arguments and input object fields. A scalar type has a name and coercion functions that validate and convert runtime values and GraphQL literals.

If a type’s coerce_output_value function returns None or Undefined, then an error will be raised and a None value will be returned in the response. Prefer validating inputs before execution so clients receive input diagnostics before result coercion fails.

Custom scalar behavior is defined via the following functions:

  • coerce_output_value(value): Implements “Result Coercion”. Given an internal value, produces an external value valid for this type. Returns Undefined or raises an error to indicate invalid values.

  • coerce_input_value(value): Implements “Input Coercion” for values. Given an external value (for example, variable values), produces an internal value valid for this type. Returns Undefined or raises an error to indicate invalid values.

  • coerce_input_literal(ast): Implements “Input Coercion” for constant literals. Given a GraphQL literal (AST) (for example, an argument value), produces an internal value valid for this type. Returns Undefined or raises an error to indicate invalid values.

  • value_to_literal(value): Converts an external value to a GraphQL literal (AST). Returns Undefined or raises an error to indicate invalid values.

Deprecated, to be removed in a future version:

  • serialize(value): Implements “Result Coercion”. Renamed to coerce_output_value().

  • parse_value(value): Implements “Input Coercion” for values. Renamed to coerce_input_value().

  • parse_literal(ast): Implements “Input Coercion” for literals including non-specified replacement of variables embedded within complex scalars. Replaced by the combination of the replace_variables() utility and the coerce_input_literal() method.

Parameters:
  • name – the GraphQL name for this scalar type

  • serialize – legacy serializer used to convert internal values for response output; deprecated, use coerce_output_value instead

  • parse_value – legacy parser used to convert externally provided input values; deprecated, use coerce_input_value instead

  • parse_literal – legacy parser used to convert externally provided input literals; deprecated, use coerce_input_literal instead

  • coerce_output_value – coerces an internal value to include in a response

  • coerce_input_value – coerces an externally provided value to use as an input

  • coerce_input_literal – coerces an externally provided const literal value to use as an input

  • value_to_literal – translates an externally provided value to a literal (AST)

  • description – human-readable description for this type, if provided

  • specified_by_url – URL identifying the behavior specified for this custom scalar

  • extensions – custom extensions for this type

  • ast_node – AST node from which this type was built, if available

  • extension_ast_nodes – AST extension nodes applied to this type

>>> from graphql import GraphQLError, GraphQLScalarType, IntValueNode
>>> def ensure_odd(value):
...     if not isinstance(value, int):
...         raise GraphQLError(
...             f"Scalar 'Odd' cannot represent '{value}'"
...             " since it is not an integer.")
...     if not value % 2:
...         raise GraphQLError(
...             f"Scalar 'Odd' cannot represent '{value}' since it is even.")
...     return value
>>> odd_type = GraphQLScalarType(
...     'Odd',
...     coerce_output_value=ensure_odd,
...     coerce_input_value=ensure_odd,
...     value_to_literal=lambda value: IntValueNode(value=str(ensure_odd(value))),
... )
>>> odd_type.coerce_output_value(3)
3
>>> odd_type.coerce_input_value(4)
Traceback (most recent call last):
...
graphql.error.graphql_error.GraphQLError: Scalar 'Odd' cannot represent '4' ...
>>> odd_type.value_to_literal(5).value
'5'

Configure a scalar type with all coercion functions and metadata:

>>> from graphql import IntValueNode, parse
>>> document = parse('''
...     "Odd integer values."
...     scalar Odd @specifiedBy(url: "https://example.com/odd")
...
...     extend scalar Odd @specifiedBy(url: "https://example.com/odd-v2")
... ''')
>>> def coerce_input_literal(ast):
...     if not isinstance(ast, IntValueNode):
...         raise TypeError('Odd can only accept integer literals.')
...     value = int(ast.value)
...     if not value % 2:
...         raise TypeError('Odd can only accept odd integer literals.')
...     return value
>>> odd_type = GraphQLScalarType(
...     'Odd',
...     description='Odd integer values.',
...     specified_by_url='https://example.com/odd',
...     coerce_output_value=ensure_odd,
...     coerce_input_value=ensure_odd,
...     coerce_input_literal=coerce_input_literal,
...     value_to_literal=lambda value: IntValueNode(value=str(ensure_odd(value))),
...     extensions={'numeric': True},
...     ast_node=document.definitions[0],
...     extension_ast_nodes=[document.definitions[1]],
... )
>>> odd_type.description
'Odd integer values.'
>>> odd_type.specified_by_url
'https://example.com/odd'
>>> odd_type.coerce_output_value(3)
3
>>> odd_type.coerce_input_value(5)
5
>>> odd_type.extensions
{'numeric': True}
ast_node: ScalarTypeDefinitionNode | None

AST node from which this schema element was built, if available.

coerce_input_literal: Callable[[IntValueNode | FloatValueNode | StringValueNode | BooleanValueNode | NullValueNode | EnumValueNode | ConstListValueNode | ConstObjectValueNode], Any] | None

Coercer used to convert GraphQL scalar input literals.

coerce_input_value: Callable[[Any], Any]

Coercer used to convert externally provided scalar input values.

coerce_output_value: Callable[[Any], Any]

Coercer used to convert internal scalar values for response output.

description: str | None

Human-readable description for this schema element, if provided.

extension_ast_nodes: tuple[ScalarTypeExtensionNode, ...]

AST extension nodes applied to this schema element.

extensions: dict[str, Any]

Custom extension fields reserved for users.

name: str

The GraphQL name for this schema element.

parse_literal(node: ValueNode, variables: dict[str, Any] | None = None) → Any

Parses an externally provided literal value to use as an input.

This default method uses the coerce_input_value method and should be replaced with a more specific version when creating a scalar type.

Deprecated since version 3.3: Use replace_variables() and coerce_input_literal() instead. parse_literal() will be removed in a future version.

Parameters:
  • node – the AST value literal to parse

  • variables – runtime variable values keyed by variable name, used to resolve variables contained in the literal

Returns:

the internal value

>>> from graphql import GraphQLScalarType, parse_value
>>> json_type = GraphQLScalarType('JSON')
>>> json_type.parse_literal(parse_value('{a: [1, 2], b: $var}'), {'var': 3})
{'a': [1, 2], 'b': 3}
static parse_value(value: Any) → Any

Parses an externally provided value to use as an input.

This default method just passes the value through and should be replaced with a more specific version when creating a scalar type.

Deprecated since version 3.3: Use coerce_input_value() instead. parse_value() will be removed in a future version.

Parameters:

value – the externally provided value

Returns:

the internal value

reserved_types: Mapping[str, GraphQLNamedType] = {'Boolean': <GraphQLScalarType 'Boolean'>, 'Float': <GraphQLScalarType 'Float'>, 'ID': <GraphQLScalarType 'ID'>, 'Int': <GraphQLScalarType 'Int'>, 'String': <GraphQLScalarType 'String'>, '__Directive': <GraphQLObjectType '__Directive'>, '__DirectiveLocation': <GraphQLEnumType '__DirectiveLocation'>, '__EnumValue': <GraphQLObjectType '__EnumValue'>, '__Field': <GraphQLObjectType '__Field'>, '__InputValue': <GraphQLObjectType '__InputValue'>, '__Schema': <GraphQLObjectType '__Schema'>, '__Type': <GraphQLObjectType '__Type'>, '__TypeKind': <GraphQLEnumType '__TypeKind'>}

Registry of reserved types (standard scalars and introspection types).

Named types with these names cannot be redefined.

static serialize(value: Any) → Any

Serializes an internal value to include in a response.

This default method just passes the value through and should be replaced with a more specific version when creating a scalar type.

Deprecated since version 3.3: Use coerce_output_value() instead. serialize() will be removed in a future version.

Parameters:

value – the internal value to serialize

Returns:

the serialized value

specified_by_url: str | None

URL identifying the behavior specified for this custom scalar.

to_kwargs() → GraphQLScalarTypeKwargs

Get the keyword arguments that can be used to recreate this type.

Returns:

a dictionary with the constructor arguments for this type

>>> from graphql import GraphQLScalarType
>>> url_type = GraphQLScalarType(
...     'Url',
...     description='An absolute URL string.',
...     specified_by_url='https://url.spec.whatwg.org/',
... )
>>> kwargs = url_type.to_kwargs()
>>> url_type_copy = GraphQLScalarType(**kwargs)
>>> kwargs['name']
'Url'
>>> kwargs['specified_by_url']
'https://url.spec.whatwg.org/'
>>> url_type_copy.name == url_type.name
True
value_to_literal: Callable[[Any], IntValueNode | FloatValueNode | StringValueNode | BooleanValueNode | NullValueNode | EnumValueNode | ConstListValueNode | ConstObjectValueNode | None] | None

Converter used to produce GraphQL literals from runtime input values.

class graphql.type.GraphQLUnionType(name: str, *_args: Any, **_kwargs: Any)

Bases: GraphQLNamedType

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:

def resolve_type(obj, _info, _type):
    if isinstance(obj, Dog):
        return 'Dog'
    if isinstance(obj, Cat):
        return 'Cat'

PetType = GraphQLUnionType('Pet', [DogType, CatType], resolve_type)
Parameters:
  • name – the GraphQL name for this union type

  • types – object types that belong to this union type, or a thunk returning these

  • resolve_type – optionally provide a custom type resolver function. If one is not provided, the default implementation will call is_type_of on each implementing Object type.

  • description – human-readable description for this type, if provided

  • extensions – custom extensions for this type

  • ast_node – AST node from which this type was built, if available

  • extension_ast_nodes – AST extension nodes applied to this type

>>> from graphql import (
...     GraphQLField, GraphQLObjectType, GraphQLString, GraphQLUnionType, parse)
>>> document = parse('''
...     union Media = Photo | Video
...
...     extend union Media = Audio
... ''')
>>> photo_type = GraphQLObjectType(
...     'Photo', {'url': GraphQLField(GraphQLString)})
>>> video_type = GraphQLObjectType(
...     'Video', {'url': GraphQLField(GraphQLString)})
>>> media_type = GraphQLUnionType(
...     'Media',
...     description='Media that can appear in a search result.',
...     types=[photo_type, video_type],
...     resolve_type=lambda value, _info, _type: (
...         'Video' if isinstance(value, dict) and 'duration' in value
...         else 'Photo'),
...     extensions={'searchable': True},
...     ast_node=document.definitions[0],
...     extension_ast_nodes=[document.definitions[1]],
... )
>>> media_type.description
'Media that can appear in a search result.'
>>> [type_.name for type_ in media_type.types]
['Photo', 'Video']
>>> media_type.extensions
{'searchable': True}
ast_node: UnionTypeDefinitionNode | None

AST node from which this schema element was built, if available.

description: str | None

Human-readable description for this schema element, if provided.

extension_ast_nodes: tuple[UnionTypeExtensionNode, ...]

AST extension nodes applied to this schema element.

extensions: dict[str, Any]

Custom extension fields reserved for users.

name: str

The GraphQL name for this schema element.

reserved_types: Mapping[str, GraphQLNamedType] = {'Boolean': <GraphQLScalarType 'Boolean'>, 'Float': <GraphQLScalarType 'Float'>, 'ID': <GraphQLScalarType 'ID'>, 'Int': <GraphQLScalarType 'Int'>, 'String': <GraphQLScalarType 'String'>, '__Directive': <GraphQLObjectType '__Directive'>, '__DirectiveLocation': <GraphQLEnumType '__DirectiveLocation'>, '__EnumValue': <GraphQLObjectType '__EnumValue'>, '__Field': <GraphQLObjectType '__Field'>, '__InputValue': <GraphQLObjectType '__InputValue'>, '__Schema': <GraphQLObjectType '__Schema'>, '__Type': <GraphQLObjectType '__Type'>, '__TypeKind': <GraphQLEnumType '__TypeKind'>}

Registry of reserved types (standard scalars and introspection types).

Named types with these names cannot be redefined.

resolve_type: Callable[[Any, GraphQLResolveInfo, GraphQLInterfaceType | GraphQLUnionType], Awaitable[str | None] | str | None] | None

Function that resolves the concrete object type for this abstract type.

to_kwargs() → GraphQLUnionTypeKwargs

Get the keyword arguments that can be used to recreate this type.

Returns:

a dictionary with the constructor arguments for this type

>>> from graphql import (
...     GraphQLField, GraphQLObjectType, GraphQLString, GraphQLUnionType)
>>> photo_type = GraphQLObjectType(
...     'Photo', {'url': GraphQLField(GraphQLString)})
>>> video_type = GraphQLObjectType(
...     'Video', {'url': GraphQLField(GraphQLString)})
>>> media_type = GraphQLUnionType('Media', [photo_type, video_type])
>>> kwargs = media_type.to_kwargs()
>>> media_type_copy = GraphQLUnionType(**kwargs)
>>> [type_.name for type_ in media_type_copy.types]
['Photo', 'Video']
property types: tuple[GraphQLObjectType, ...]

Get provided types.

Returns:

the union member object types

>>> from graphql import assert_union_type, build_schema
>>> schema = build_schema('''
...     type Photo {
...       url: String!
...     }
...
...     type Video {
...       url: String!
...     }
...
...     union Media = Photo | Video
...
...     type Query {
...       media: [Media]
...     }
... ''')
>>> media_type = assert_union_type(schema.get_type('Media'))
>>> [type_.name for type_ in media_type.types]
['Photo', 'Video']

Type Wrappers

class graphql.type.GraphQLList(type_: GT_co)

Bases: GraphQLWrappingType[GT_co]

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:

PersonType = GraphQLObjectType('Person', lambda: {
    'parents': GraphQLField(GraphQLList(PersonType)),
    'children': GraphQLField(GraphQLList(PersonType)),
})
Parameters:

type – the type to wrap

>>> from graphql import GraphQLList, GraphQLNonNull, GraphQLString
>>> string_list = GraphQLList(GraphQLString)
>>> string_list.of_type
<GraphQLScalarType 'String'>
>>> str(string_list)
'[String]'
>>> str(GraphQLList(GraphQLNonNull(GraphQLString)))
'[String!]'
of_type: GT_co

The type wrapped by this list or non-null type.

class graphql.type.GraphQLNonNull(type_: GNT_co)

Bases: GraphQLWrappingType[GNT_co]

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:

RowType = GraphQLObjectType('Row', lambda: {
    'id': GraphQLField(GraphQLNonNull(GraphQLString)),
})

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

Parameters:

type – the nullable type to wrap

>>> from graphql import GraphQLList, GraphQLNonNull, GraphQLString
>>> required_string = GraphQLNonNull(GraphQLString)
>>> required_string.of_type
<GraphQLScalarType 'String'>
>>> str(required_string)
'String!'
>>> str(GraphQLNonNull(GraphQLList(GraphQLString)))
'[String]!'
of_type: GT_co

The type wrapped by this list or non-null type.

Types

graphql.type.GraphQLAbstractType

alias of GraphQLInterfaceType | GraphQLUnionType

class graphql.type.GraphQLArgument(type_: GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList | GraphQLNonNull[GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList], default_value: Any = Undefined, description: str | None = None, deprecation_reason: str | None = None, out_name: str | None = None, extensions: dict[str, Any] | None = None, ast_node: InputValueDefinitionNode | None = None, default: GraphQLDefaultInput | None = None)

Bases: object

Definition of a GraphQL argument

Parameters:
  • type – the GraphQL input type of this argument

  • default_value – legacy internal (already coerced) default value used when no explicit value is supplied; deprecated, use default instead

  • description – human-readable description for this argument, if provided

  • deprecation_reason – reason this argument is deprecated, if one was provided

  • out_name – name of the Python keyword argument passed to the resolver, if different from the argument name (extension of GraphQL.js)

  • extensions – custom extensions for this argument

  • ast_node – AST node from which this argument was built, if available

  • default – default value represented as either a runtime value or a GraphQL literal

>>> from graphql import (
...     GraphQLArgument, GraphQLDefaultInput, GraphQLField, GraphQLString)
>>> arg = GraphQLArgument(GraphQLString, default=GraphQLDefaultInput('world'))
>>> field = GraphQLField(GraphQLString, args={'name': arg})
>>> field.args['name'] is arg
True
>>> arg.default.value
'world'
ast_node: InputValueDefinitionNode | None

AST node from which this schema element was built, if available.

default: GraphQLDefaultInput | None

Default value represented as either a runtime value or a GraphQL literal.

default_value: Any

Legacy default value used when no explicit value is supplied.

This is the internal (already coerced) default value, or Undefined.

Deprecated since version 3.3: Use default instead. default_value will be removed in a future version.

deprecation_reason: str | None

Reason this element is deprecated, if one was provided.

description: str | None

Human-readable description for this schema element, if provided.

extensions: dict[str, Any]

Custom extension fields reserved for users.

out_name: str | None

Name of the Python keyword argument (extension of GraphQL.js).

Used for transforming names; if not set, the argument name is used.

to_kwargs() → GraphQLArgumentKwargs

Get the keyword arguments that can be used to recreate this argument.

Returns:

a dictionary with the constructor arguments for this argument

>>> from graphql import GraphQLArgument, GraphQLDefaultInput, GraphQLInt
>>> arg = GraphQLArgument(GraphQLInt, default=GraphQLDefaultInput(10))
>>> kwargs = arg.to_kwargs()
>>> kwargs['type_'], kwargs['default'].value
(<GraphQLScalarType 'Int'>, 10)
>>> GraphQLArgument(**kwargs) == arg
True
type: GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList | GraphQLNonNull[GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList]

The GraphQL type reference or runtime type for this element.

graphql.type.GraphQLArgumentMap

alias of dict[str, GraphQLArgument]

graphql.type.GraphQLCompositeType

alias of GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType

class graphql.type.GraphQLDefaultInput(value: Any = Undefined, literal: IntValueNode | FloatValueNode | StringValueNode | BooleanValueNode | NullValueNode | EnumValueNode | ConstListValueNode | ConstObjectValueNode | None = None)

Bases: object

A default value, preserved either as a coerced value or as a literal.

Default values can be provided either as already coerced Python values or as GraphQL literals (AST nodes). Preserving the original literal allows it to be printed back without a lossy round-trip through coercion (see GraphQL.js issue #3051). Exactly one of value or literal is set; the other is left undefined.

Here value is the external default value (it will be coerced), while the deprecated default_value config option of arguments and input fields holds the internal (already coerced) value.

Parameters:
  • value – the runtime default value, if provided

  • literal – the GraphQL literal default value, if provided

>>> from graphql import GraphQLDefaultInput, parse_const_value, print_ast
>>> default = GraphQLDefaultInput(['en', 'de'])
>>> default.value
['en', 'de']
>>> default = GraphQLDefaultInput(literal=parse_const_value('{ lang: "en" }'))
>>> print_ast(default.literal)
'{ lang: "en" }'
literal: IntValueNode | FloatValueNode | StringValueNode | BooleanValueNode | NullValueNode | EnumValueNode | ConstListValueNode | ConstObjectValueNode | None

GraphQL literal default value, or None if a runtime value is provided instead.

value: Any

Runtime default value, or Undefined if a literal is provided instead.

class graphql.type.GraphQLEnumValue(value: Any = None, description: str | None = None, deprecation_reason: str | None = None, extensions: dict[str, Any] | None = None, ast_node: EnumValueDefinitionNode | None = None)

Bases: object

Definition of a GraphQL enum value

Parameters:
  • value – internal value represented by this enum value; if it is not provided, the name of the enum value will be used as its internal value when the value is serialized

  • description – human-readable description for this enum value, if provided

  • deprecation_reason – reason this enum value is deprecated, if one was provided

  • extensions – custom extensions for this enum value

  • ast_node – AST node from which this enum value was built, if available

>>> from graphql import GraphQLEnumType, GraphQLEnumValue, parse
>>> document = parse('''
...     enum Episode {
...       NEW_HOPE
...     }
... ''')
>>> new_hope = GraphQLEnumValue(
...     4,
...     description='Released in 1977.',
...     deprecation_reason='Use A_NEW_HOPE.',
...     extensions={'trilogy': 'original'},
...     ast_node=document.definitions[0].values[0],
... )
>>> new_hope.value, new_hope.description
(4, 'Released in 1977.')
>>> episode_type = GraphQLEnumType('Episode', {'NEW_HOPE': new_hope})
>>> episode_type.serialize(4)
'NEW_HOPE'
ast_node: EnumValueDefinitionNode | None

AST node from which this schema element was built, if available.

deprecation_reason: str | None

Reason this element is deprecated, if one was provided.

description: str | None

Human-readable description for this schema element, if provided.

extensions: dict[str, Any]

Custom extension fields reserved for users.

to_kwargs() → GraphQLEnumValueKwargs

Get the keyword arguments that can be used to recreate this enum value.

Returns:

a dictionary with the constructor arguments for this enum value

>>> from graphql import GraphQLEnumValue
>>> enum_value = GraphQLEnumValue(4, description='Released in 1977.')
>>> kwargs = enum_value.to_kwargs()
>>> kwargs['value'], kwargs['description']
(4, 'Released in 1977.')
>>> GraphQLEnumValue(**kwargs) == enum_value
True
value: Any

Internal value represented by this enum value.

graphql.type.GraphQLEnumValueMap

alias of dict[str, GraphQLEnumValue]

class graphql.type.GraphQLField(type_: GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLList | GraphQLNonNull[GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLList], args: dict[str, GraphQLArgument] | None = None, resolve: Callable[[...], Any] | None = None, subscribe: Callable[[...], Any] | None = None, description: str | None = None, deprecation_reason: str | None = None, extensions: dict[str, Any] | None = None, ast_node: FieldDefinitionNode | None = None)

Bases: object

Definition of a GraphQL field

Parameters:
  • type – the GraphQL output type of this field

  • args – arguments accepted by this field, as a dictionary with argument names as keys and GraphQLArgument instances (or input types) as values

  • resolve – resolver function used to produce this field value

  • subscribe – resolver function used to create a subscription event stream for this field

  • description – human-readable description for this field, if provided

  • deprecation_reason – reason this field is deprecated, if one was provided

  • extensions – custom extensions for this field

  • ast_node – AST node from which this field was built, if available

>>> from graphql import (
...     GraphQLArgument, GraphQLDefaultInput, GraphQLField, GraphQLString, parse)
>>> document = parse('''
...     type User {
...       name(format: String = "short"): String
...     }
... ''')
>>> name_field = document.definitions[0].fields[0]
>>> field = GraphQLField(
...     GraphQLString,
...     description='The formatted user name.',
...     args={
...         'format': GraphQLArgument(
...             GraphQLString, default=GraphQLDefaultInput('short'))
...     },
...     resolve=lambda user, _info, format: (
...         user['full_name'] if format == 'long' else user['name']),
...     deprecation_reason='Use displayName.',
...     extensions={'cacheSeconds': 60},
...     ast_node=name_field,
... )
>>> field.type
<GraphQLScalarType 'String'>
>>> field.args['format'].default.value
'short'
>>> field.resolve({'name': 'Luke', 'full_name': 'Luke Skywalker'}, None, 'long')
'Luke Skywalker'
>>> field.deprecation_reason
'Use displayName.'
>>> field.extensions
{'cacheSeconds': 60}
args: dict[str, GraphQLArgument]

Arguments accepted by this field or directive.

ast_node: FieldDefinitionNode | None

AST node from which this schema element was built, if available.

deprecation_reason: str | None

Reason this element is deprecated, if one was provided.

description: str | None

Human-readable description for this schema element, if provided.

extensions: dict[str, Any]

Custom extension fields reserved for users.

resolve: Callable[[...], Any] | None

Resolver function used to produce this field value.

subscribe: Callable[[...], Any] | None

Resolver function used to create a subscription event stream for this field.

to_kwargs() → GraphQLFieldKwargs

Get the keyword arguments that can be used to recreate this field.

Returns:

a dictionary with the constructor arguments for this field

>>> from graphql import GraphQLField, GraphQLString
>>> field = GraphQLField(GraphQLString, description='The user name.')
>>> kwargs = field.to_kwargs()
>>> kwargs['type_'], kwargs['description']
(<GraphQLScalarType 'String'>, 'The user name.')
>>> GraphQLField(**kwargs) == field
True
type: GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLList | GraphQLNonNull[GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLList]

The GraphQL type reference or runtime type for this element.

graphql.type.GraphQLFieldMap

alias of dict[str, GraphQLField]

class graphql.type.GraphQLInputField(type_: GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList | GraphQLNonNull[GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList], default_value: Any = Undefined, description: str | None = None, deprecation_reason: str | None = None, out_name: str | None = None, extensions: dict[str, Any] | None = None, ast_node: InputValueDefinitionNode | None = None, default: GraphQLDefaultInput | None = None)

Bases: object

Definition of a GraphQL input field

Parameters:
  • type – the GraphQL input type of this input field

  • default_value – legacy internal (already coerced) default value used when no explicit value is supplied; deprecated, use default instead

  • description – human-readable description for this input field, if provided

  • deprecation_reason – reason this input field is deprecated, if one was provided

  • out_name – name of the key in the outbound value, if different from the field name (extension of GraphQL.js)

  • extensions – custom extensions for this input field

  • ast_node – AST node from which this input field was built, if available

  • default – default value represented as either a runtime value or a GraphQL literal

>>> from graphql import (
...     GraphQLDefaultInput, GraphQLInputField, GraphQLInputObjectType,
...     GraphQLString)
>>> field = GraphQLInputField(GraphQLString, default=GraphQLDefaultInput(''))
>>> review_input_type = GraphQLInputObjectType(
...     'ReviewInput', {'commentary': field})
>>> review_input_type.fields['commentary'] is field
True
>>> field.default.value
''
ast_node: InputValueDefinitionNode | None

AST node from which this schema element was built, if available.

default: GraphQLDefaultInput | None

Default value represented as either a runtime value or a GraphQL literal.

default_value: Any

Legacy default value used when no explicit value is supplied.

This is the internal (already coerced) default value, or Undefined.

Deprecated since version 3.3: Use default instead. default_value will be removed in a future version.

deprecation_reason: str | None

Reason this element is deprecated, if one was provided.

description: str | None

Human-readable description for this schema element, if provided.

extensions: dict[str, Any]

Custom extension fields reserved for users.

out_name: str | None

Name of the key in the outbound value (extension of GraphQL.js).

Used for transforming names; if not set, the field name is used.

to_kwargs() → GraphQLInputFieldKwargs

Get the keyword arguments that can be used to recreate this input field.

Returns:

a dictionary with the constructor arguments for this input field

>>> from graphql import GraphQLDefaultInput, GraphQLInputField, GraphQLString
>>> field = GraphQLInputField(GraphQLString, default=GraphQLDefaultInput(''))
>>> kwargs = field.to_kwargs()
>>> kwargs['type_'], kwargs['default'].value
(<GraphQLScalarType 'String'>, '')
>>> GraphQLInputField(**kwargs) == field
True
type: GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList | GraphQLNonNull[GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList]

The GraphQL type reference or runtime type for this element.

graphql.type.GraphQLInputFieldMap

alias of dict[str, GraphQLInputField]

graphql.type.GraphQLInputType

alias of GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList | GraphQLNonNull[GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList]

graphql.type.GraphQLLeafType

alias of GraphQLScalarType | GraphQLEnumType

class graphql.type.GraphQLNamedType(name: str, *_args: Any, **_kwargs: Any)

Bases: GraphQLType

Base class for all GraphQL named types

Named types do not include modifiers like List or NonNull.

Parameters:
  • name – the GraphQL name for this type

  • description – human-readable description for this type, if provided

  • extensions – custom extensions; use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, a dictionary which can contain all the values you need.

  • ast_node – AST node from which this type was built, if available

  • extension_ast_nodes – AST extension nodes applied to this type

>>> from graphql import GraphQLNamedType, GraphQLList, GraphQLString
>>> isinstance(GraphQLString, GraphQLNamedType)
True
>>> isinstance(GraphQLList(GraphQLString), GraphQLNamedType)
False
>>> named_type = GraphQLNamedType(
...     'Named', description='A named type.', extensions={'custom': True})
>>> named_type.name, named_type.description, named_type.extensions
('Named', 'A named type.', {'custom': True})
ast_node: TypeDefinitionNode | None

AST node from which this schema element was built, if available.

description: str | None

Human-readable description for this schema element, if provided.

extension_ast_nodes: tuple[TypeExtensionNode, ...]

AST extension nodes applied to this schema element.

extensions: dict[str, Any]

Custom extension fields reserved for users.

name: str

The GraphQL name for this schema element.

reserved_types: Mapping[str, GraphQLNamedType] = {'Boolean': <GraphQLScalarType 'Boolean'>, 'Float': <GraphQLScalarType 'Float'>, 'ID': <GraphQLScalarType 'ID'>, 'Int': <GraphQLScalarType 'Int'>, 'String': <GraphQLScalarType 'String'>, '__Directive': <GraphQLObjectType '__Directive'>, '__DirectiveLocation': <GraphQLEnumType '__DirectiveLocation'>, '__EnumValue': <GraphQLObjectType '__EnumValue'>, '__Field': <GraphQLObjectType '__Field'>, '__InputValue': <GraphQLObjectType '__InputValue'>, '__Schema': <GraphQLObjectType '__Schema'>, '__Type': <GraphQLObjectType '__Type'>, '__TypeKind': <GraphQLEnumType '__TypeKind'>}

Registry of reserved types (standard scalars and introspection types).

Named types with these names cannot be redefined.

to_kwargs() → GraphQLNamedTypeKwargs

Get the keyword arguments that can be used to recreate this type.

Returns:

a dictionary with the constructor arguments for this type

>>> from graphql import GraphQLNamedType
>>> named_type = GraphQLNamedType('Named', description='A named type.')
>>> kwargs = named_type.to_kwargs()
>>> kwargs['name'], kwargs['description']
('Named', 'A named type.')
>>> GraphQLNamedType(**kwargs).name
'Named'
graphql.type.GraphQLNullableType

alias of GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList

graphql.type.GraphQLOutputType

alias of GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLList | GraphQLNonNull[GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLList]

class graphql.type.GraphQLType

Bases: object

Base class for all GraphQL types

class graphql.type.GraphQLWrappingType(type_: GT_co)

Bases: GraphQLType, Generic[GT_co]

Base class for all GraphQL wrapping types

These types wrap and modify other types. The concrete wrapping types are GraphQLList and GraphQLNonNull.

Parameters:

type – the type to wrap

>>> from graphql import GraphQLList, GraphQLString, GraphQLWrappingType
>>> string_list = GraphQLList(GraphQLString)
>>> isinstance(string_list, GraphQLWrappingType)
True
>>> string_list.of_type
<GraphQLScalarType 'String'>
of_type: GT_co

The type wrapped by this list or non-null type.

graphql.type.Thunk

alias of Callable[[], T] | T

graphql.type.ThunkCollection

alias of Callable[[], Collection[T]] | Collection[T]

graphql.type.ThunkMapping

alias of Callable[[], Mapping[str, T]] | Mapping[str, T]

Resolvers

graphql.type.GraphQLFieldResolver

alias of Callable[[…], Any]

graphql.type.GraphQLIsTypeOfFn

alias of Callable[[Any, GraphQLResolveInfo], Awaitable[bool] | bool]

class graphql.type.GraphQLResolveInfo(field_name: str, field_nodes: list[FieldNode], return_type: GraphQLOutputType, parent_type: GraphQLObjectType, path: Path, schema: GraphQLSchema, fragments: dict[str, FragmentDefinitionNode], root_value: Any, operation: OperationDefinitionNode, variable_values: VariableValues, context: TContext, is_awaitable: Callable[[Any], TypeGuard[Awaitable]], abort_signal: AbortSignal | None, async_helpers: GraphQLResolveInfoHelpers)

Bases: NamedTuple, Generic[TContext]

Collection of information passed to the resolvers.

Information about the currently executing GraphQL field. This is always passed as the second 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. The same applies to the abort signal which in JavaScript is passed as an additional argument to the resolvers.

abort_signal: AbortSignal | None

The abort signal supplied for this execution, if any.

async_helpers: GraphQLResolveInfoHelpers

Helper functions for tracking asynchronous resolver work.

context: TContext

The context value passed to the operation.

This is commonly used to represent an authenticated user, or request-specific caches.

count(value, /)

Return number of occurrences of value.

field_name: str

The name of the field that is currently being resolved.

field_nodes: list[FieldNode]

AST field nodes that contributed to the current field execution.

fragments: dict[str, FragmentDefinitionNode]

Fragment definitions in the operation document keyed by fragment name.

index(value, start=0, stop=9223372036854775807, /)

Return first index of value.

Raises ValueError if the value is not present.

is_awaitable: Callable[[Any], TypeGuard[Awaitable]]

Function used to check whether a value is awaitable.

operation: OperationDefinitionNode

The operation selected for execution.

parent_type: GraphQLObjectType

Object type that owns the current field.

path: Path

Response path to the field that is currently being resolved.

return_type: GraphQLOutputType

GraphQL output type declared for the current field.

root_value: Any

Initial root value passed to the operation.

schema: GraphQLSchema

The schema used for execution.

variable_values: VariableValues

Coerced variable values and source metadata for this operation.

Resolver code that needs runtime variable values should read variable_values.coerced.

class graphql.type.GraphQLResolveInfoHelpers(gather: Callable[[Sequence[Awaitable[Any]]], Awaitable[list[Any]]], track: Callable[[Sequence[Any]], None])

Bases: NamedTuple

Helpers for resolvers to interact with the execution engine.

Utilities available from resolver info for tracking asynchronous work.

count(value, /)

Return number of occurrences of value.

gather: Callable[[Sequence[Awaitable[Any]]], Awaitable[list[Any]]]

Concurrently await the given values as one unit of asynchronous work.

When one of the values fails, the others are cancelled and settled before the error is propagated, so that no asynchronous work is orphaned. This is the counterpart of promiseAll in GraphQL.js.

Intended use: return or await the result from resolver work. Un-awaited async side effects are an anti-pattern; use track for them instead.

index(value, start=0, stop=9223372036854775807, /)

Return first index of value.

Raises ValueError if the value is not present.

track: Callable[[Sequence[Any]], None]

Track asynchronous work that should delay execution completion.

Registers possibly awaitable values as pending asynchronous work of the execution, so that they are still settled and their errors observed when they would otherwise be abandoned.

graphql.type.GraphQLTypeResolver

alias of Callable[[Any, GraphQLResolveInfo, GraphQLAbstractType], Awaitable[str | None] | str | None]

graphql.type.ResponsePath

alias of Path

Directives

Predicates

graphql.type.is_directive(directive: Any) → TypeGuard[GraphQLDirective]

Test if the given value is a GraphQL directive.

Parameters:

directive – the value to inspect

Returns:

whether the value is a GraphQLDirective

>>> from graphql import DirectiveLocation, GraphQLDirective, GraphQLString
>>> from graphql import is_directive
>>> upper = GraphQLDirective('upper', [DirectiveLocation.FIELD_DEFINITION])
>>> is_directive(upper)
True
>>> is_directive(GraphQLString)
False
graphql.type.is_specified_directive(directive: GraphQLDirective) → bool

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

Parameters:

directive – the directive to inspect

Returns:

whether the directive is specified by GraphQL

>>> from graphql import DirectiveLocation, GraphQLDirective
>>> from graphql import GraphQLIncludeDirective, is_specified_directive
>>> custom_directive = GraphQLDirective(
...     'auth', [DirectiveLocation.FIELD_DEFINITION]
... )
>>> is_specified_directive(GraphQLIncludeDirective)
True
>>> is_specified_directive(custom_directive)
False

Assertions

graphql.type.assert_directive(directive: Any) → GraphQLDirective

Return the value as a GraphQL directive, or raise if it is not a directive.

Parameters:

directive – the value to inspect

Returns:

the value typed as a GraphQLDirective

>>> from graphql import DirectiveLocation, GraphQLDirective, GraphQLString
>>> from graphql import assert_directive
>>> upper = GraphQLDirective('upper', [DirectiveLocation.FIELD_DEFINITION])
>>> assert_directive(upper) is upper
True
>>> assert_directive(GraphQLString)
Traceback (most recent call last):
...
TypeError: Expected String to be a GraphQL directive.

Definitions

class graphql.type.GraphQLDirective(name: str, locations: Collection[DirectiveLocation], args: dict[str, GraphQLArgument] | None = None, is_repeatable: bool = False, deprecation_reason: str | None = None, description: str | None = None, extensions: dict[str, Any] | None = None, ast_node: ast.DirectiveDefinitionNode | None = None, extension_ast_nodes: Collection[ast.DirectiveExtensionNode] | None = None)

Bases: object

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.

Parameters:
  • name – the GraphQL name for this directive

  • locations – the locations where this directive may be applied, given as DirectiveLocation values or their names

  • args – the arguments accepted by this directive, given as a dictionary mapping argument names to GraphQLArgument instances or input types

  • is_repeatable – whether this directive may appear more than once at the same location

  • deprecation_reason – the reason this directive is deprecated, if any

  • description – a human-readable description for this directive, if any

  • extensions – custom extension fields reserved for users

  • ast_node – the AST node from which this directive was built, if available

  • extension_ast_nodes – the AST extension nodes applied to this directive

>>> from graphql import (
...     DirectiveLocation,
...     GraphQLArgument,
...     GraphQLBoolean,
...     GraphQLDefaultInput,
...     GraphQLDirective,
...     GraphQLInt,
...     GraphQLNonNull,
...     parse,
... )
>>> document = parse(
...     '''
...     directive @cacheControl(maxAge: Int) repeatable on FIELD_DEFINITION
...     extend directive @cacheControl @tag
...     ''',
... )
>>> definition = document.definitions[0]
>>> cache_control = GraphQLDirective(
...     name='cacheControl',
...     description='Controls HTTP cache hints for a field.',
...     locations=[DirectiveLocation.FIELD_DEFINITION],
...     args={
...         'inheritMaxAge': GraphQLArgument(
...             GraphQLNonNull(GraphQLBoolean),
...             description='Inherit the parent cache hint.',
...             default=GraphQLDefaultInput(False),
...             deprecation_reason='Use maxAge instead.',
...             extensions={'scope': 'cache'},
...         ),
...         'maxAge': GraphQLArgument(
...             GraphQLInt, ast_node=definition.arguments[0]
...         ),
...     },
...     is_repeatable=True,
...     deprecation_reason='Use @cache instead.',
...     extensions={'scope': 'cache'},
...     ast_node=definition,
...     extension_ast_nodes=[document.definitions[1]],
... )
>>> cache_control.name
'cacheControl'
>>> cache_control.description
'Controls HTTP cache hints for a field.'
>>> list(cache_control.args)
['inheritMaxAge', 'maxAge']
>>> cache_control.args['inheritMaxAge'].default.value
False
>>> cache_control.is_repeatable
True
>>> cache_control.extensions
{'scope': 'cache'}
args: dict[str, GraphQLArgument]

Arguments accepted by this directive.

ast_node: DirectiveDefinitionNode | None

AST node from which this schema element was built, if available.

deprecation_reason: str | None

Reason this element is deprecated, if one was provided.

description: str | None

Human-readable description for this schema element, if provided.

extension_ast_nodes: tuple[DirectiveExtensionNode, ...]

AST extension nodes applied to this schema element.

extensions: dict[str, Any]

Custom extension fields reserved for users.

is_repeatable: bool

Whether this directive may appear more than once at the same location.

locations: tuple[DirectiveLocation, ...]

Locations where this directive may be applied.

name: str

The GraphQL name for this schema element.

to_kwargs() → GraphQLDirectiveKwargs

Get a normalized dictionary of keyword arguments for this directive.

Returns:

keyword arguments that can be used to recreate this directive

>>> from graphql import DirectiveLocation, GraphQLDirective, GraphQLString
>>> tag = GraphQLDirective(
...     'tag', [DirectiveLocation.FIELD_DEFINITION], {'name': GraphQLString}
... )
>>> kwargs = tag.to_kwargs()
>>> tag_copy = GraphQLDirective(**kwargs)
>>> kwargs['args']['name'].type is GraphQLString
True
>>> list(tag_copy.args)
['name']
graphql.type.GraphQLIncludeDirective

alias of <GraphQLDirective(@include)>

graphql.type.GraphQLSkipDirective

alias of <GraphQLDirective(@skip)>

graphql.type.GraphQLDeferDirective

alias of <GraphQLDirective(@defer)>

graphql.type.GraphQLStreamDirective

alias of <GraphQLDirective(@stream)>

graphql.type.GraphQLDeprecatedDirective

alias of <GraphQLDirective(@deprecated)>

graphql.type.GraphQLSpecifiedByDirective

alias of <GraphQLDirective(@specifiedBy)>

graphql.type.GraphQLOneOfDirective

alias of <GraphQLDirective(@oneOf)>

graphql.type.specified_directives

A tuple with all directives from the GraphQL specification

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_: GraphQLNamedType) → bool

Check whether the given named GraphQL type is an introspection type.

Parameters:

type – the GraphQL type to inspect

Returns:

whether the type is one of the built-in introspection types

>>> from graphql import GraphQLString, introspection_types, is_introspection_type
>>> is_introspection_type(introspection_types['__Type'])
True
>>> is_introspection_type(GraphQLString)
False

Definitions

class graphql.type.TypeKind(*values)

Bases: Enum

Kinds of types

The introspection enum describing the different kinds of GraphQL types.

ENUM = 'enum'
INPUT_OBJECT = 'input object'
INTERFACE = 'interface'
LIST = 'list'
NON_NULL = 'non-null'
OBJECT = 'object'
SCALAR = 'scalar'
UNION = 'union'
graphql.type.TypeMetaFieldDef

alias of <GraphQLField <GraphQLObjectType ‘__Type’>>

graphql.type.TypeNameMetaFieldDef

alias of <GraphQLField <GraphQLNonNull <GraphQLScalarType ‘String’>>>

graphql.type.SchemaMetaFieldDef

alias of <GraphQLField <GraphQLNonNull <GraphQLObjectType ‘__Schema’>>>

graphql.type.introspection_types

This is a mapping containing all introspection types with their names as keys

Scalars

Predicates

graphql.type.is_specified_scalar_type(type_: GraphQLNamedType) → TypeGuard[GraphQLScalarType]

Check whether the given named GraphQL type is a specified scalar type.

Parameters:

type – the GraphQL type to inspect

Returns:

whether the type is one of the scalars specified by GraphQL

>>> from graphql import GraphQLScalarType, GraphQLString, is_specified_scalar_type
>>> DateTime = GraphQLScalarType('DateTime')
>>> is_specified_scalar_type(GraphQLString)
True
>>> is_specified_scalar_type(DateTime)
False

Definitions

graphql.type.GraphQLBoolean

alias of <GraphQLScalarType ‘Boolean’>

graphql.type.GraphQLFloat

alias of <GraphQLScalarType ‘Float’>

graphql.type.GraphQLID

alias of <GraphQLScalarType ‘ID’>

graphql.type.GraphQLInt

alias of <GraphQLScalarType ‘Int’>

graphql.type.GraphQLString

alias of <GraphQLScalarType ‘String’>

graphql.type.specified_scalar_types

A mapping containing all scalar types from the GraphQL specification

graphql.type.GRAPHQL_MAX_INT

Maximum possible Int value as per GraphQL Spec (32-bit signed integer)

graphql.type.GRAPHQL_MIN_INT

Minimum possible Int value as per GraphQL Spec (32-bit signed integer)

Schema

Predicates

graphql.type.is_schema(schema: Any) → TypeGuard[GraphQLSchema]

Test if the given value is a GraphQL schema.

Parameters:

schema – the value to inspect

Returns:

whether the value is a GraphQLSchema

>>> from graphql import GraphQLString, build_schema, is_schema
>>> schema = build_schema('''
...     type Query {
...       greeting: String
...     }
... ''')
>>> is_schema(schema)
True
>>> is_schema(GraphQLString)
False

Assertions

graphql.type.assert_schema(schema: Any) → GraphQLSchema

Return the value as a GraphQL schema, or raise if it is not a schema.

Parameters:

schema – the value to inspect

Returns:

the value typed as a GraphQLSchema

>>> from graphql import GraphQLString, assert_schema, build_schema
>>> schema = build_schema('''
...     type Query {
...       greeting: String
...     }
... ''')
>>> assert_schema(schema) is schema
True
>>> assert_schema(GraphQLString)
Traceback (most recent call last):
...
TypeError: Expected String to be a GraphQL schema.

Definitions

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

Bases: object

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.

Schemas should be considered immutable once they are created. If you want to modify a schema, modify the result of the to_kwargs() method and recreate the schema.

Example:

MyAppQueryRootType = GraphQLObjectType(
    'Query', {'greeting': GraphQLField(GraphQLString)})

MyAppMutationRootType = GraphQLObjectType(
    'Mutation', {'setGreeting': GraphQLField(GraphQLString)})

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', {'name': GraphQLField(GraphQLString)})

human_type = GraphQLObjectType(
    'Human', {'name': GraphQLField(GraphQLString)},
    interfaces=[character_interface])

droid_type = GraphQLObjectType(
    'Droid', {'name': GraphQLField(GraphQLString)},
    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 is 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(
  query=MyAppQueryRootType,
  directives=(*specified_directives, my_custom_directive))
Parameters:
  • query – the root object type for query operations

  • mutation – the root object type for mutation operations

  • subscription – the root object type for subscription operations

  • types – additional named types that shall be included in the schema

  • directives – the directives available in this schema; if not provided, the specified directives will be used

  • description – a human-readable description for this schema, if any

  • extensions – custom extension fields reserved for users

  • ast_node – the AST node from which this schema was built, if available

  • extension_ast_nodes – the AST extension nodes applied to this schema

  • assume_valid – if this schema was built from a source known to be valid, then it may be marked with assume_valid to avoid an additional type system validation

Create a schema with the required query root:

>>> from graphql import (
...     GraphQLField, GraphQLObjectType, GraphQLSchema, GraphQLString
... )
>>> Query = GraphQLObjectType(
...     'Query',
...     {'greeting': GraphQLField(GraphQLString, resolve=lambda *_: 'Hello')},
... )
>>> schema = GraphQLSchema(
...     description='The application schema.',
...     query=Query,
... )
>>> schema.query_type is Query
True
>>> schema.description
'The application schema.'

This variant configures every schema option, including directives and extensions:

>>> from graphql import (
...     DirectiveLocation,
...     GraphQLArgument,
...     GraphQLBoolean,
...     GraphQLDirective,
...     GraphQLField,
...     GraphQLObjectType,
...     GraphQLSchema,
...     GraphQLString,
...     parse,
... )
>>> Query = GraphQLObjectType(
...     'Query', {'greeting': GraphQLField(GraphQLString)}
... )
>>> Mutation = GraphQLObjectType(
...     'Mutation', {'setGreeting': GraphQLField(GraphQLString)}
... )
>>> Subscription = GraphQLObjectType(
...     'Subscription', {'greetingChanged': GraphQLField(GraphQLString)}
... )
>>> AuditEvent = GraphQLObjectType(
...     'AuditEvent', {'message': GraphQLField(GraphQLString)}
... )
>>> auth_directive = GraphQLDirective(
...     'auth',
...     [DirectiveLocation.FIELD_DEFINITION],
...     {'required': GraphQLArgument(GraphQLBoolean)},
... )
>>> schema_document = parse('''
...     schema {
...       query: Query
...       mutation: Mutation
...       subscription: Subscription
...     }
...
...     extend schema @auth
... ''')
>>> schema = GraphQLSchema(
...     description='Operations exposed by the application.',
...     query=Query,
...     mutation=Mutation,
...     subscription=Subscription,
...     types=[AuditEvent],
...     directives=[auth_directive],
...     extensions={'owner': 'platform'},
...     ast_node=schema_document.definitions[0],
...     extension_ast_nodes=[schema_document.definitions[1]],
...     assume_valid=True,
... )
>>> schema.mutation_type is Mutation
True
>>> schema.subscription_type is Subscription
True
>>> schema.get_type('AuditEvent') is AuditEvent
True
>>> schema.get_directive('auth') is auth_directive
True
>>> schema.extensions
{'owner': 'platform'}
assume_valid: bool

Whether this schema instance skips validation checks.

ast_node: ast.SchemaDefinitionNode | None

AST node from which this schema element was built, if available.

description: str | None

Human-readable description for this schema element, if provided.

directives: tuple[GraphQLDirective, ...]

Directives available in this schema.

extension_ast_nodes: tuple[ast.SchemaExtensionNode, ...]

AST extension nodes applied to this schema element.

extensions: dict[str, Any]

Custom extension fields reserved for users.

get_directive(name: str) → GraphQLDirective | None

Get the directive with the provided name.

Parameters:

name – the GraphQL name to look up

Returns:

the directive definition, if known

>>> from graphql import build_schema
>>> schema = build_schema('''
...     directive @upper on FIELD_DEFINITION
...
...     type Query {
...       greeting: String @upper
...     }
... ''')
>>> schema.get_directive('upper').name
'upper'
>>> schema.get_directive('missing') is None
True
>>> [directive.name for directive in schema.directives]
['upper', 'include', 'skip', 'deprecated', 'specifiedBy', 'oneOf']
get_field(parent_type: GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType, field_name: str) → GraphQLField | None

Get field of a given type with the given name.

This method looks up the field on the given type definition. It has special casing for the three introspection fields, __schema, __type and __typename.

__typename is special because it can always be queried as a field, even in situations where no other fields are allowed, like on a Union.

__schema and __type could get automatically added to the query type, but that would require mutating type definitions, which would cause issues.

Parameters:
  • parent_type – composite type to look up the field on

  • field_name – field name to look up

Returns:

the field definition, including supported introspection fields

>>> from graphql import build_schema
>>> schema = build_schema('''
...     type Query {
...       greeting: String
...     }
... ''')
>>> query_type = schema.query_type
>>> schema.get_field(query_type, 'greeting').type
<GraphQLScalarType 'String'>
>>> str(schema.get_field(query_type, '__typename').type)
'String!'
>>> schema.get_field(query_type, 'missing') is None
True
get_implementations(interface_type: GraphQLInterfaceType) → InterfaceImplementations

Get the objects and interfaces that implement an interface type.

Parameters:

interface_type – the interface type to inspect

Returns:

the object and interface implementations of the interface

>>> from graphql import assert_interface_type, build_schema
>>> schema = build_schema('''
...     interface Resource {
...       url: String!
...     }
...
...     interface Image implements Resource {
...       url: String!
...       width: Int
...     }
...
...     type Photo implements Resource & Image {
...       url: String!
...       width: Int
...     }
...
...     type Query {
...       resource: Resource
...     }
... ''')
>>> Resource = assert_interface_type(schema.get_type('Resource'))
>>> implementations = schema.get_implementations(Resource)
>>> [type_.name for type_ in implementations.interfaces]
['Image']
>>> [type_.name for type_ in implementations.objects]
['Photo']
get_possible_types(abstract_type: GraphQLInterfaceType | GraphQLUnionType) → list[GraphQLObjectType]

Get list of all possible concrete types for given abstract type.

Parameters:

abstract_type – the interface or union type to inspect

Returns:

the object types that may satisfy the abstract type

>>> from graphql import (
...     assert_interface_type, assert_union_type, build_schema
... )
>>> schema = build_schema('''
...     interface Node {
...       id: ID!
...     }
...
...     type User implements Node {
...       id: ID!
...     }
...
...     type Organization implements Node {
...       id: ID!
...     }
...
...     union SearchResult = User | Organization
...
...     type Query {
...       node: Node
...       search: [SearchResult]
...     }
... ''')
>>> Node = assert_interface_type(schema.get_type('Node'))
>>> SearchResult = assert_union_type(schema.get_type('SearchResult'))
>>> [type_.name for type_ in schema.get_possible_types(Node)]
['User', 'Organization']
>>> [type_.name for type_ in schema.get_possible_types(SearchResult)]
['User', 'Organization']
get_root_type(operation: OperationType) → GraphQLObjectType | None

Get the root object type for the requested operation kind.

Parameters:

operation – the operation kind to resolve

Returns:

the root object type for the operation kind, if this schema defines one

>>> from graphql import OperationType, build_schema
>>> schema = build_schema('''
...     type Query {
...       greeting: String
...     }
...
...     type Mutation {
...       setGreeting(value: String!): String
...     }
... ''')
>>> schema.get_root_type(OperationType.QUERY).name
'Query'
>>> schema.get_root_type(OperationType.MUTATION).name
'Mutation'
>>> schema.get_root_type(OperationType.SUBSCRIPTION) is None
True
get_type(name: str) → GraphQLNamedType | None

Get the named type with the provided name.

Parameters:

name – the GraphQL name to look up

Returns:

the named schema type, if one exists

>>> from graphql import build_schema
>>> schema = build_schema('''
...     type User {
...       name: String
...     }
...
...     type Query {
...       viewer: User
...     }
... ''')
>>> str(schema.get_type('User'))
'User'
>>> schema.get_type('Missing') is None
True
is_sub_type(abstract_type: GraphQLInterfaceType | GraphQLUnionType, maybe_sub_type: GraphQLNamedType) → bool

Check whether a type is a subtype of a given abstract type.

Parameters:
  • abstract_type – the interface or union type to inspect

  • maybe_sub_type – the object or interface type to test as a possible subtype

Returns:

whether the subtype may satisfy the abstract type

>>> from graphql import (
...     assert_interface_type, assert_object_type, build_schema
... )
>>> schema = build_schema('''
...     interface Node {
...       id: ID!
...     }
...
...     type User implements Node {
...       id: ID!
...     }
...
...     type Review {
...       body: String
...     }
...
...     type Query {
...       node: Node
...       review: Review
...     }
... ''')
>>> Node = assert_interface_type(schema.get_type('Node'))
>>> User = assert_object_type(schema.get_type('User'))
>>> Review = assert_object_type(schema.get_type('Review'))
>>> schema.is_sub_type(Node, User)
True
>>> schema.is_sub_type(Node, Review)
False
mutation_type: GraphQLObjectType | None

The root object type for mutation operations, if this schema defines one.

query_type: GraphQLObjectType | None

The root object type for query operations, if this schema defines one.

subscription_type: GraphQLObjectType | None

The root object type for subscription operations, if defined.

to_kwargs() → GraphQLSchemaKwargs

Get a normalized dictionary of keyword arguments for this schema.

The returned keyword arguments preserve the original assume_valid flag so the schema can be recreated with the same validation behavior.

Returns:

keyword arguments that can be used to recreate this schema

>>> from graphql import GraphQLSchema, build_schema
>>> schema = build_schema('''
...     type Query {
...       greeting: String
...     }
... ''')
>>> kwargs = schema.to_kwargs()
>>> schema_copy = GraphQLSchema(**kwargs)
>>> kwargs['query'].name
'Query'
>>> schema_copy.query_type.name
'Query'
type_map: TypeMap

All named types known to this schema, keyed by type name.

Validate

Functions

graphql.type.validate_schema(schema: GraphQLSchema) → list[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.

Parameters:

schema – the GraphQL schema to validate

Returns:

the schema validation errors, or an empty list if the schema is valid

>>> from graphql import build_schema, validate_schema
>>> schema = build_schema('''
...     type Query {
...       name: String
...     }
... ''')
>>> validate_schema(schema)
[]

Assertions

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

Utility function which asserts a schema is valid.

Throws a TypeError if the schema is invalid.

Parameters:

schema – the GraphQL schema to validate

>>> from graphql import assert_valid_schema, build_schema
>>> schema = build_schema('''
...     type Query {
...       name: String
...     }
... ''')
>>> assert_valid_schema(schema)  # does not raise

Other

Thunk Handling

graphql.type.resolve_thunk(thunk: Callable[[], T] | T) → T

Resolve the given thunk.

Used while defining GraphQL types to allow for circular references in otherwise immutable type definitions.

Parameters:

thunk – the thunk (a function without arguments) or value to resolve

Returns:

the result of calling the thunk, or the value itself

>>> from graphql import GraphQLString, resolve_thunk
>>> lazy_fields = resolve_thunk(lambda: {'name': GraphQLString})
>>> fields = resolve_thunk({'name': GraphQLString})
>>> lazy_fields['name']
<GraphQLScalarType 'String'>
>>> fields['name']
<GraphQLScalarType 'String'>

Assertions

graphql.type.assert_name(name: str) → str

Uphold the spec rules about naming.

Parameters:

name – the GraphQL name to validate

Returns:

the validated GraphQL name

>>> from graphql import assert_name
>>> assert_name('User')
'User'
>>> assert_name('123User')
Traceback (most recent call last):
...
graphql.error.graphql_error.GraphQLError: Names must start with [_a-zA-Z] ...
graphql.type.assert_enum_value_name(name: str) → str

Uphold the spec rules about naming enum values.

Parameters:

name – the GraphQL name to validate

Returns:

the validated GraphQL name

>>> from graphql import assert_enum_value_name
>>> assert_enum_value_name('ACTIVE')
'ACTIVE'
>>> assert_enum_value_name('true')
Traceback (most recent call last):
...
graphql.error.graphql_error.GraphQLError: Enum values cannot be named: true.