GraphQL Examples

This guide provides practical GraphQL examples for Crane Ledger's API, covering common accounting workflows, data fetching patterns, and integration scenarios.

Getting Started Examples

Basic Organization Query

query GetOrganizationInfo {
  organization {
    id
    name
    baseCurrency {
      code
      name
      symbol
    }
    isRoot
    creditsRemaining
    createdAt
  }
}

Response:

{
  "data": {
    "organization": {
      "id": "org_1234567890abcdef",
      "name": "Acme Corporation",
      "baseCurrency": {
        "code": "USD",
        "name": "US Dollar",
        "symbol": "$"
      },
      "isRoot": true,
      "creditsRemaining": 1500,
      "createdAt": "2024-01-15T10:30:00Z"
    }
  }
}

Check Credit Balance

query GetCreditStatus {
  organization {
    creditBalance {
      creditsRemaining
      creditsTotal
      autoRechargeEnabled
    }
    creditPackages {
      packageType
      credits
      name
      priceUsd
    }
  }
}

Chart of Accounts Management

Create Complete Chart of Accounts

mutation SetupChartOfAccounts {
  # Asset accounts
  cash: createAccount(
    code: "1001"
    name: "Operating Cash"
    accountType: ASSET
    description: "Primary checking account"
  ) { id code name }

  accountsReceivable: createAccount(
    code: "1101"
    name: "Accounts Receivable"
    accountType: ASSET
    description: "Money owed by customers"
  ) { id code name }

  inventory: createAccount(
    code: "1201"
    name: "Inventory"
    accountType: ASSET
    description: "Value of goods held for sale"
  ) { id code name }

  # Liability accounts
  accountsPayable: createAccount(
    code: "2001"
    name: "Accounts Payable"
    accountType: LIABILITY
    description: "Money owed to vendors"
  ) { id code name }

  # Equity accounts
  ownersEquity: createAccount(
    code: "3001"
    name: "Owner's Equity"
    accountType: EQUITY
    description: "Owner's investment in the business"
  ) { id code name }

  retainedEarnings: createAccount(
    code: "3101"
    name: "Retained Earnings"
    accountType: EQUITY
    description: "Accumulated profits"
  ) { id code name }

  # Revenue accounts
  salesRevenue: createAccount(
    code: "4001"
    name: "Sales Revenue"
    accountType: REVENUE
    description: "Revenue from product sales"
  ) { id code name }

  serviceRevenue: createAccount(
    code: "4101"
    name: "Service Revenue"
    accountType: REVENUE
    description: "Revenue from services"
  ) { id code name }

  # Expense accounts
  costOfGoodsSold: createAccount(
    code: "5001"
    name: "Cost of Goods Sold"
    accountType: EXPENSE
    description: "Direct cost of products sold"
  ) { id code name }

  salariesExpense: createAccount(
    code: "5101"
    name: "Salaries Expense"
    accountType: EXPENSE
    description: "Employee salaries and wages"
  ) { id code name }

  rentExpense: createAccount(
    code: "5201"
    name: "Rent Expense"
    accountType: EXPENSE
    description: "Office and facility rent"
  ) { id code name }
}

Query Account Hierarchy

query GetChartOfAccounts {
  organization {
    accounts {
      id
      code
      name
      accountType
      parentAccountId
      status
      balance {
        formatted
      }
    }
  }
}

Transaction Management

Record Opening Balances

mutation RecordOpeningBalances {
  createTransaction(
    description: "Opening balances - January 1, 2024"
    date: "2024-01-01T00:00:00Z"
    entries: [
      # Cash in bank
      {
        accountId: "act_1001"
        entryType: DEBIT
        amount: 25000.00
        description: "Opening cash balance"
      }
      # Accounts receivable
      {
        accountId: "act_1101"
        entryType: DEBIT
        amount: 5000.00
        description: "Outstanding invoices"
      }
      # Inventory
      {
        accountId: "act_1201"
        entryType: DEBIT
        amount: 15000.00
        description: "Inventory value"
      }
      # Owner's equity (balancing entry)
      {
        accountId: "act_3001"
        entryType: CREDIT
        amount: 45000.00
        description: "Owner's initial investment"
      }
    ]
  ) {
    id
    description
    amount
    status
    entries {
      accountId
      entryType
      amount
      description
    }
  }
}

Record Daily Sales

mutation RecordCashSale {
  createTransaction(
    description: "Cash sale - Invoice #001"
    date: "2024-01-15T00:00:00Z"
    entries: [
      {
        accountId: "act_1001"
        entryType: DEBIT
        amount: 1250.00
        description: "Cash received"
        reference: "Receipt #12345"
      }
      {
        accountId: "act_4001"
        entryType: CREDIT
        amount: 1250.00
        description: "Product sales revenue"
        reference: "Invoice #001"
      }
    ]
  ) {
    id
    description
    status
  }
}

Record Credit Sale

mutation RecordCreditSale {
  createTransaction(
    description: "Credit sale - Acme Corp"
    date: "2024-01-15T00:00:00Z"
    entries: [
      {
        accountId: "act_1101"
        entryType: DEBIT
        amount: 2500.00
        description: "Sale on credit terms"
        reference: "Invoice #002"
      }
      {
        accountId: "act_4001"
        entryType: CREDIT
        amount: 2500.00
        description: "Product sales revenue"
        reference: "Invoice #002"
      }
    ]
  ) {
    id
    description
    status
  }
}

Record Expense Payment

mutation RecordExpensePayment {
  createTransaction(
    description: "Office rent payment"
    date: "2024-01-01T00:00:00Z"
    entries: [
      {
        accountId: "act_5201"
        entryType: DEBIT
        amount: 2500.00
        description: "Monthly office rent"
        reference: "Check #1001"
      }
      {
        accountId: "act_1001"
        entryType: CREDIT
        amount: 2500.00
        description: "Cash payment"
        reference: "Check #1001"
      }
    ]
  ) {
    id
    description
    status
  }
}

Customer and Invoice Management

Create Customer and Send Invoice

# First, create the customer
mutation CreateCustomer {
  createContact(
    name: "TechStart Inc."
    contactType: CUSTOMER
    email: "billing@techstart.com"
    phone: "+1-555-0123"
    taxId: "US123456789"
  ) {
    id
    name
    contactType
  }
}

# Then create invoice (using customer ID from above)
mutation CreateInvoice($customerId: ID!) {
  createInvoice(
    contactId: $customerId
    invoiceDate: "2024-01-15T00:00:00Z"
    dueDate: "2024-02-15T00:00:00Z"
    items: [
      {
        description: "Software Development"
        quantity: 40.0
        unitPrice: 125.00
      }
      {
        description: "Hosting Setup"
        quantity: 1.0
        unitPrice: 500.00
      }
      {
        description: "Training Session"
        quantity: 2.0
        unitPrice: 300.00
      }
    ]
    notes: "Thank you for your business! Payment terms: Net 30 days."
  ) {
    id
    invoiceNumber
    contactId
    subtotal
    taxAmount
    total
    status
    items {
      description
      quantity
      unitPrice
      lineTotal
    }
  }
}

Record Invoice Payment

mutation RecordPayment($invoiceId: ID!) {
  recordInvoicePayment(
    invoiceId: $invoiceId
    amount: 12000.00
    paymentDate: "2024-01-20T00:00:00Z"
    paymentMethod: "Wire Transfer"
    reference: "TXN-2024-001"
    notes: "Full payment received via wire transfer"
  ) {
    id
    amount
    paymentDate
    paymentMethod
    reference
  }
}

Query Customer Financial History

query GetCustomerFinancials($contactId: ID!) {
  contact(id: $contactId) {
    id
    name
    email

    # Recent transactions
    transactions(limit: 10) {
      id
      description
      amount
      date
      currency {
        code
      }
    }

    # All invoices
    invoices {
      id
      invoiceNumber
      invoiceDate
      dueDate
      status
      total
      currency {
        code
      }

      # Payment history
      payments {
        amount
        paymentDate
        paymentMethod
        reference
      }
    }

    # Outstanding balance calculation
    outstandingBalance: transactions(limit: 100) {
      amount
      # You'd calculate this in your application
    }
  }
}

Vendor and Bill Management

Create Vendor and Enter Bill

mutation CreateVendor {
  createContact(
    name: "Office Supplies Co."
    contactType: VENDOR
    email: "ap@officesupplies.com"
    phone: "+1-555-0456"
    taxId: "US987654321"
  ) {
    id
    name
    contactType
  }
}

mutation CreateBill($vendorId: ID!) {
  createBill(
    contactId: $vendorId
    billDate: "2024-01-10T00:00:00Z"
    dueDate: "2024-02-10T00:00:00Z"
    items: [
      {
        description: "Office Chairs"
        quantity: 4.0
        unitPrice: 250.00
      }
      {
        description: "Printer Paper"
        quantity: 10.0
        unitPrice: 45.00
      }
      {
        description: "Coffee Supplies"
        quantity: 5.0
        unitPrice: 35.00
      }
    ]
    notes: "Monthly office supply order"
  ) {
    id
    billNumber
    contactId
    subtotal
    taxAmount
    total
    status
  }
}

Pay Vendor Bill

mutation PayBill($billId: ID!) {
  recordBillPayment(
    billId: $billId
    amount: 1875.00
    paymentDate: "2024-01-12T00:00:00Z"
    paymentMethod: "Check"
    reference: "Check #1002"
    notes: "Payment for office supplies"
  ) {
    id
    amount
    paymentDate
    paymentMethod
    reference
  }
}

Financial Reporting

Generate Trial Balance

query GetTrialBalance {
  organization {
    trialBalance {
      generatedAt
      totalDebits
      totalCredits
      accounts {
        accountCode
        accountName
        accountType
        debitBalance
        creditBalance
        netBalance
      }
    }
  }
}

Generate Balance Sheet

query GetBalanceSheet {
  organization {
    balanceSheet {
      generatedAt
      asOfDate
      totalAssets
      totalLiabilities
      totalEquity

      assets {
        accountName
        balance
      }
      liabilities {
        accountName
        balance
      }
      equity {
        accountName
        balance
      }
    }
  }
}

Generate Income Statement

query GetIncomeStatement {
  organization {
    incomeStatement {
      generatedAt
      periodStart
      periodEnd
      totalRevenue
      totalExpenses
      netIncome

      revenue {
        accountName
        amount
      }
      expenses {
        accountName
        amount
      }
    }
  }
}

Comprehensive Financial Dashboard

query GetFinancialDashboard {
  organization {
    id
    name
    creditsRemaining

    # Current financial position
    balanceSheet {
      totalAssets
      totalLiabilities
      totalEquity
      assets {
        accountName
        balance
      }
    }

    # Profitability
    incomeStatement {
      totalRevenue
      totalExpenses
      netIncome
    }

    # Trial balance check
    trialBalance {
      totalDebits
      totalCredits
      inBalance
    }

    # Recent activity
    recentTransactions(limit: 10) {
      id
      description
      amount
      date
      status
    }

    # Key accounts
    accounts {
      id
      code
      name
      balance {
        formatted
      }
    }
  }
}

Multi-Currency Operations

Create Foreign Currency Transaction

mutation RecordForeignCurrencySale {
  createTransaction(
    description: "Export sale to European customer"
    date: "2024-01-15T00:00:00Z"
    entries: [
      {
        accountId: "act_1101"  # Accounts Receivable (EUR)
        entryType: DEBIT
        amount: 2500.00        # EUR amount
        currencyId: "CUR_EUR"
        description: "Invoice payment due"
      }
      {
        accountId: "act_4001"  # Sales Revenue (USD)
        entryType: CREDIT
        amount: 2750.00        # USD equivalent
        currencyId: "CUR_USD"
        description: "Export sales revenue"
      }
    ]
  ) {
    id
    description
    amount
    currency {
      code
    }
    entries {
      amount
      currency {
        code
      }
      baseAmount
    }
  }
}

Check Exchange Rates

query GetExchangeRates {
  # This would need to be added to the API
  currencies {
    code
    name
  }
}

Advanced Patterns

Bulk Operations with Fragments

fragment AccountDetails on AccountNode {
  id
  code
  name
  accountType
  balance {
    formatted
  }
  status
}

fragment TransactionSummary on TransactionNode {
  id
  description
  amount
  date
  status
  entries {
    accountId
    entryType
    amount
  }
}

query GetBulkData {
  organization {
    name
    accounts {
      ...AccountDetails
      transactions(limit: 5) {
        ...TransactionSummary
      }
    }
    recentTransactions(limit: 20) {
      ...TransactionSummary
    }
  }
}

Conditional Queries with Variables

query GetFlexibleReport($includeDetails: Boolean!, $limit: Int) {
  organization {
    name
    accounts {
      id
      code
      name
      balance {
        formatted
      }
      transactions(limit: $limit) @include(if: $includeDetails) {
        id
        description
        amount
        date
      }
    }
    trialBalance {
      totalDebits
      totalCredits
      accounts @include(if: $includeDetails) {
        accountCode
        accountName
        netBalance
      }
    }
  }
}

Error Handling Examples

Handle Authentication Errors

try {
  const result = await client.query({
    query: GET_ORGANIZATION
  });
  console.log(result.data);
} catch (error) {
  if (error.graphQLErrors) {
    error.graphQLErrors.forEach(graphQLError => {
      if (graphQLError.extensions?.code === 'UNAUTHENTICATED') {
        // Redirect to login
        window.location.href = '/login';
      }
    });
  }
}

Handle Business Logic Errors

const CREATE_TRANSACTION = gql`
  mutation CreateTransaction($input: TransactionInput!) {
    createTransaction(input: $input) {
      id
      status
    }
  }
`;

try {
  const result = await client.mutate({
    mutation: CREATE_TRANSACTION,
    variables: { input: transactionData }
  });
} catch (error) {
  if (error.graphQLErrors) {
    error.graphQLErrors.forEach(graphQLError => {
      switch (graphQLError.extensions?.code) {
        case 'BUSINESS_RULE_VIOLATION':
          alert('Transaction must balance (debits = credits)');
          break;
        case 'VALIDATION_ERROR':
          alert('Invalid account or amount');
          break;
        case 'CREDIT_LIMIT_EXCEEDED':
          alert('Insufficient credits - please top up');
          break;
      }
    });
  }
}

Integration Examples

React Component for Account Management

import { useQuery, useMutation, gql } from '@apollo/client';

const GET_ACCOUNTS = gql`
  query GetAccounts {
    organization {
      accounts {
        id
        code
        name
        accountType
        balance {
          formatted
        }
      }
    }
  }
`;

const CREATE_ACCOUNT = gql`
  mutation CreateAccount($input: CreateAccountInput!) {
    createAccount(input: $input) {
      id
      code
      name
      accountType
    }
  }
`;

function AccountManager() {
  const { loading, error, data, refetch } = useQuery(GET_ACCOUNTS);
  const [createAccount] = useMutation(CREATE_ACCOUNT);

  const handleCreateAccount = async (accountData) => {
    try {
      await createAccount({ variables: { input: accountData } });
      refetch(); // Refresh the list
    } catch (error) {
      console.error('Failed to create account:', error);
    }
  };

  if (loading) return <p>Loading accounts...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <div>
      <h2>Chart of Accounts</h2>
      <button onClick={() => handleCreateAccount({
        code: '6001',
        name: 'New Expense Account',
        accountType: 'EXPENSE'
      })}>
        Add Account
      </button>

      <ul>
        {data.organization.accounts.map(account => (
          <li key={account.id}>
            {account.code} - {account.name}: {account.balance.formatted}
          </li>
        ))}
      </ul>
    </div>
  );
}

Node.js Invoice Processing

const { GraphQLClient, gql } = require('graphql-request');

const client = new GraphQLClient('https://api.craneledger.ai/graphql', {
  headers: {
    'Authorization': 'Bearer cl_live_your_key'
  }
});

const CREATE_INVOICE = gql`
  mutation CreateInvoice($input: CreateInvoiceInput!) {
    createInvoice(input: $input) {
      id
      invoiceNumber
      total
      pdfUrl
    }
  }
`;

async function createAndSendInvoice(customerData, items) {
  try {
    // Create invoice
    const invoiceResult = await client.request(CREATE_INVOICE, {
      input: {
        contactId: customerData.id,
        invoiceDate: new Date().toISOString(),
        dueDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
        items: items,
        notes: 'Thank you for your business!'
      }
    });

    console.log('Invoice created:', invoiceResult.createInvoice.invoiceNumber);

    // Send email with PDF link
    await sendInvoiceEmail(customerData.email, {
      invoiceNumber: invoiceResult.createInvoice.invoiceNumber,
      pdfUrl: invoiceResult.createInvoice.pdfUrl,
      total: invoiceResult.createInvoice.total
    });

    return invoiceResult.createInvoice;
  } catch (error) {
    console.error('Failed to create invoice:', error);
    throw error;
  }
}

Python Financial Dashboard

import asyncio
from gql import gql, Client
from gql.transport.aiohttp import AIOHTTPTransport

transport = AIOHTTPTransport(
    url="https://api.craneledger.ai/graphql",
    headers={"Authorization": "Bearer cl_live_your_key"}
)

client = Client(transport=transport)

GET_DASHBOARD_DATA = gql("""
    query GetDashboardData {
        organization {
            name
            balanceSheet {
                totalAssets
                totalLiabilities
                totalEquity
            }
            incomeStatement {
                totalRevenue
                totalExpenses
                netIncome
            }
            recentTransactions(limit: 5) {
                description
                amount
                date
            }
        }
    }
""")

async def generate_financial_report():
    try:
        result = await client.execute_async(GET_DASHBOARD_DATA)

        org = result['organization']
        print(f"Financial Report for {org['name']}")
        print(f"Total Assets: ${org['balanceSheet']['totalAssets']:,.2f}")
        print(f"Net Income: ${org['incomeStatement']['netIncome']:,.2f}")

        print("\nRecent Transactions:")
        for txn in org['recentTransactions']:
            print(f"- {txn['description']}: ${txn['amount']:,.2f}")

    except Exception as e:
        print(f"Error generating report: {e}")

# Run the report
asyncio.run(generate_financial_report())

These examples demonstrate how to use Crane Ledger's GraphQL API for comprehensive accounting operations, from basic data retrieval to complex financial workflows. The API's flexibility allows you to build exactly the accounting functionality your application needs.


Need help?

Create a free account to access our support portal. Once signed in, use the Support tab in your dashboard to submit a support ticket — our team typically responds within 24 hours.