Up to this point, I have discussed implementing both ObjectTypes and Resolvers. These are concrete, specific pillars of any GraphQL implementation. Fields, on the other hand, are a generic reference to any given “thing” on a GraphQL type.
What does that mean exactly? Well let’s again consider my
Bucket class. example.
from graphene import ObjectType, String class Bucket(ObjectType): bucket_name = String() region = String()
Bucket class inherits
graphene, and it has a few class constants that are set as
Scalar types of
String. Or, at least, that is how we would describe it in Python.
In GraphQL, it would be more appropriate to say that the
ObjectType has two
Fields. And those fields are
Scalar types, which means they can’t have any sub-types, so they are termination points for the graph.
Implementing a Field
In addition to my
ObjectType, I have also already implemented a resolver named
resolve_bucket so that I can generate an instance of
Bucket when I need it.
def resolve_bucket( parent, info, bucket_name, region ): record = record_lookup(bucket_name, region) if record is None: return Bucket() else: return Bucket( bucket_name = record.bucket_name, region = record.region )
Both of these implementations, however, are lacking a means to reference each other. Said another way, how does Graphene know that it should use
resolve_bucket any time a
Bucket is needed? That is where Field comes in.
from graphene import Field _bucket = Field( type = Bucket, resolver = resolve_bucket, bucket_name = String(default_value=None) region = String(default_value=None) )
Again, there isn’t a lot going on here, but it is important to understand it. As the keywords should hopefully make clear, the
_bucket is now an interface for producing
Bucket. I assign a specific resolver to it, which in this case can accept two arguments – so in addition to the
type and the
resolver, I also declare those arguments in the Field.
What this means for Fields in GraphQL
While a “field” in GraphQL is a generic for several things, in Graphene
Field is both how an
ObjectType is made available on another type and also a mapping device that connects the type with the resolver.
Hopefully at this point it is feeling like our system is fairly well connected to eahc of its parts. But there is actually one final step before I can say my engine is prepped.
I need to be able to attach my
Field to a root level object, which will be called a schema.