Graphene Python: Lesson 1
Graphene Python: Lesson 1
Graphene is a Python library for building GraphQL APIs quickly and efficiently. Below are 5 examples with explanations:
1. Basic GraphQL Schema Definition
import graphene
class Query(graphene.ObjectType):
hello = graphene.String()
def resolve_hello(root, info):
return "Hello, GraphQL!"
schema = graphene.Schema(query=Query)
query_string = '{ hello }'
result = schema.execute(query_string)
print(result.data)
Explanation:
Define Schema:
Queryis a root schema class with one field,hello.Field Resolution:
resolve_hellodefines how thehellofield is computed.Execution: A query
'{ hello }'fetches thehellofield.Output: Returns
{"hello": "Hello, GraphQL!"}as data.
2. Adding Arguments to a Field
import graphene
class Query(graphene.ObjectType):
greet = graphene.String(name=graphene.String(default_value="World"))
def resolve_greet(root, info, name):
return f"Hello, {name}!"
schema = graphene.Schema(query=Query)
query_string = '{ greet(name: "Alice") }'
result = schema.execute(query_string)
print(result.data)
Explanation:
Arguments: The
greetfield accepts anameargument.Default Value: If no name is provided, it defaults to "World".
Dynamic Response:
resolve_greetreturns a personalized greeting.Output: Query with
name: "Alice"outputs{"greet": "Hello, Alice!"}.
3. Using ObjectType to Structure Data
import graphene
class User(graphene.ObjectType):
id = graphene.Int()
name = graphene.String()
class Query(graphene.ObjectType):
user = graphene.Field(User)
def resolve_user(root, info):
return User(id=1, name="John Doe")
schema = graphene.Schema(query=Query)
query_string = '{ user { id name } }'
result = schema.execute(query_string)
print(result.data)
Explanation:
ObjectType:
Userdefines a reusable GraphQL type withidandname.Field Composition:
useris a field inQuerythat resolves to aUser.Nested Queries: GraphQL allows querying nested fields like
user { id name }.Output: Returns user data as
{"user": {"id": 1, "name": "John Doe"}}.
4. Using Lists in GraphQL
import graphene
class Item(graphene.ObjectType):
name = graphene.String()
class Query(graphene.ObjectType):
items = graphene.List(Item)
def resolve_items(root, info):
return [Item(name="Apple"), Item(name="Banana")]
schema = graphene.Schema(query=Query)
query_string = '{ items { name } }'
result = schema.execute(query_string)
print(result.data)
Explanation:
Lists:
itemsfield returns a list ofItemobjects.Data Handling: The resolver returns multiple objects.
Structured Querying: You can query
items { name }to get all names.Output: Outputs
{"items": [{"name": "Apple"}, {"name": "Banana"}]}.
5. Mutations for Data Changes
import graphene
class CreateUser(graphene.Mutation):
class Arguments:
name = graphene.String()
ok = graphene.Boolean()
user = graphene.Field(lambda: User)
def mutate(root, info, name):
user = User(id=2, name=name)
return CreateUser(user=user, ok=True)
class User(graphene.ObjectType):
id = graphene.Int()
name = graphene.String()
class Mutation(graphene.ObjectType):
create_user = CreateUser.Field()
schema = graphene.Schema(mutation=Mutation)
mutation_string = 'mutation { createUser(name: "Jane Doe") { user { id name } ok } }'
result = schema.execute(mutation_string)
print(result.data)
Explanation:
Mutations: Define
CreateUserto handle changes like creating a user.Arguments: Accepts
namefor the new user.Result: Returns the created user and status (
ok).Output: Outputs
{"createUser": {"user": {"id": 2, "name": "Jane Doe"}, "ok": true}}.
These examples demonstrate Graphene’s flexibility for building GraphQL APIs with Python.