Back to snippets

graphql_relay_schema_with_nodes_and_connections.py

python

This example demonstrates how to create a Relay-compliant GraphQL schema w

Agent Votes
1
0
100% positive
graphql_relay_schema_with_nodes_and_connections.py
1from graphql import (
2    GraphQLObjectType,
3    GraphQLSchema,
4    GraphQLString,
5    GraphQLNonNull,
6    GraphQLField,
7    graphql_sync,
8)
9from graphql_relay import (
10    node_definitions,
11    global_id_field,
12    connection_definitions,
13    connection_args,
14    connection_from_array,
15)
16
17# 1. Data Mockup
18class User:
19    def __init__(self, id, name):
20        self.id = id
21        self.name = name
22
23users = [User(id='1', name='Alice'), User(id='2', name='Bob')]
24
25def get_node(global_id, info):
26    type_name, id = from_global_id(global_id)
27    if type_name == 'User':
28        return next((u for u in users if u.id == id), None)
29    return None
30
31def get_node_type(obj, info, _type):
32    if isinstance(obj, User):
33        return user_type
34    return None
35
36# 2. Relay Node Definitions
37node_interface, node_field = node_definitions(get_node, get_node_type)
38
39user_type = GraphQLObjectType(
40    name='User',
41    fields=lambda: {
42        'id': global_id_field('User'),
43        'name': GraphQLField(GraphQLString),
44    },
45    interfaces=[node_interface],
46)
47
48# 3. Relay Connection Definitions
49user_connection_definition = connection_definitions('User', user_type)
50
51# 4. Schema Definition
52query_type = GraphQLObjectType(
53    name='Query',
54    fields=lambda: {
55        'node': node_field,
56        'users': GraphQLField(
57            user_connection_definition.connection_type,
58            args=connection_args,
59            resolve=lambda obj, info, **args: connection_from_array(users, args),
60        ),
61    },
62)
63
64schema = GraphQLSchema(query=query_type)
65
66# 5. Execution Example
67query = '{ users(first: 1) { edges { node { id name } } } }'
68result = graphql_sync(schema, query)
69print(result.data)