Skip to content

FlowSync-Consulting/netsuite-rest-integration-patterns

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

NetSuite REST Integration Patterns

Sample RESTlet and REST API integration patterns for NetSuite, covering authentication, error handling, rate limiting, batch processing, and webhook receivers. These patterns represent production-tested approaches for integrating external systems with NetSuite.

About FlowSync Consulting

FlowSync Consulting specializes in NetSuite customization, integration, and automation. These patterns reflect the integration architectures we use in client projects.

Contact us for NetSuite consulting services →

Features

  • RESTlet Templates - Production-ready RESTlet scaffolding with proper authentication
  • Error Handling - Standardized error responses and retry logic
  • Rate Limiting - Client-side and server-side rate limiting patterns
  • Batch Processing - Efficient bulk data handling for large datasets
  • Webhook Receivers - Secure webhook endpoints with signature validation
  • Authentication - OAuth 1.0, OAuth 2.0, and Token-Based Auth (TBA) examples
  • Response Formatting - Consistent JSON response structures

Repository Structure

patterns/
├── restlets/
│   ├── customer-api/          # CRUD operations for customers
│   ├── order-management/      # Order creation and updates
│   ├── inventory-lookup/      # Real-time inventory queries
│   └── webhook-receiver/      # Generic webhook handler
├── authentication/
│   ├── oauth1/                # OAuth 1.0 flow examples
│   ├── oauth2/                # OAuth 2.0 implementation
│   └── tba/                   # Token-Based Authentication
├── error-handling/
│   ├── response-formatter.js  # Standardized error responses
│   ├── retry-logic.js         # Exponential backoff patterns
│   └── logging.js             # Error logging utilities
├── rate-limiting/
│   ├── client-side.js         # Client-side throttling
│   └── server-side.js         # NetSuite governance-aware limiting
└── batch-processing/
    ├── bulk-import.js         # Large dataset import patterns
    ├── queue-processor.js     # Async processing queue
    └── chunking.js            # Data chunking utilities

Use Cases

Customer Data Synchronization

  • External CRM → NetSuite customer records
  • Real-time customer lookup for e-commerce platforms
  • Bidirectional contact synchronization

Order Management

  • E-commerce platform → NetSuite sales orders
  • Order status updates back to storefront
  • Fulfillment notifications

Inventory Integration

  • Real-time inventory availability queries
  • Multi-channel inventory updates
  • Warehouse management system (WMS) integration

Financial Data Exchange

  • Payment gateway → NetSuite customer payments
  • Invoice data export for external reporting
  • Bank reconciliation automation

Quick Start

1. Deploy a RESTlet

/**
 * @NApiVersion 2.1
 * @NScriptType Restlet
 */
define(['./patterns/restlets/customer-api/handler'], (handler) => ({
    get: handler.get,
    post: handler.post,
    put: handler.put,
    delete: handler.delete
}));

2. Call from External System

// Node.js example using OAuth 1.0
const axios = require('axios');
const OAuth = require('oauth-1.0a');

const oauth = OAuth({
    consumer: { key: CONSUMER_KEY, secret: CONSUMER_SECRET },
    signature_method: 'HMAC-SHA256',
    hash_function: (base_string, key) => {
        return crypto.createHmac('sha256', key)
            .update(base_string)
            .digest('base64');
    }
});

const request = {
    url: 'https://[account].restlets.api.netsuite.com/app/site/hosting/restlet.nl?script=123&deploy=1',
    method: 'GET'
};

const response = await axios.get(request.url, {
    headers: oauth.toHeader(oauth.authorize(request, token))
});

3. Handle Errors Gracefully

try {
    const result = await callNetSuiteAPI();
    return formatSuccess(result);
} catch (error) {
    if (error.code === 'RATE_LIMIT_EXCEEDED') {
        await delay(5000); // Wait and retry
        return await callNetSuiteAPI();
    }
    return formatError(error);
}

Authentication Patterns

OAuth 1.0 (Legacy)

  • Used for older integrations
  • Requires signature generation
  • See /patterns/authentication/oauth1/

OAuth 2.0 (Modern)

  • Recommended for new integrations
  • Token-based with refresh capability
  • See /patterns/authentication/oauth2/

Token-Based Authentication (TBA)

  • NetSuite-native authentication method
  • Simpler than OAuth for server-to-server
  • See /patterns/authentication/tba/

Error Handling Best Practices

Standardized Response Format

{
    "success": false,
    "error": {
        "code": "INVALID_CUSTOMER_ID",
        "message": "Customer ID 12345 does not exist",
        "details": {
            "providedId": "12345",
            "suggestion": "Verify customer exists in NetSuite"
        }
    },
    "timestamp": "2026-03-20T10:30:00Z",
    "requestId": "abc123"
}

Common Error Codes

Code Meaning Retry?
RATE_LIMIT_EXCEEDED Too many requests Yes (after delay)
INVALID_CREDENTIALS Authentication failed No
RECORD_NOT_FOUND Entity doesn't exist No
INSUFFICIENT_PERMISSION User lacks role access No
CONCURRENT_REQUEST_ERROR Record locked by another process Yes (after delay)
UNEXPECTED_ERROR Unhandled exception Maybe (depends on error)

Rate Limiting

Client-Side Throttling

const RateLimiter = require('./patterns/rate-limiting/client-side');

const limiter = new RateLimiter({
    maxRequests: 10,
    perMilliseconds: 1000
});

await limiter.throttle(async () => {
    return await callNetSuiteAPI();
});

Server-Side Governance Monitoring

const governance = require('./patterns/rate-limiting/server-side');

function processRecords(records) {
    records.forEach(record => {
        if (governance.getRemainingUsage() < 100) {
            log.audit('Pausing', 'Low governance units, will resume in next execution');
            return;
        }
        processRecord(record);
    });
}

Batch Processing

Chunking Large Datasets

const { chunkArray } = require('./patterns/batch-processing/chunking');

const customers = [...]; // 10,000 customers
const batches = chunkArray(customers, 100); // Split into batches of 100

for (const batch of batches) {
    await processCustomerBatch(batch);
}

Queue-Based Processing

const QueueProcessor = require('./patterns/batch-processing/queue-processor');

const queue = new QueueProcessor({
    batchSize: 50,
    delayBetweenBatches: 1000
});

queue.add(customers);
queue.process(async (customer) => {
    await createNetSuiteCustomer(customer);
});

Security Considerations

  1. Never hardcode credentials - Use environment variables or secure storage
  2. Validate webhook signatures - Verify requests are from legitimate sources
  3. Implement rate limiting - Prevent abuse and accidental DoS
  4. Log all API calls - Audit trail for troubleshooting
  5. Use HTTPS only - Encrypt data in transit
  6. Sanitize inputs - Prevent injection attacks

Testing

Each pattern includes example test cases demonstrating:

  • Success scenarios
  • Error handling
  • Edge cases (null values, empty arrays, etc.)
  • Performance considerations

Code Quality Standards

All patterns include:

  • Comprehensive JSDoc comments
  • Error handling with detailed logging
  • Governance limit awareness
  • Request/response examples
  • Security best practices documentation

Contributing

Found a bug or have a pattern to contribute? Open an issue or submit a pull request.

License

MIT License - see LICENSE file for details.

Contact


Status: 🚧 Work in progress - patterns being added incrementally

Roadmap:

  • Customer API RESTlet (in progress)
  • OAuth 2.0 authentication examples (in progress)
  • Error handling framework (planned)
  • Rate limiting utilities (planned)
  • Batch processing patterns (planned)
  • Webhook receiver with signature validation (planned)

About

Sample RESTlet and REST API integration patterns for NetSuite (authentication, error handling, rate limiting, batch processing, webhook receivers)

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors