GraphQL Examples: Real-World Code Samples

Practical GraphQL examples you can copy and use in your projects

Published: January 2025 • 15 min read

Learning GraphQL is best done through practical examples. This guide provides real-world code samples covering everything from basic queries to advanced patterns. Each example is production-ready and can be adapted to your needs.

Use our GraphQL formatter to beautify these examples, and our schema validator to check your schemas. For more fundamentals, check our What is GraphQL guide.

Examples Covered

Schema Examples:

  • • Basic Type Definitions
  • • Complex Relationships
  • • Custom Scalars
  • • Interfaces & Unions

Query Examples:

  • • Simple Queries
  • • Nested Queries
  • • Query Variables
  • • Fragments

Mutation Examples:

  • • Creating Data
  • • Updating Data
  • • Deleting Data
  • • Batch Operations

Advanced Examples:

  • • Subscriptions
  • • Pagination
  • • Error Handling
  • • Full-Stack Setup

Schema Examples

1. Basic E-commerce Schema

A simple online store with products, users, and orders:

type Product {
  id: ID!
  name: String!
  description: String
  price: Float!
  inStock: Boolean!
  category: Category!
  reviews: [Review!]!
}

type Category {
  id: ID!
  name: String!
  products: [Product!]!
}

type User {
  id: ID!
  email: String!
  name: String!
  orders: [Order!]!
  cart: [CartItem!]!
}

type Order {
  id: ID!
  user: User!
  items: [OrderItem!]!
  total: Float!
  status: OrderStatus!
  createdAt: String!
}

type OrderItem {
  product: Product!
  quantity: Int!
  price: Float!
}

enum OrderStatus {
  PENDING
  PROCESSING
  SHIPPED
  DELIVERED
  CANCELLED
}

type Query {
  product(id: ID!): Product
  products(category: ID, inStock: Boolean): [Product!]!
  user(id: ID!): User
  order(id: ID!): Order
}

2. Social Media Schema with Interfaces

Using interfaces for polymorphic content types:

interface Content {
  id: ID!
  author: User!
  createdAt: String!
  likes: Int!
}

type Post implements Content {
  id: ID!
  author: User!
  createdAt: String!
  likes: Int!
  title: String!
  body: String!
  comments: [Comment!]!
}

type Video implements Content {
  id: ID!
  author: User!
  createdAt: String!
  likes: Int!
  title: String!
  url: String!
  duration: Int!
  views: Int!
}

type Image implements Content {
  id: ID!
  author: User!
  createdAt: String!
  likes: Int!
  url: String!
  caption: String
  tags: [String!]!
}

type User {
  id: ID!
  username: String!
  avatar: String
  followers: [User!]!
  following: [User!]!
  content: [Content!]!
}

type Query {
  feed: [Content!]!
  user(username: String!): User
}

3. Custom Scalars Example

Using custom scalar types for validation:

scalar DateTime
scalar Email
scalar URL
scalar JSON

type User {
  id: ID!
  email: Email!
  createdAt: DateTime!
  profile: JSON
  website: URL
}

type Event {
  id: ID!
  title: String!
  startTime: DateTime!
  endTime: DateTime!
  location: JSON
}

Query Examples

4. Simple Product Query

query GetProduct {
  product(id: "123") {
    name
    price
    inStock
    category {
      name
    }
  }
}

Returns only the fields you specify - no over-fetching!

5. Nested Query with Multiple Levels

query GetUserWithOrders {
  user(id: "456") {
    name
    email
    orders {
      id
      total
      status
      items {
        product {
          name
          price
        }
        quantity
      }
    }
  }
}

One request replaces 3+ REST API calls!

6. Query with Variables

Query:

query GetProducts(
  $category: ID
  $inStock: Boolean
  $limit: Int
) {
  products(
    category: $category
    inStock: $inStock
    limit: $limit
  ) {
    id
    name
    price
  }
}

Variables:

{
  "category": "electronics",
  "inStock": true,
  "limit": 10
}

7. Using Fragments for Reusability

fragment UserInfo on User {
  id
  name
  email
  avatar
}

fragment ProductDetails on Product {
  id
  name
  price
  category {
    name
  }
}

query GetOrderDetails {
  order(id: "789") {
    id
    user {
      ...UserInfo
    }
    items {
      product {
        ...ProductDetails
      }
      quantity
    }
  }
}

8. Aliases for Multiple Queries

query CompareProducts {
  product1: product(id: "123") {
    name
    price
    reviews {
      rating
    }
  }
  product2: product(id: "456") {
    name
    price
    reviews {
      rating
    }
  }
}

Query the same field multiple times with different arguments

Mutation Examples

9. Creating a New Product

mutation CreateProduct($input: ProductInput!) {
  createProduct(input: $input) {
    id
    name
    price
    createdAt
  }
}

# Variables
{
  "input": {
    "name": "Wireless Headphones",
    "description": "Noise-cancelling Bluetooth headphones",
    "price": 199.99,
    "categoryId": "electronics",
    "inStock": true
  }
}

10. Updating User Profile

mutation UpdateUser($id: ID!, $input: UserUpdateInput!) {
  updateUser(id: $id, input: $input) {
    id
    name
    email
    updatedAt
  }
}

# Variables
{
  "id": "user123",
  "input": {
    "name": "Jane Doe",
    "avatar": "https://example.com/avatar.jpg"
  }
}

11. Delete with Confirmation

mutation DeleteProduct($id: ID!) {
  deleteProduct(id: $id) {
    success
    message
    deletedId
  }
}

# Variables
{
  "id": "product789"
}

For more on mutations, check our detailed GraphQL Mutations guide.

Advanced Examples

12. Pagination with Cursor-Based Approach

type ProductConnection {
  edges: [ProductEdge!]!
  pageInfo: PageInfo!
}

type ProductEdge {
  node: Product!
  cursor: String!
}

type PageInfo {
  hasNextPage: Boolean!
  hasPreviousPage: Boolean!
  startCursor: String
  endCursor: String
}

type Query {
  products(first: Int, after: String): ProductConnection!
}

# Query with pagination
query GetProducts($first: Int!, $after: String) {
  products(first: $first, after: $after) {
    edges {
      node {
        id
        name
        price
      }
      cursor
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}

13. Real-time Subscriptions

type Subscription {
  messageAdded(chatId: ID!): Message!
  orderStatusChanged(userId: ID!): Order!
  productPriceChanged(productId: ID!): Product!
}

# Subscribe to new messages
subscription OnNewMessage($chatId: ID!) {
  messageAdded(chatId: $chatId) {
    id
    text
    author {
      name
      avatar
    }
    createdAt
  }
}

14. Error Handling

type MutationResponse {
  success: Boolean!
  message: String
  errors: [Error!]
}

type Error {
  field: String
  message: String!
}

type CreateProductResponse implements MutationResponse {
  success: Boolean!
  message: String
  errors: [Error!]
  product: Product
}

mutation CreateProduct($input: ProductInput!) {
  createProduct(input: $input) {
    success
    message
    errors {
      field
      message
    }
    product {
      id
      name
    }
  }
}

15. Complete Node.js Server Example

Here's a complete working GraphQL server with Apollo Server:

const { ApolloServer, gql } = require('apollo-server');

// Schema definition
const typeDefs = gql`
  type Book {
    id: ID!
    title: String!
    author: Author!
  }

  type Author {
    id: ID!
    name: String!
    books: [Book!]!
  }

  type Query {
    books: [Book!]!
    book(id: ID!): Book
    authors: [Author!]!
  }

  type Mutation {
    addBook(title: String!, authorId: ID!): Book!
  }
`;

// Sample data
const books = [
  { id: '1', title: '1984', authorId: '1' },
  { id: '2', title: 'Animal Farm', authorId: '1' },
];

const authors = [
  { id: '1', name: 'George Orwell' },
];

// Resolvers
const resolvers = {
  Query: {
    books: () => books,
    book: (parent, { id }) => books.find(book => book.id === id),
    authors: () => authors,
  },
  Mutation: {
    addBook: (parent, { title, authorId }) => {
      const book = {
        id: String(books.length + 1),
        title,
        authorId,
      };
      books.push(book);
      return book;
    },
  },
  Book: {
    author: (parent) => authors.find(author => author.id === parent.authorId),
  },
  Author: {
    books: (parent) => books.filter(book => book.authorId === parent.id),
  },
};

// Server setup
const server = new ApolloServer({ typeDefs, resolvers });

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});

💡 Tip: Run this code with Node.js and visit http://localhost:4000 to access the GraphQL Playground!

Best Practices for GraphQL

✅ Always Name Your Queries

Named queries are easier to debug and monitor in production.

✅ Use Fragments

Keep your queries DRY and maintainable with reusable fragments.

✅ Leverage Variables

Use variables instead of string interpolation for security.

✅ Handle Errors Properly

Always check both data and errors in responses.

✅ Implement Pagination

Use cursor-based pagination for large datasets.

✅ Validate Schema

Use our schema validator regularly.

GraphQL Development Tools

Related GraphQL Guides

External Resources

Official Documentation

Example Repositories