In GraphQL, an ObjectType is a basic primitive that represents a “thing you can query.”
In my example, I laid out that I needed the details of an S3 bucket. Logically, that implies that I also need something to represent an S3 bucket. So, in GraphQL, that means I need an `ObjectType`. And since Graphene is a reliably faithful implementation of GraphQL, it gives me an ObjectType to import.
So let’s implement our first `ObjectType`.
from graphene import ObjectType, String class Bucket(ObjectType): bucket_name = String() region = String()
An initial observation should probably be that the `bucket` ObjectType is just a Python `class` that is inheriting the `ObjectType` class and declaring some class constants. Oh, and there are some imports.
Turns out physics still works – this is just Python!
But I am also importing a `String` out of Graphene and assigning it to my class constants. Which is kinda weird, since Python has `str` as a builtin.
A quick sidestep into GraphQL Scalars
If you really want to get into it, you can read up on Scalars here.
As a basic programming concept, a scalar is the variable implementation definition – it’s what builds a `str`, puts it into memory, and tells the language how to validate it and what to do with it. In GraphQL, the only difference is that a `Scalar` operates on the framework/module level, not the language level.
It is our termination point in a GraphQL definition – when the graph paths (ie, GraphQL Fields) run out and we now need to return an actual value, we can’t use a builtin – we need a `Scalar` type.
If you are still curious, I’d examine how Graphene implements it and go from there.
What this means for ObjectTypes in GraphQL
So if we stitch it all together…
- I import `ObjectType` and `String` out of `graphene`
- I create a class named `Bucket` that inherits `ObjectType`
- I assign some class constants to `Bucket` and assign `String` scalars to them
On the surface, this implementation seems pretty straightforward. No `__init__` methods, no `super` invocations, really nothing to do at all. I’m letting that `ObjectType` parent do a lot of lifting for me.
But by now, you’ve probably had the thought… but wait… how does Graphene know how to assign a value to `bucket_name` and a `region` on a `Bucket` type?
That’s the right question, and why we end up needing resolvers.
Leave a Reply