An Interface is an abstract type that defines a set of fields that implementing types must include. To create an interface, inherit from graphene.Interface. To implement an interface in an ObjectType, include the interface in the interfaces tuple within the Meta inner class.
Implementing an interface allows you to return different object types from a single field, provided they all satisfy the interface's field requirements. You can query interface fields directly or use inline fragments (... on TypeName) to access type-specific fields.
import graphene
# 1. Define the Interface
class Character(graphene.Interface):
id = graphene.ID(required=True)
name = graphene.String(required=True)
friends = graphene.List(lambda: Character)
# 2. Implement the Interface in ObjectTypes
class Human(graphene.ObjectType):
class Meta:
interfaces = (Character,)
starships = graphene.List(Starship)
home_planet = graphene.String()
class Droid(graphene.ObjectType):
class Meta:
interfaces = (Character,)
primary_function = graphene.String()
# 3. Use the Interface in a Query
class Query(graphene.ObjectType):
hero = graphene.Field(Character, required=True, episode=graphene.Int(required=True))
def resolve_hero(root, info, episode):
if episode == 5:
return get_human(name='Luke Skywalker')
return get_droid(name='R2-D2')
schema = graphene.Schema(query=Query, types=[Human, Droid])