Skip to main content

Command Palette

Search for a command to run...

Graphene Python: Lesson 1

Published
3 min read

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:

  1. Define Schema: Query is a root schema class with one field, hello.

  2. Field Resolution: resolve_hello defines how the hello field is computed.

  3. Execution: A query '{ hello }' fetches the hello field.

  4. 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:

  1. Arguments: The greet field accepts a name argument.

  2. Default Value: If no name is provided, it defaults to "World".

  3. Dynamic Response: resolve_greet returns a personalized greeting.

  4. 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:

  1. ObjectType: User defines a reusable GraphQL type with id and name.

  2. Field Composition: user is a field in Query that resolves to a User.

  3. Nested Queries: GraphQL allows querying nested fields like user { id name }.

  4. 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:

  1. Lists: items field returns a list of Item objects.

  2. Data Handling: The resolver returns multiple objects.

  3. Structured Querying: You can query items { name } to get all names.

  4. 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:

  1. Mutations: Define CreateUser to handle changes like creating a user.

  2. Arguments: Accepts name for the new user.

  3. Result: Returns the created user and status (ok).

  4. Output: Outputs {"createUser": {"user": {"id": 2, "name": "Jane Doe"}, "ok": true}}.


These examples demonstrate Graphene’s flexibility for building GraphQL APIs with Python.

graphene python

Part 1 of 1

More from this blog

Programming , Big Data, DevOps, etc

271 posts

Programming , Big Data, DevOps, etc