Code Samples

Ready-to-use code examples and integration patterns for Hello World Systems APIs. Copy, customize, and integrate with confidence.

300+
Code Samples
8
Languages
12
Categories
25k+
Downloads

Browse Code Samples

Showing 4 of 4 samples

Cemetery Records CRUD Operations

Beginner

Complete example showing how to create, read, update, and delete cemetery records using the API.

REST APICRUDCemetery
145
2340
567
javascript
// Initialize API client
const HelloWorldAPI = require('@helloworldsystems/api');
const client = new HelloWorldAPI({
  apiKey: process.env.HELLO_WORLD_API_KEY,
  baseUrl: 'https://api.helloworldsystems.com'
});

// Create a new cemetery record
async function createCemeteryRecord(recordData) {
  try {
    const response = await client.cemetery.create({
      name: recordData.name,
      birth_date: recordData.birthDate,
      death_date: recordData.deathDate,
      plot_number: recordData.plotNumber,
      section: recordData.section,
      next_of_kin: recordData.nextOfKin
    });
    
    console.log('Record created:', response.data);
    return response.data;
  } catch (error) {
    console.error('Error creating record:', error.message);
    throw error;
  }
}

// Fetch cemetery records with pagination
async function getCemeteryRecords(options = {}) {
  try {
    const response = await client.cemetery.list({
      limit: options.limit || 10,
      offset: options.offset || 0,
      status: options.status || 'active',
      search: options.search
    });
    
    return {
      records: response.data,
      pagination: response.pagination
    };
  } catch (error) {
    console.error('Error fetching records:', error.message);
    throw error;
  }
}

// Update cemetery record
async function updateCemeteryRecord(recordId, updateData) {
  try {
    const response = await client.cemetery.update(recordId, updateData);
    console.log('Record updated:', response.data);
    return response.data;
  } catch (error) {
    console.error('Error updating record:', error.message);
    throw error;
  }
}

// Delete cemetery record
async function deleteCemeteryRecord(recordId) {
  try {
    await client.cemetery.delete(recordId);
    console.log('Record deleted successfully');
  } catch (error) {
    console.error('Error deleting record:', error.message);
    throw error;
  }
}

// Example usage
async function main() {
  // Create a new record
  const newRecord = await createCemeteryRecord({
    name: 'John Doe',
    birthDate: '1945-03-15',
    deathDate: '2023-07-20',
    plotNumber: 'A-42',
    section: 'East Garden',
    nextOfKin: 'Jane Doe'
  });
  
  // Fetch records
  const records = await getCemeteryRecords({ limit: 20 });
  console.log('Found records:', records.records.length);
  
  // Update record
  await updateCemeteryRecord(newRecord.id, {
    status: 'active',
    notes: 'Updated with additional information'
  });
}

main().catch(console.error);
Updated 2 days ago

Asset Management Integration

Intermediate

Python example for integrating with asset management system including tracking and maintenance.

PythonAssetsTracking
98
1876
432
python
import os
import requests
from datetime import datetime
from typing import List, Dict, Optional

class HelloWorldAssetAPI:
    def __init__(self, api_key: str, base_url: str = "https://api.helloworldsystems.com"):
        self.api_key = api_key
        self.base_url = base_url
        self.headers = {
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json'
        }
    
    def get_assets(self, category: Optional[str] = None, 
                   status: Optional[str] = None, 
                   location: Optional[str] = None) -> List[Dict]:
        """Retrieve assets with optional filtering"""
        params = {}
        if category:
            params['category'] = category
        if status:
            params['status'] = status
        if location:
            params['location'] = location
        
        response = requests.get(
            f"{self.base_url}/api/v1/assets",
            headers=self.headers,
            params=params
        )
        response.raise_for_status()
        return response.json()['data']
    
    def create_asset(self, asset_data: Dict) -> Dict:
        """Create a new asset"""
        response = requests.post(
            f"{self.base_url}/api/v1/assets",
            headers=self.headers,
            json=asset_data
        )
        response.raise_for_status()
        return response.json()
    
    def update_asset_status(self, asset_id: str, status: str, notes: str = "") -> Dict:
        """Update asset status"""
        data = {
            'status': status,
            'notes': notes,
            'updated_at': datetime.now().isoformat()
        }
        
        response = requests.patch(
            f"{self.base_url}/api/v1/assets/{asset_id}",
            headers=self.headers,
            json=data
        )
        response.raise_for_status()
        return response.json()
    
    def schedule_maintenance(self, asset_id: str, maintenance_type: str, 
                           scheduled_date: str, description: str) -> Dict:
        """Schedule asset maintenance"""
        data = {
            'asset_id': asset_id,
            'maintenance_type': maintenance_type,
            'scheduled_date': scheduled_date,
            'description': description,
            'status': 'scheduled'
        }
        
        response = requests.post(
            f"{self.base_url}/api/v1/assets/{asset_id}/maintenance",
            headers=self.headers,
            json=data
        )
        response.raise_for_status()
        return response.json()

# Example usage
def main():
    # Initialize API client
    api = HelloWorldAssetAPI(
        api_key=os.getenv('HELLO_WORLD_API_KEY')
    )
    
    try:
        # Get all vehicles
        vehicles = api.get_assets(category='vehicles', status='active')
        print(f"Found {len(vehicles)} active vehicles")
        
        # Create new asset
        new_asset = api.create_asset({
            'name': 'Municipal Truck - Ford F-150',
            'category': 'vehicles',
            'serial_number': 'VH001234',
            'location': 'Public Works Depot',
            'purchase_date': '2023-01-15',
            'value': 45000.00,
            'status': 'active'
        })
        print(f"Created asset: {new_asset['id']}")
        
        # Update asset status
        updated_asset = api.update_asset_status(
            new_asset['id'],
            'maintenance',
            'Scheduled for routine maintenance'
        )
        
        # Schedule maintenance
        maintenance = api.schedule_maintenance(
            new_asset['id'],
            'routine',
            '2023-08-15',
            'Oil change and tire rotation'
        )
        print(f"Maintenance scheduled: {maintenance['id']}")
        
    except requests.exceptions.RequestException as e:
        print(f"API Error: {e}")
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()
Updated 5 days ago

Real-time Webhook Handler

Advanced

Node.js Express server for handling Hello World Systems webhooks with signature verification.

WebhooksNode.jsExpressReal-time
203
3421
789
javascript
const express = require('express');
const crypto = require('crypto');
const bodyParser = require('body-parser');

const app = express();
const PORT = process.env.PORT || 3000;
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET;

// Middleware for raw body parsing (needed for signature verification)
app.use('/webhook', bodyParser.raw({ type: 'application/json' }));
app.use(bodyParser.json());

// Webhook signature verification
function verifyWebhookSignature(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');
  
  return crypto.timingSafeEqual(
    Buffer.from(signature, 'hex'),
    Buffer.from(expectedSignature, 'hex')
  );
}

// Webhook event handlers
const eventHandlers = {
  'cemetery.record.created': (data) => {
    console.log('New cemetery record created:', data.record.id);
    // Send notification to relevant staff
    // Update local database
    // Trigger automated workflows
  },
  
  'cemetery.record.updated': (data) => {
    console.log('Cemetery record updated:', data.record.id);
    // Sync changes with local systems
    // Notify stakeholders of changes
  },
  
  'asset.status.changed': (data) => {
    console.log('Asset status changed:', data.asset.id, 'to', data.new_status);
    // Update maintenance schedules
    // Send alerts for critical status changes
    if (data.new_status === 'critical') {
      sendCriticalAssetAlert(data.asset);
    }
  },
  
  'indigent.application.submitted': (data) => {
    console.log('New indigent application:', data.application.id);
    // Queue for review
    // Send acknowledgment to applicant
    // Update dashboard metrics
  },
  
  'recruitment.application.received': (data) => {
    console.log('New job application:', data.application.id);
    // Screen application
    // Send confirmation email
    // Update hiring manager dashboard
  },
  
  'helpdesk.ticket.created': (data) => {
    console.log('New support ticket:', data.ticket.id);
    // Assign to appropriate technician
    // Send auto-response to user
    // Update SLA tracking
  },
  
  'scheduling.shift.conflict': (data) => {
    console.log('Shift conflict detected:', data.conflict.id);
    // Alert managers
    // Suggest alternatives
    // Update scheduling system
  }
};

// Webhook endpoint
app.post('/webhook/hello-world', (req, res) => {
  try {
    const signature = req.headers['x-hello-world-signature'];
    const payload = req.body;
    
    // Verify webhook signature
    if (!verifyWebhookSignature(payload, signature, WEBHOOK_SECRET)) {
      console.log('Invalid webhook signature');
      return res.status(401).json({ error: 'Invalid signature' });
    }
    
    const event = JSON.parse(payload);
    const { type, data, timestamp, id } = event;
    
    console.log(`Received webhook: ${type} at ${timestamp}`);
    
    // Handle the event
    if (eventHandlers[type]) {
      eventHandlers[type](data);
    } else {
      console.log(`Unhandled event type: ${type}`);
    }
    
    // Log event for debugging
    logWebhookEvent(event);
    
    res.status(200).json({ 
      message: 'Webhook processed successfully',
      event_id: id 
    });
    
  } catch (error) {
    console.error('Webhook processing error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// Helper functions
function sendCriticalAssetAlert(asset) {
  // Implementation for critical asset alerts
  console.log(`CRITICAL ALERT: Asset ${asset.name} requires immediate attention`);
  // Send email, SMS, or push notification
}

function logWebhookEvent(event) {
  // Log to database or monitoring system
  console.log('Webhook event logged:', {
    id: event.id,
    type: event.type,
    timestamp: event.timestamp,
    processed_at: new Date().toISOString()
  });
}

// Health check endpoint
app.get('/health', (req, res) => {
  res.json({ 
    status: 'healthy',
    timestamp: new Date().toISOString(),
    webhook_endpoint: '/webhook/hello-world'
  });
});

// Start server
app.listen(PORT, () => {
  console.log(`Webhook server running on port ${PORT}`);
  console.log('Webhook endpoint: /webhook/hello-world');
});

// Graceful shutdown
process.on('SIGTERM', () => {
  console.log('Received SIGTERM, shutting down gracefully');
  server.close(() => {
    console.log('Server closed');
    process.exit(0);
  });
});
Updated 1 week ago

PHP SDK Integration Example

Intermediate

Complete PHP integration example with error handling and best practices.

PHPSDKIntegration
76
1432
298
php
<?php

require_once 'vendor/autoload.php';

use HelloWorldSystems\Client;
use HelloWorldSystems\Exception\ApiException;

class HelloWorldIntegration {
    private $client;
    
    public function __construct($apiKey) {
        $this->client = new Client([
            'api_key' => $apiKey,
            'base_url' => 'https://api.helloworldsystems.com',
            'timeout' => 30
        ]);
    }
    
    /**
     * Sync cemetery records from external database
     */
    public function syncCemeteryRecords() {
        try {
            // Fetch records from local database
            $localRecords = $this->getLocalCemeteryRecords();
            
            foreach ($localRecords as $record) {
                // Check if record exists in Hello World Systems
                $existingRecord = $this->findCemeteryRecord($record['plot_number']);
                
                if ($existingRecord) {
                    // Update existing record
                    $this->updateCemeteryRecord($existingRecord['id'], $record);
                } else {
                    // Create new record
                    $this->createCemeteryRecord($record);
                }
            }
            
            echo "Cemetery records synchronized successfully\n";
            
        } catch (ApiException $e) {
            echo "API Error: " . $e->getMessage() . "\n";
            echo "Error Code: " . $e->getCode() . "\n";
        } catch (Exception $e) {
            echo "General Error: " . $e->getMessage() . "\n";
        }
    }
    
    /**
     * Find cemetery record by plot number
     */
    private function findCemeteryRecord($plotNumber) {
        try {
            $response = $this->client->cemetery->list([
                'plot_number' => $plotNumber,
                'limit' => 1
            ]);
            
            return !empty($response['data']) ? $response['data'][0] : null;
            
        } catch (ApiException $e) {
            if ($e->getCode() === 404) {
                return null; // Record not found
            }
            throw $e;
        }
    }
    
    /**
     * Create new cemetery record
     */
    private function createCemeteryRecord($record) {
        $data = [
            'name' => $record['name'],
            'birth_date' => $record['birth_date'],
            'death_date' => $record['death_date'],
            'plot_number' => $record['plot_number'],
            'section' => $record['section'],
            'next_of_kin' => $record['next_of_kin'],
            'burial_date' => $record['burial_date']
        ];
        
        $response = $this->client->cemetery->create($data);
        echo "Created record: " . $response['id'] . "\n";
        
        return $response;
    }
    
    /**
     * Update existing cemetery record
     */
    private function updateCemeteryRecord($recordId, $record) {
        $data = [
            'name' => $record['name'],
            'next_of_kin' => $record['next_of_kin'],
            'notes' => $record['notes']
        ];
        
        $response = $this->client->cemetery->update($recordId, $data);
        echo "Updated record: " . $recordId . "\n";
        
        return $response;
    }
    
    /**
     * Get records from local database
     */
    private function getLocalCemeteryRecords() {
        // This would connect to your local database
        // Return array of records
        return [
            [
                'name' => 'John Doe',
                'birth_date' => '1945-03-15',
                'death_date' => '2023-07-20',
                'plot_number' => 'A-42',
                'section' => 'East Garden',
                'next_of_kin' => 'Jane Doe',
                'burial_date' => '2023-07-23',
                'notes' => 'Memorial service held'
            ]
        ];
    }
    
    /**
     * Batch process indigent applications
     */
    public function processIndigentApplications() {
        try {
            // Get pending applications
            $applications = $this->client->indigent->list([
                'status' => 'pending',
                'limit' => 50
            ]);
            
            foreach ($applications['data'] as $application) {
                $this->processApplication($application);
            }
            
        } catch (ApiException $e) {
            echo "Error processing applications: " . $e->getMessage() . "\n";
        }
    }
    
    /**
     * Process individual application
     */
    private function processApplication($application) {
        // Business logic for processing applications
        $approved = $this->evaluateApplication($application);
        
        $status = $approved ? 'approved' : 'rejected';
        $notes = $approved ? 'Application meets criteria' : 'Insufficient documentation';
        
        $this->client->indigent->update($application['id'], [
            'status' => $status,
            'notes' => $notes,
            'processed_by' => 'system',
            'processed_at' => date('Y-m-d H:i:s')
        ]);
        
        echo "Processed application: " . $application['id'] . " - " . $status . "\n";
    }
    
    /**
     * Evaluate application based on criteria
     */
    private function evaluateApplication($application) {
        // Implement your business logic here
        return $application['household_income'] < 30000 && 
               $application['household_size'] >= 3;
    }
}

// Usage example
try {
    $integration = new HelloWorldIntegration($_ENV['HELLO_WORLD_API_KEY']);
    
    // Sync cemetery records
    $integration->syncCemeteryRecords();
    
    // Process indigent applications
    $integration->processIndigentApplications();
    
} catch (Exception $e) {
    echo "Integration failed: " . $e->getMessage() . "\n";
}

?>
Updated 3 days ago

Start building with the Hello World Systems APIs

Explore the Docs