0
0
GraphQLquery~5 mins

Node interface pattern in GraphQL

Choose your learning style9 modes available
Introduction

The Node interface pattern helps us fetch any object by its unique ID in a simple way.

When you want to get different types of data (like users, posts, or comments) using one query.
When building apps that need to load data quickly by ID.
When you want a consistent way to fetch any item in your system.
When you want to make your API easier to use and understand.
When you want to support pagination and caching efficiently.
Syntax
GraphQL
interface Node {
  id: ID!
}

type User implements Node {
  id: ID!
  name: String!
}

type Post implements Node {
  id: ID!
  title: String!
}

# Query to fetch any Node by id
 type Query {
  node(id: ID!): Node
}

The Node interface requires an id field that is unique.

Types like User and Post implement Node to share this ID field.

Examples
This defines the Node interface with a required unique ID.
GraphQL
interface Node {
  id: ID!
}
User type implements Node and adds a name field.
GraphQL
type User implements Node {
  id: ID!
  name: String!
}
Query to get any Node by its ID.
GraphQL
type Query {
  node(id: ID!): Node
}
Sample Program

This example shows the Node interface with User and Post types. The query fetches a node by ID and uses fragments to get fields based on the actual type.

GraphQL
interface Node {
  id: ID!
}

type User implements Node {
  id: ID!
  name: String!
}

type Post implements Node {
  id: ID!
  title: String!
}

type Query {
  node(id: ID!): Node
}

# Sample query
# {
#   node(id: "1") {
#     id
#     ... on User {
#       name
#     }
#     ... on Post {
#       title
#     }
#   }
# }

# Sample response for node with id "1" being a User
# {
#   "data": {
#     "node": {
#       "id": "1",
#       "name": "Alice"
#     }
#   }
# }
OutputSuccess
Important Notes

Use fragments (... on TypeName) to get fields specific to each type.

The id field must be unique across all types implementing Node.

This pattern helps clients fetch any object with one query, simplifying API design.

Summary

The Node interface defines a unique ID for all types.

It allows fetching any object by ID using one query.

Use fragments to get type-specific fields when querying a Node.