API Reference

Schema

class graphene.types.schema.Schema(query=None, mutation=None, subscription=None, types=None, directives=None, auto_camelcase=True)[source]

Schema Definition. A Graphene Schema can execute operations (query, mutation, subscription) against the defined types. For advanced purposes, the schema can be used to lookup type definitions and answer questions about the types through introspection. :param query: Root query ObjectType. Describes entry point for fields to read

data in your Schema.
Parameters:
  • mutation (Optional[Type[ObjectType]]) – Root mutation ObjectType. Describes entry point for fields to create, update or delete data in your API.
  • subscription (Optional[Type[ObjectType]]) – Root subscription ObjectType. Describes entry point for fields to receive continuous updates.
  • types (Optional[List[Type[ObjectType]]]) – List of any types to include in schema that may not be introspected through root types.
  • directives (List[GraphQLDirective], optional) – List of custom directives to include in the GraphQL schema. Defaults to only include directives defined by GraphQL spec (@include and @skip) [GraphQLIncludeDirective, GraphQLSkipDirective].
  • auto_camelcase (bool) – Fieldnames will be transformed in Schema’s TypeMap from snake_case to camelCase (preferred by GraphQL standard). Default True.
execute(*args, **kwargs)[source]

Execute a GraphQL query on the schema. Use the graphql_sync function from graphql-core to provide the result for a query string. Most of the time this method will be called by one of the Graphene Integrations via a web request. :param request_string: GraphQL request (query, mutation or subscription)

as string or parsed AST form from graphql-core.
Parameters:
  • root_value (Any, optional) – Value to use as the parent value object when resolving root types.
  • context_value (Any, optional) – Value to be made available to all resolvers via info.context. Can be used to share authorization, dataloaders or other information needed to resolve an operation.
  • variable_values (dict, optional) – If variables are used in the request string, they can be provided in dictionary form mapping the variable name to the variable value.
  • operation_name (str, optional) – If multiple operations are provided in the request_string, an operation name must be provided for the result to be provided.
  • middleware (List[SupportsGraphQLMiddleware]) – Supply request level middleware as defined in graphql-core.
  • execution_context_class (ExecutionContext, optional) – The execution context class to use when resolving queries and mutations.
Returns:

ExecutionResult containing any data and errors for the operation.

execute_async(*args, **kwargs)[source]

Execute a GraphQL query on the schema asynchronously. Same as execute, but uses graphql instead of graphql_sync.

subscribe(query, *args, **kwargs)[source]

Execute a GraphQL subscription on the schema asynchronously.

Object types

class graphene.ObjectType[source]

Object Type Definition

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

The name of the type defined by an _ObjectType_ defaults to the class name. The type description defaults to the class docstring. This can be overridden by adding attributes to a Meta inner class.

The class attributes of an _ObjectType_ are mounted as instances of graphene.Field.

Methods starting with resolve_<field_name> are bound as resolvers of the matching Field name. If no resolver is provided, the default resolver is used.

Ambiguous types with Interface and Union can be determined through is_type_of method and Meta.possible_types attribute.

from graphene import ObjectType, String, Field

class Person(ObjectType):
    class Meta:
        description = 'A human'

    # implicitly mounted as Field
    first_name = String()
    # explicitly mounted as Field
    last_name = Field(String)

    def resolve_last_name(parent, info):
        return last_name

ObjectType must be mounted using graphene.Field.

from graphene import ObjectType, Field

class Query(ObjectType):

    person = Field(Person, description="My favorite person")
Meta class options (optional):
name (str): Name of the GraphQL type (must be unique in schema). Defaults to class
name.
description (str): Description of the GraphQL type in the schema. Defaults to class
docstring.
interfaces (Iterable[graphene.Interface]): GraphQL interfaces to extend with this object.
all fields from interface will be included in this object’s schema.
possible_types (Iterable[class]): Used to test parent value object via isinstance to see if
this type can be used to resolve an ambiguous type (interface, union).
default_resolver (any Callable resolver): Override the default resolver for this
type. Defaults to graphene default resolver which returns an attribute or dictionary key with the same name as the field.
fields (Dict[str, graphene.Field]): Dictionary of field name to Field. Not recommended to
use (prefer class attributes).

An _ObjectType_ can be used as a simple value object by creating an instance of the class.

p = Person(first_name='Bob', last_name='Roberts')
assert p.first_name == 'Bob'
Parameters:
  • *args (List[Any]) – Positional values to use for Field values of value object
  • (Dict[str (**kwargs) – Any]): Keyword arguments to use for Field values of value object
class graphene.InputObjectType(*args, **kwargs)[source]

Input Object Type Definition

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

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

All class attributes of graphene.InputObjectType are implicitly mounted as InputField using the below Meta class options.

from graphene import InputObjectType, String, InputField

class Person(InputObjectType):
    # implicitly mounted as Input Field
    first_name = String(required=True)
    # explicitly mounted as Input Field
    last_name = InputField(String, description="Surname")

The fields on an input object type can themselves refer to input object types, but you can’t mix input and output types in your schema.

Meta class options (optional):
name (str): the name of the GraphQL type (must be unique in schema). Defaults to class
name.
description (str): the description of the GraphQL type in the schema. Defaults to class
docstring.
container (class): A class reference for a value object that allows for
attribute initialization and access. Default InputObjectTypeContainer.
fields (Dict[str, graphene.InputField]): Dictionary of field name to InputField. Not
recommended to use (prefer class attributes).
class graphene.Mutation → None[source]

Object Type Definition (mutation field)

Mutation is a convenience type that helps us build a Field which takes Arguments and returns a mutation Output ObjectType.

import graphene

class CreatePerson(graphene.Mutation):
    class Arguments:
        name = graphene.String()

    ok = graphene.Boolean()
    person = graphene.Field(Person)

    def mutate(parent, info, name):
        person = Person(name=name)
        ok = True
        return CreatePerson(person=person, ok=ok)

class Mutation(graphene.ObjectType):
    create_person = CreatePerson.Field()
Meta class options (optional):
output (graphene.ObjectType): Or Output inner class with attributes on Mutation class.
Or attributes from Mutation class. Fields which can be returned from this mutation field.
resolver (Callable resolver method): Or mutate method on Mutation class. Perform data
change and return output.
arguments (Dict[str, graphene.Argument]): Or Arguments inner class with attributes on
Mutation class. Arguments to use for the mutation Field.
name (str): Name of the GraphQL type (must be unique in schema). Defaults to class
name.
description (str): Description of the GraphQL type in the schema. Defaults to class
docstring.
interfaces (Iterable[graphene.Interface]): GraphQL interfaces to extend with the payload
object. All fields from interface will be included in this object’s schema.
fields (Dict[str, graphene.Field]): Dictionary of field name to Field. Not recommended to
use (prefer class attributes or Meta.output).
classmethod Field(name=None, description=None, deprecation_reason=None, required=False)[source]

Mount instance of mutation Field.

Fields (Mounted Types)

class graphene.Field(type_, args=None, resolver=None, source=None, deprecation_reason=None, name=None, description=None, required=False, _creation_counter=None, default_value=None, **extra_args)[source]

Makes a field available on an ObjectType in the GraphQL schema. Any type can be mounted as a Field:

  • Object Type
  • Scalar Type
  • Enum
  • Interface
  • Union

All class attributes of graphene.ObjectType are implicitly mounted as Field using the below arguments.

class Person(ObjectType):
    first_name = graphene.String(required=True)                # implicitly mounted as Field
    last_name = graphene.Field(String, description='Surname')  # explicitly mounted as Field
Parameters:
  • type (class for a graphene.UnmountedType) – Must be a class (not an instance) of an unmounted graphene type (ex. scalar or object) which is used for the type of this field in the GraphQL schema.
  • args (optional, Dict[str, graphene.Argument]) – Arguments that can be input to the field. Prefer to use **extra_args, unless you use an argument name that clashes with one of the Field arguments presented here (see example).
  • resolver (optional, Callable) – A function to get the value for a Field from the parent value object. If not set, the default resolver method for the schema is used.
  • source (optional, str) – attribute name to resolve for this field from the parent value object. Alternative to resolver (cannot set both source and resolver).
  • deprecation_reason (optional, str) – Setting this value indicates that the field is depreciated and may provide instruction or reason on how for clients to proceed.
  • required (optional, bool) – indicates this field as not null in the graphql schema. Same behavior as graphene.NonNull. Default False.
  • name (optional, str) – the name of the GraphQL field (must be unique in a type). Defaults to attribute name.
  • description (optional, str) – the description of the GraphQL field in the schema.
  • default_value (optional, Any) – Default value to resolve if none set from schema.
  • **extra_args (optional, Dict[str, Union[graphene.Argument, graphene.UnmountedType]) – any additional arguments to mount on the field.
class graphene.Argument(type_, default_value=Undefined, deprecation_reason=None, description=None, name=None, required=False, _creation_counter=None)[source]

Makes an Argument available on a Field in the GraphQL schema.

Arguments will be parsed and provided to resolver methods for fields as keyword arguments.

All arg and **extra_args for a graphene.Field are implicitly mounted as Argument using the below parameters.

from graphene import String, Boolean, Argument

age = String(
    # Boolean implicitly mounted as Argument
    dog_years=Boolean(description="convert to dog years"),
    # Boolean explicitly mounted as Argument
    decades=Argument(Boolean, default_value=False),
)
Parameters:
  • type (class for a graphene.UnmountedType) – must be a class (not an instance) of an unmounted graphene type (ex. scalar or object) which is used for the type of this argument in the GraphQL schema.
  • required (optional, bool) – indicates this argument as not null in the graphql schema. Same behavior as graphene.NonNull. Default False.
  • name (optional, str) – the name of the GraphQL argument. Defaults to parameter name.
  • description (optional, str) – the description of the GraphQL argument in the schema.
  • default_value (optional, Any) – The value to be provided if the user does not set this argument in the operation.
  • deprecation_reason (optional, str) – Setting this value indicates that the argument is depreciated and may provide instruction or reason on how for clients to proceed. Cannot be set if the argument is required (see spec).
class graphene.InputField(type_, name=None, default_value=Undefined, deprecation_reason=None, description=None, required=False, _creation_counter=None, **extra_args)[source]

Makes a field available on an ObjectType in the GraphQL schema. Any type can be mounted as a Input Field except Interface and Union:

  • Object Type
  • Scalar Type
  • Enum

Input object types also can’t have arguments on their input fields, unlike regular graphene.Field.

All class attributes of graphene.InputObjectType are implicitly mounted as InputField using the below arguments.

from graphene import InputObjectType, String, InputField

class Person(InputObjectType):
    # implicitly mounted as Input Field
    first_name = String(required=True)
    # explicitly mounted as Input Field
    last_name = InputField(String, description="Surname")
Parameters:
  • type (class for a graphene.UnmountedType) – Must be a class (not an instance) of an unmounted graphene type (ex. scalar or object) which is used for the type of this field in the GraphQL schema.
  • name (optional, str) – Name of the GraphQL input field (must be unique in a type). Defaults to attribute name.
  • default_value (optional, Any) – Default value to use as input if none set in user operation ( query, mutation, etc.).
  • deprecation_reason (optional, str) – Setting this value indicates that the field is depreciated and may provide instruction or reason on how for clients to proceed.
  • description (optional, str) – Description of the GraphQL field in the schema.
  • required (optional, bool) – Indicates this input field as not null in the graphql schema. Raises a validation error if argument not provided. Same behavior as graphene.NonNull. Default False.
  • **extra_args (optional, Dict) – Not used.

Fields (Unmounted Types)

class graphene.types.unmountedtype.UnmountedType(*args, **kwargs)[source]

This class acts a proxy for a Graphene Type, so it can be mounted dynamically as Field, InputField or Argument.

Instead of writing:

from graphene import ObjectType, Field, String

class MyObjectType(ObjectType):
    my_field = Field(String, description='Description here')

It lets you write:

from graphene import ObjectType, String

class MyObjectType(ObjectType):
    my_field = String(description='Description here')

It is not used directly, but is inherited by other types and streamlines their use in different context:

  • Object Type
  • Scalar Type
  • Enum
  • Interface
  • Union

An unmounted type will accept arguments based upon its context (ObjectType, Field or InputObjectType) and pass it on to the appropriate MountedType (Field, Argument or InputField).

See each Mounted type reference for more information about valid parameters.

GraphQL Scalars

class graphene.Int[source]

The Int scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^53 - 1) and 2^53 - 1 since represented in JSON as double-precision floating point numbers specified by [IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point).

class graphene.Float[source]

The Float scalar type represents signed double-precision fractional values as specified by [IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point).

class graphene.String[source]

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

class graphene.Boolean[source]

The Boolean scalar type represents true or false.

class graphene.ID[source]

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

Graphene Scalars

class graphene.Date[source]

The Date scalar type represents a Date value as specified by [iso8601](https://en.wikipedia.org/wiki/ISO_8601).

class graphene.DateTime[source]

The DateTime scalar type represents a DateTime value as specified by [iso8601](https://en.wikipedia.org/wiki/ISO_8601).

class graphene.Time[source]

The Time scalar type represents a Time value as specified by [iso8601](https://en.wikipedia.org/wiki/ISO_8601).

class graphene.Decimal[source]

The Decimal scalar type represents a python Decimal.

class graphene.UUID[source]

Leverages the internal Python implementation of UUID (uuid.UUID) to provide native UUID objects in fields, resolvers and input.

class graphene.JSONString[source]

Allows use of a JSON String for input / output from the GraphQL schema.

Use of this type is not recommended as you lose the benefits of having a defined, static schema (one of the key benefits of GraphQL).

class graphene.Base64[source]

The Base64 scalar type represents a base64-encoded String.

Enum

class graphene.Enum[source]

Enum type definition

Defines a static set of values that can be provided as a Field, Argument or InputField.

from graphene import Enum

class NameFormat(Enum):
    FIRST_LAST = "first_last"
    LAST_FIRST = "last_first"
Meta:

enum (optional, Enum): Python enum to use as a base for GraphQL Enum.

name (optional, str): Name of the GraphQL type (must be unique in schema). Defaults to class
name.
description (optional, str): Description of the GraphQL type in the schema. Defaults to class
docstring.
deprecation_reason (optional, str): Setting this value indicates that the enum is
depreciated and may provide instruction or reason on how for clients to proceed.

Structures

class graphene.List(of_type, *args, **kwargs)[source]

List Modifier

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

List indicates that many values will be returned (or input) for this field.

from graphene import List, String

field_name = List(String, description="There will be many values")
class graphene.NonNull(*args, **kwargs)[source]

Non-Null Modifier

A non-null is a kind of type marker, 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.

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

NonNull can also be indicated on all Mounted types with the keyword argument required.

from graphene import NonNull, String

field_name = NonNull(String, description='This field will not be null')
another_field = String(required=True, description='This is equivalent to the above')

Type Extension

class graphene.Interface[source]

Interface Type Definition

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

from graphene import Interface, String

class HasAddress(Interface):
    class Meta:
        description = "Address fields"

    address1 = String()
    address2 = String()

If a field returns an Interface Type, the ambiguous type of the object can be determined using resolve_type on Interface and an ObjectType with Meta.possible_types or is_type_of.

Meta:
name (str): Name of the GraphQL type (must be unique in schema). Defaults to class
name.
description (str): Description of the GraphQL type in the schema. Defaults to class
docstring.
fields (Dict[str, graphene.Field]): Dictionary of field name to Field. Not recommended to
use (prefer class attributes).
class graphene.Union[source]

Union Type Definition

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

The schema in this example can take a search text and return any of the GraphQL object types indicated: Human, Droid or Starship.

Ambiguous return types can be resolved on each ObjectType through Meta.possible_types attribute or is_type_of method. Or by implementing resolve_type class method on the Union.

from graphene import Union, ObjectType, List

class SearchResult(Union):
    class Meta:
        types = (Human, Droid, Starship)

class Query(ObjectType):
    search = List(SearchResult.Field(
        search_text=String(description='Value to search for'))
    )
Meta:
types (Iterable[graphene.ObjectType]): Required. Collection of types that may be returned
by this Union for the graphQL schema.
name (optional, str): the name of the GraphQL type (must be unique in schema). Defaults to class
name.
description (optional, str): the description of the GraphQL type in the schema. Defaults to class
docstring.

Execution Metadata

graphene.ResolveInfo

alias of GraphQLResolveInfo

class graphene.Context(**params)[source]

Context can be used to make a convenient container for attributes to provide for execution for resolvers of a GraphQL operation like a query.

from graphene import Context

context = Context(loaders=build_dataloaders(), request=my_web_request)
schema.execute('{ hello(name: "world") }', context=context)

def resolve_hello(parent, info, name):
    info.context.request  # value set in Context
    info.context.loaders  # value set in Context
    # ...
Parameters:**params (Dict[str, Any]) – values to make available on Context instance as attributes.