Skip to content

GraphQL Examples

Comprehensive code examples for using HeliosDB's GraphQL API.

Basic Queries

Simple Query

query GetUsers {
  users(limit: 10) {
    id
    name
    email
    created_at
  }
}

Query with Variables

query GetUser($id: Int!) {
  users_by_pk(id: $id) {
    id
    name
    email
    profile {
      bio
      avatar_url
    }
  }
}

Variables:

{
  "id": 123
}

Query with Filtering

query ActiveUsers {
  users(
    where: {
      status: { _eq: "active" },
      created_at: { _gt: "2024-01-01" }
    },
    order_by: { created_at: desc },
    limit: 20
  ) {
    id
    name
    email
  }
}

Complex Filtering

query SearchUsers($search: String!, $statuses: [String!]!) {
  users(
    where: {
      _and: [
        { _or: [
          { name: { _ilike: $search } },
          { email: { _ilike: $search } }
        ]},
        { status: { _in: $statuses } }
      ]
    }
  ) {
    id
    name
    email
    status
  }
}

Relationships

One-to-Many

query UsersWithOrders {
  users(limit: 10) {
    id
    name
    orders(order_by: { created_at: desc }, limit: 5) {
      id
      total
      status
      created_at
    }
  }
}

Many-to-Many

query ProductsWithCategories {
  products(limit: 10) {
    id
    name
    price
    product_categories {
      category {
        id
        name
      }
    }
  }
}

Nested Relationships

query OrderDetails($orderId: Int!) {
  orders_by_pk(id: $orderId) {
    id
    total
    status
    user {
      id
      name
      email
    }
    order_items {
      quantity
      price
      product {
        id
        name
        description
      }
    }
  }
}

Aggregations

Basic Aggregation

query UserStats {
  users_aggregate {
    aggregate {
      count
    }
  }
}

Aggregation with Grouping

query OrdersByStatus {
  orders_aggregate(
    where: { created_at: { _gt: "2024-01-01" } }
  ) {
    aggregate {
      count
      sum { total }
      avg { total }
    }
  }
}

Aggregation with Nested Data

query UsersWithOrderStats {
  users(limit: 10) {
    id
    name
    orders_aggregate {
      aggregate {
        count
        sum { total }
      }
    }
  }
}

Mutations

Insert Single Record

mutation CreateUser($input: users_insert_input!) {
  insert_users_one(object: $input) {
    id
    name
    email
    created_at
  }
}

Variables:

{
  "input": {
    "name": "Alice",
    "email": "alice@example.com",
    "status": "active"
  }
}

Insert Multiple Records

mutation CreateUsers($inputs: [users_insert_input!]!) {
  insert_users(objects: $inputs) {
    affected_rows
    returning {
      id
      name
    }
  }
}

Update Records

mutation UpdateUserStatus($id: Int!, $status: String!) {
  update_users_by_pk(
    pk_columns: { id: $id },
    _set: { status: $status, updated_at: "now()" }
  ) {
    id
    status
    updated_at
  }
}

Upsert (Insert or Update)

mutation UpsertUser($user: users_insert_input!) {
  insert_users_one(
    object: $user,
    on_conflict: {
      constraint: users_email_key,
      update_columns: [name, updated_at]
    }
  ) {
    id
    name
    email
  }
}

Delete Records

mutation DeleteUser($id: Int!) {
  delete_users_by_pk(id: $id) {
    id
    name
  }
}

Bulk Delete

mutation DeleteInactiveUsers {
  delete_users(
    where: {
      status: { _eq: "inactive" },
      last_login: { _lt: "2023-01-01" }
    }
  ) {
    affected_rows
  }
}

Subscriptions

Basic Subscription

subscription WatchNewOrders {
  orders(
    where: { status: { _eq: "pending" } },
    order_by: { created_at: desc },
    limit: 10
  ) {
    id
    total
    status
    created_at
    user {
      name
    }
  }
}

Subscription with Variables

subscription WatchUserOrders($userId: Int!) {
  orders(
    where: { user_id: { _eq: $userId } },
    order_by: { created_at: desc }
  ) {
    id
    total
    status
    created_at
  }
}

Client Examples

JavaScript (Apollo Client)

import { ApolloClient, InMemoryCache, gql, split, HttpLink } from '@apollo/client';
import { WebSocketLink } from '@apollo/client/link/ws';
import { getMainDefinition } from '@apollo/client/utilities';

// HTTP link for queries and mutations
const httpLink = new HttpLink({
  uri: 'https://localhost:443/graphql',
  headers: {
    Authorization: 'Bearer YOUR_API_KEY'
  }
});

// WebSocket link for subscriptions
const wsLink = new WebSocketLink({
  uri: 'wss://localhost:443/graphql/ws',
  options: {
    reconnect: true,
    connectionParams: {
      authToken: 'YOUR_API_KEY'
    }
  }
});

// Split links based on operation type
const splitLink = split(
  ({ query }) => {
    const definition = getMainDefinition(query);
    return (
      definition.kind === 'OperationDefinition' &&
      definition.operation === 'subscription'
    );
  },
  wsLink,
  httpLink
);

const client = new ApolloClient({
  link: splitLink,
  cache: new InMemoryCache()
});

// Query
const { data } = await client.query({
  query: gql`
    query GetUsers {
      users(limit: 10) {
        id
        name
      }
    }
  `
});

// Mutation
const { data: mutationData } = await client.mutate({
  mutation: gql`
    mutation CreateUser($name: String!, $email: String!) {
      insert_users_one(object: { name: $name, email: $email }) {
        id
      }
    }
  `,
  variables: { name: 'Alice', email: 'alice@example.com' }
});

// Subscription
client.subscribe({
  query: gql`
    subscription WatchOrders {
      orders(limit: 10, order_by: { created_at: desc }) {
        id
        total
        status
      }
    }
  `
}).subscribe({
  next: (result) => console.log(result.data),
  error: (err) => console.error(err)
});

Python (gql)

from gql import gql, Client
from gql.transport.websockets import WebsocketsTransport
from gql.transport.requests import RequestsHTTPTransport

# HTTP client for queries/mutations
http_transport = RequestsHTTPTransport(
    url="https://localhost:443/graphql",
    headers={"Authorization": "Bearer YOUR_API_KEY"}
)
http_client = Client(transport=http_transport)

# Query
query = gql("""
    query GetUsers($limit: Int!) {
        users(limit: $limit) {
            id
            name
            email
        }
    }
""")
result = http_client.execute(query, variable_values={"limit": 10})
print(result["users"])

# Mutation
mutation = gql("""
    mutation CreateUser($name: String!, $email: String!) {
        insert_users_one(object: { name: $name, email: $email }) {
            id
            name
        }
    }
""")
result = http_client.execute(mutation, variable_values={
    "name": "Alice",
    "email": "alice@example.com"
})
print(result["insert_users_one"])

# WebSocket client for subscriptions
ws_transport = WebsocketsTransport(
    url="wss://localhost:443/graphql/ws",
    headers={"Authorization": "Bearer YOUR_API_KEY"}
)

async def subscribe_orders():
    async with Client(transport=ws_transport) as session:
        subscription = gql("""
            subscription WatchOrders {
                orders(limit: 10, order_by: { created_at: desc }) {
                    id
                    total
                }
            }
        """)
        async for result in session.subscribe(subscription):
            print(result)

Go (graphql-go)

package main

import (
    "context"
    "fmt"
    "github.com/machinebox/graphql"
)

func main() {
    client := graphql.NewClient("https://localhost:443/graphql")

    // Query
    req := graphql.NewRequest(`
        query GetUsers($limit: Int!) {
            users(limit: $limit) {
                id
                name
                email
            }
        }
    `)
    req.Var("limit", 10)
    req.Header.Set("Authorization", "Bearer YOUR_API_KEY")

    var response struct {
        Users []struct {
            ID    int    `json:"id"`
            Name  string `json:"name"`
            Email string `json:"email"`
        } `json:"users"`
    }

    if err := client.Run(context.Background(), req, &response); err != nil {
        panic(err)
    }

    for _, user := range response.Users {
        fmt.Printf("User: %s (%s)\n", user.Name, user.Email)
    }
}

Error Handling

try {
  const { data, errors } = await client.query({
    query: GET_USERS,
    errorPolicy: 'all'
  });

  if (errors) {
    errors.forEach(error => {
      console.error('GraphQL Error:', error.message);
      if (error.extensions) {
        console.error('Code:', error.extensions.code);
      }
    });
  }

  if (data) {
    // Process data
  }
} catch (networkError) {
  console.error('Network Error:', networkError);
}

Last Updated: January 2026