Relay library for graphql-core

3.2.0 · active · verified Sun Mar 29

graphql-relay-py is the Python port of the JavaScript Relay library for GraphQL, designed to facilitate the creation of Relay-compliant GraphQL servers using graphql-core. It provides utilities for global object identification (Nodes) and cursor-based pagination (Connections). The library maintains a regular release cadence, often aligning with updates to graphql-core and the upstream graphql-relay-js specification. The current version is 3.2.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a basic Relay-compliant GraphQL schema using `graphql-relay` with `graphene`. It includes defining a Node interface for global object identification and a Connection for pagination. It showcases `node_definitions`, `global_id_field`, `connection_definitions`, `connection_from_array`, and `connection_args`.

import graphene
from graphql.execution.execute import execute
from graphql.language.parser import parse
from graphql_relay import node_definitions, global_id_field, connection_definitions, connection_from_array, connection_args, from_global_id

class User:
    def __init__(self, id, name):
        self.id = id
        self.name = name

users_data = {
    "1": User("1", "Alice"),
    "2": User("2", "Bob"),
}

def get_user(id):
    return users_data.get(id)

def get_object_from_global_id(global_id, info):
    type_name, id = from_global_id(global_id)
    if type_name == 'User':
        return get_user(id)
    return None

node_interface, node_field = node_definitions(
    get_object_from_global_id, lambda obj, info: UserNode if isinstance(obj, User) else None
)

class UserNode(graphene.ObjectType):
    class Meta:
        name = 'User'
        interfaces = (node_interface,)

    id = global_id_field('User')
    name = graphene.String()

UserConnection = connection_definitions(UserNode, 'UserConnection').connection_type

class Query(graphene.ObjectType):
    node = node_field
    users = graphene.Field(
        UserConnection,
        args=connection_args,
        resolve=lambda obj, info, **args:
            connection_from_array(list(users_data.values()), args)
    )

schema = graphene.Schema(query=Query)

# Example Usage:
query_str = '''
    query {
      users (first: 1) {
        edges {
          node {
            id
            name
          }
        }
      }
      node(id: "VXNlcjox") {
        id
        ... on User {
          name
        }
      }
    }
'''

# Assuming "VXNlcjox" is the global ID for User:1 (to_global_id('User', '1'))
# Use 'User:1' -> base64 -> 'VXNlcjox'

result = execute(schema, parse(query_str))
print(result.data)

view raw JSON →