---
title: Fetch Orders
slug: fetch-orders
docTags: 
createdAt: 2026-02-13T04:24:49.103Z
---

This guide provides comprehensive instructions for retrieving order data using the Nue Lifecycle Management API. Learn how to fetch customer orders, filter by status, include related data, and implement efficient order retrieval patterns.

## Prerequisites

Before you begin, ensure you have:

- A valid Nue API key with order read permissions
- Customer IDs for the orders you want to retrieve
- Basic understanding of REST APIs and JSON
- Familiarity with order data structures and lifecycle

## Authentication

All order retrieval operations require authentication using your Nue API key in the `nue-api-key` header:

```javascript
const myHeaders = new Headers();
myHeaders.append("nue-api-key", "YOUR_API_KEY_HERE");
myHeaders.append("Content-Type", "application/json");
```

## REST Endpoints

The Nue API provides REST endpoints for flexible order data access:

```javascript
// Global order endpoints
GET https://api.nue.io/orders              // Get all orders with pagination
GET https://api.nue.io/orders?id={orderId} // Get a specific order by ID

// Customer-scoped order endpoints  
GET https://api.nue.io/customers/{customerId}/orders          // Get orders for a customer
GET https://api.nue.io/customers/{customerId}/orders/{orderId} // Get a specific order for a customer
```

### Filtering

Order endpoints support filtering using query parameters:

**Query Parameters**:

- `customerIds` - Array of customer IDs to filter by
- `customerId` - Single customer ID to filter by
- `status` - Filter by order status: `activated`, `draft`, `canceled`
- `includes` - Include related data (e.g., `orderProducts`, `assets`, `invoices`)
- `page` - Page number for pagination
- `limit` - Number of results per page

## Basic Order Retrieval

### Fetch All Orders for Customer

**Try it now:** [Fetch Orders →](https://api-docs.nue.io/fetch-orders)

```javascript
const myHeaders = new Headers();
myHeaders.append("nue-api-key", "YOUR_API_KEY_HERE");
myHeaders.append("Content-Type", "application/json");

// Fetch all orders for a customer
const customerIds = ["d2e04653-ae90-49df-a986-134cf64f6d03"];
const encodedCustomerIds = encodeURIComponent(JSON.stringify(customerIds));

fetch(`https://api.nue.io/orders?customerIds=${encodedCustomerIds}`, {
  method: 'GET',
  headers: myHeaders
})
.then(response => response.json())
.then(result => {
  console.log('Orders retrieved successfully:', result);
  
  if (result.status === 'SUCCESS' && result.data) {
    console.log(`Found orders for customer`);
    
    // Display order summary
    console.log('\n📋 Order Summary:');
    console.log(`Customer ID: ${customerIds[0]}`);
    console.log(`Total Orders: ${result.data.length || 0}`);
    
    // Display each order
    if (result.data.length > 0) {
      result.data.forEach((order, index) => {
        console.log(`\n${index + 1}. Order ${order.orderNumber}`);
        console.log(`   ID: ${order.id}`);
        console.log(`   Status: ${order.status}`);
        console.log(`   Total: $${order.grandTotal || order.netTotal}`);
        console.log(`   Date: ${order.orderStartDate || order.createdDate}`);
        console.log(`   Type: ${order.orderType || 'Standard'}`);
      });
    }
  }
})
.catch(error => console.log('Error:', error));
```

### Fetch Orders for Multiple Customers

Retrieve orders for multiple customers in a single API call:

```javascript
// Fetch orders for multiple customers
const customerIds = [
  "d2e04653-ae90-49df-a986-134cf64f6d03",
  "cc5e1f0f-5e14-48cc-ab98-9e5b191aa46f",
  "f1b2c3d4-e5f6-7890-abcd-ef1234567890"
];

const encodedCustomerIds = encodeURIComponent(JSON.stringify(customerIds));

fetch(`https://api.nue.io/orders?customerIds=${encodedCustomerIds}`, {
  method: 'GET',
  headers: myHeaders  
})
.then(response => response.json())
.then(result => {
  if (result.status === 'SUCCESS') {
    console.log(`Retrieved orders for ${customerIds.length} customers`);
    
    // Group orders by customer
    const ordersByCustomer = {};
    
    if (result.data && Array.isArray(result.data)) {
      result.data.forEach(order => {
        const customerId = order.customerId;
        if (!ordersByCustomer[customerId]) {
          ordersByCustomer[customerId] = [];
        }
        ordersByCustomer[customerId].push(order);
      });
    }
    
    // Display grouped results
    Object.keys(ordersByCustomer).forEach(customerId => {
      const orders = ordersByCustomer[customerId];
      console.log(`\n--- Customer ${customerId} ---`);
      console.log(`Orders: ${orders.length}`);
      
      orders.forEach(order => {
        console.log(`  • ${order.orderNumber} - ${order.status} - $${order.grandTotal || order.netTotal}`);
      });
    });
  }
})
.catch(error => console.log('Error:', error));
```

## Filtered Order Retrieval

### Fetch Active Orders Only

Filter orders by status to retrieve only active orders:

```javascript
const customerIds = ["d2e04653-ae90-49df-a986-134cf64f6d03"];
const encodedCustomerIds = encodeURIComponent(JSON.stringify(customerIds));

// Fetch only active orders
const url = `https://api.nue.io/orders?customerIds=${encodedCustomerIds}&status=activated`;

fetch(url, {
  method: 'GET',
  headers: myHeaders
})
.then(response => response.json())
.then(result => {
  if (result.status === 'SUCCESS') {
    console.log('🟢 Active Orders Retrieved');
    
    if (result.data && result.data.length > 0) {
      result.data.forEach(order => {
        console.log(`\n📦 ${order.orderNumber}`);
        console.log(`   Status: ${order.status}`);
        console.log(`   Activated: ${order.activatedDate || 'N/A'}`);
        console.log(`   Value: $${order.grandTotal}`);
        console.log(`   Next Billing: ${order.nextBillingDate || 'N/A'}`);
        
        // Show subscription details if available
        if (order.subscriptionEndDate) {
          console.log(`   Subscription End: ${order.subscriptionEndDate}`);
        }
      });
    } else {
      console.log('No active orders found for this customer');
    }
  }
})
.catch(error => console.log('Error:', error));
```

### Fetch Draft Orders Only

Retrieve draft orders that are pending activation:

```javascript
const draftOrdersUrl = `https://api.nue.io/orders?customerIds=${encodedCustomerIds}&status=draft`;

fetch(draftOrdersUrl, {
  method: 'GET',
  headers: myHeaders
})
.then(response => response.json())
.then(result => {
  if (result.status === 'SUCCESS') {
    console.log('📝 Draft Orders Retrieved');
    
    if (result.data && result.data.length > 0) {
      result.data.forEach(order => {
        console.log(`\n📋 ${order.orderNumber || order.id}`);
        console.log(`   Status: ${order.status}`);
        console.log(`   Created: ${order.createdDate}`);
        console.log(`   Value: $${order.grandTotal}`);
        console.log(`   Ready for Activation: ${order.readyForActivation ? 'Yes' : 'No'}`);
      });
      
      console.log(`\n💡 ${result.data.length} draft orders ready for activation`);
    } else {
      console.log('No draft orders found for this customer');
    }
  }
})
.catch(error => console.log('Error:', error));
```

## Including Related Data

### Fetch Orders with Product Details

Include order products in the response for detailed analysis:

```javascript
const customerIds = ["d2e04653-ae90-49df-a986-134cf64f6d03"];
const encodedIds = encodeURIComponent(JSON.stringify(customerIds));

// Include order products in the response
const urlWithProducts = `https://api.nue.io/orders?customerIds=${encodedIds}&includes=orderProducts`;

fetch(urlWithProducts, {
  method: 'GET',
  headers: myHeaders
})
.then(response => response.json())
.then(result => {
  if (result.status === 'SUCCESS' && result.data) {
    result.data.forEach(order => {
      console.log(`\n📦 Order ${order.orderNumber}`);
      console.log(`   Status: ${order.status}`);
      console.log(`   Total: $${order.grandTotal}`);
      
      // Display order products
      if (order.orderProducts && order.orderProducts.length > 0) {
        console.log(`\n   Products (${order.orderProducts.length}):`);
        order.orderProducts.forEach(product => {
          console.log(`     • ${product.productName || product.description}`);
          console.log(`       Quantity: ${product.quantity}`);
          console.log(`       Unit Price: $${product.unitPrice || 'N/A'}`);
          console.log(`       Total: $${product.totalPrice || 'N/A'}`);
          
          if (product.subscriptionTerm) {
            console.log(`       Term: ${product.subscriptionTerm} months`);
          }
          
          if (product.startDate && product.endDate) {
            console.log(`       Period: ${product.startDate} to ${product.endDate}`);
          }
        });
      } else {
        console.log('   No product details available');
      }
    });
  }
})
.catch(error => console.log('Error:', error));
```

### Fetch Orders with Assets and Invoices

Include complete order ecosystem data:

```javascript
// Include multiple related data types
const urlWithAll = `https://api.nue.io/orders?customerIds=${encodedIds}&includes=orderProducts,assets,invoices`;

fetch(urlWithAll, {
  method: 'GET',
  headers: myHeaders
})
.then(response => response.json())
.then(result => {
  if (result.status === 'SUCCESS' && result.data) {
    result.data.forEach(order => {
      console.log(`\n🎯 Complete Order Details: ${order.orderNumber}`);
      console.log(`   Status: ${order.status}`);
      console.log(`   Customer: ${order.customerName || order.customerId}`);
      console.log(`   Total Value: $${order.grandTotal}`);
      
      // Order Products
      if (order.orderProducts && order.orderProducts.length > 0) {
        console.log(`\n   📋 Order Lines: ${order.orderProducts.length}`);
        order.orderProducts.forEach((product, idx) => {
          console.log(`     ${idx + 1}. ${product.productName} (Qty: ${product.quantity})`);
        });
      }
      
      // Assets Created
      if (order.assets && order.assets.length > 0) {
        console.log(`\n   🏗️  Assets: ${order.assets.length}`);
        order.assets.forEach(asset => {
          console.log(`     • ${asset.productName}: ${asset.status}`);
          console.log(`       Period: ${asset.startDate} to ${asset.endDate}`);
          console.log(`       Quantity: ${asset.quantity}`);
        });
      }
      
      // Invoices Generated
      if (order.invoices && order.invoices.length > 0) {
        console.log(`\n   💰 Invoices: ${order.invoices.length}`);
        order.invoices.forEach(invoice => {
          console.log(`     • ${invoice.invoiceNumber || invoice.id}: $${invoice.amount}`);
          console.log(`       Status: ${invoice.status}`);
          console.log(`       Due: ${invoice.dueDate}`);
          console.log(`       Balance: $${invoice.balance}`);
        });
      }
    });
  }
})
.catch(error => console.log('Error:', error));
```

## Advanced Order Analysis

### Order Portfolio Analysis Service

Build comprehensive order analytics and insights:

```javascript
class OrderAnalysisService {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.headers = new Headers();
    this.headers.append("nue-api-key", apiKey);
    this.headers.append("Content-Type", "application/json");
  }
  
  async analyzeCustomerOrders(customerId, options = {}) {
    try {
      // Fetch comprehensive order data
      const orders = await this.fetchOrdersWithDetails([customerId], options);
      
      if (!orders || orders.length === 0) {
        return {
          customerId,
          totalOrders: 0,
          message: 'No orders found for customer'
        };
      }
      
      // Perform analysis
      const analysis = this.performOrderAnalysis(orders);
      
      // Generate insights
      const insights = this.generateInsights(analysis);
      
      return {
        customerId,
        analysis,
        insights,
        orders: options.includeOrderDetails ? orders : undefined
      };
      
    } catch (error) {
      console.error(`Order analysis failed for customer ${customerId}:`, error);
      return {
        customerId,
        error: error.message
      };
    }
  }
  
  async fetchOrdersWithDetails(customerIds, options = {}) {
    const encodedIds = encodeURIComponent(JSON.stringify(customerIds));
    
    // Build URL with includes
    const includes = ['orderProducts', 'assets', 'invoices'];
    const includesStr = includes.join(',');
    
    const url = `https://api.nue.io/orders?customerIds=${encodedIds}&includes=${includesStr}`;
    
    const response = await fetch(url, {
      method: 'GET',
      headers: this.headers
    });
    
    if (!response.ok) {
      throw new Error(`Failed to fetch orders: ${response.status}`);
    }
    
    const result = await response.json();
    
    if (result.status !== 'SUCCESS') {
      throw new Error(`API error: ${result.message || 'Unknown error'}`);
    }
    
    return result.data || [];
  }
  
  performOrderAnalysis(orders) {
    const analysis = {
      overview: {
        totalOrders: orders.length,
        ordersByStatus: {},
        ordersByType: {},
        totalValue: 0,
        averageOrderValue: 0
      },
      timeline: {
        firstOrder: null,
        lastOrder: null,
        orderFrequency: 0
      },
      products: {
        uniqueProducts: new Set(),
        topProducts: {},
        totalAssets: 0,
        activeAssets: 0
      },
      financial: {
        totalInvoiced: 0,
        totalPaid: 0,
        outstandingBalance: 0,
        invoicesByStatus: {}
      },
      subscription: {
        activeSubscriptions: 0,
        subscriptionValue: 0,
        averageSubscriptionLength: 0,
        renewalDates: []
      }
    };
    
    let totalSubLength = 0;
    let subCount = 0;
    
    orders.forEach(order => {
      // Overview analysis
      analysis.overview.totalValue += (order.grandTotal || order.netTotal || 0);
      
      const status = order.status || 'Unknown';
      analysis.overview.ordersByStatus[status] = (analysis.overview.ordersByStatus[status] || 0) + 1;
      
      const type = order.orderType || 'Standard';
      analysis.overview.ordersByType[type] = (analysis.overview.ordersByType[type] || 0) + 1;
      
      // Timeline analysis
      const orderDate = new Date(order.orderStartDate || order.createdDate);
      if (!analysis.timeline.firstOrder || orderDate < new Date(analysis.timeline.firstOrder)) {
        analysis.timeline.firstOrder = order.orderStartDate || order.createdDate;
      }
      if (!analysis.timeline.lastOrder || orderDate > new Date(analysis.timeline.lastOrder)) {
        analysis.timeline.lastOrder = order.orderStartDate || order.createdDate;
      }
      
      // Product analysis
      if (order.orderProducts) {
        order.orderProducts.forEach(product => {
          const productName = product.productName || product.description;
          if (productName) {
            analysis.products.uniqueProducts.add(productName);
            analysis.products.topProducts[productName] = (analysis.products.topProducts[productName] || 0) + (product.quantity || 1);
          }
        });
      }
      
      // Asset analysis
      if (order.assets) {
        analysis.products.totalAssets += order.assets.length;
        analysis.products.activeAssets += order.assets.filter(a => a.status === 'Active').length;
        
        // Subscription analysis
        order.assets.forEach(asset => {
          if (asset.status === 'Active' && asset.endDate) {
            analysis.subscription.activeSubscriptions++;
            analysis.subscription.subscriptionValue += (asset.recurringRevenue || 0);
            analysis.subscription.renewalDates.push(asset.endDate);
            
            if (asset.startDate && asset.endDate) {
              const start = new Date(asset.startDate);
              const end = new Date(asset.endDate);
              const lengthMonths = Math.round((end - start) / (1000 * 60 * 60 * 24 * 30));
              totalSubLength += lengthMonths;
              subCount++;
            }
          }
        });
      }
      
      // Financial analysis
      if (order.invoices) {
        order.invoices.forEach(invoice => {
          analysis.financial.totalInvoiced += (invoice.amount || 0);
          analysis.financial.outstandingBalance += (invoice.balance || 0);
          analysis.financial.totalPaid += ((invoice.amount || 0) - (invoice.balance || 0));
          
          const invoiceStatus = invoice.status || 'Unknown';
          analysis.financial.invoicesByStatus[invoiceStatus] = (analysis.financial.invoicesByStatus[invoiceStatus] || 0) + 1;
        });
      }
    });
    
    // Calculate derived metrics
    analysis.overview.averageOrderValue = analysis.overview.totalOrders > 0 ? 
      analysis.overview.totalValue / analysis.overview.totalOrders : 0;
    
    analysis.subscription.averageSubscriptionLength = subCount > 0 ? 
      totalSubLength / subCount : 0;
    
    // Calculate order frequency (orders per year)
    if (analysis.timeline.firstOrder && analysis.timeline.lastOrder) {
      const firstDate = new Date(analysis.timeline.firstOrder);
      const lastDate = new Date(analysis.timeline.lastOrder);
      const yearsDiff = (lastDate - firstDate) / (1000 * 60 * 60 * 24 * 365);
      analysis.timeline.orderFrequency = yearsDiff > 0 ? 
        analysis.overview.totalOrders / yearsDiff : 0;
    }
    
    // Convert Set to Array for JSON serialization
    analysis.products.uniqueProducts = Array.from(analysis.products.uniqueProducts);
    
    return analysis;
  }
  
  generateInsights(analysis) {
    const insights = [];
    
    // Order volume insights
    if (analysis.overview.totalOrders === 0) {
      insights.push({
        type: 'warning',
        category: 'orders',
        message: 'No orders found for this customer'
      });
    } else if (analysis.overview.totalOrders === 1) {
      insights.push({
        type: 'info',
        category: 'orders',
        message: 'Single order customer - potential for growth'
      });
    } else if (analysis.overview.totalOrders >= 10) {
      insights.push({
        type: 'positive',
        category: 'orders',
        message: 'High-volume customer with strong order history'
      });
    }
    
    // Order value insights
    if (analysis.overview.averageOrderValue > 50000) {
      insights.push({
        type: 'positive',
        category: 'revenue',
        message: 'High-value customer with large average order size'
      });
    } else if (analysis.overview.averageOrderValue < 1000) {
      insights.push({
        type: 'warning',
        category: 'revenue',
        message: 'Low average order value - consider upselling opportunities'
      });
    }
    
    // Status insights
    const draftOrders = analysis.overview.ordersByStatus['Draft'] || 0;
    if (draftOrders > 0) {
      insights.push({
        type: 'action',
        category: 'orders',
        message: `${draftOrders} draft orders pending activation`
      });
    }
    
    // Financial insights
    if (analysis.financial.outstandingBalance > 0) {
      insights.push({
        type: 'warning',
        category: 'finance',
        message: `Outstanding balance: $${analysis.financial.outstandingBalance.toLocaleString()}`
      });
    }
    
    // Subscription insights
    if (analysis.subscription.activeSubscriptions > 0) {
      const nextRenewal = analysis.subscription.renewalDates
        .sort()
        .find(date => new Date(date) > new Date());
      
      if (nextRenewal) {
        const daysToRenewal = Math.ceil((new Date(nextRenewal) - new Date()) / (1000 * 60 * 60 * 24));
        
        if (daysToRenewal <= 30) {
          insights.push({
            type: 'action',
            category: 'subscription',
            message: `Subscription renewal due in ${daysToRenewal} days`
          });
        }
      }
    }
    
    // Product insights
    if (analysis.products.uniqueProducts.length === 1) {
      insights.push({
        type: 'opportunity',
        category: 'products',
        message: 'Single product customer - consider cross-selling'
      });
    } else if (analysis.products.uniqueProducts.length >= 5) {
      insights.push({
        type: 'positive',
        category: 'products',
        message: 'Diverse product portfolio customer'
      });
    }
    
    return insights;
  }
  
  async generateOrderReport(customerIds, options = {}) {
    console.log(`\n📊 Generating Order Report for ${customerIds.length} customers...`);
    
    const reports = [];
    
    for (const customerId of customerIds) {
      const analysis = await this.analyzeCustomerOrders(customerId, options);
      reports.push(analysis);
      
      // Display individual customer report
      this.displayCustomerReport(analysis);
    }
    
    // Generate summary report
    this.displaySummaryReport(reports);
    
    return reports;
  }
  
  displayCustomerReport(analysis) {
    if (analysis.error) {
      console.log(`\n❌ ${analysis.customerId}: ${analysis.error}`);
      return;
    }
    
    console.log(`\n📋 Customer ${analysis.customerId}`);
    console.log('='.repeat(50));
    
    const a = analysis.analysis;
    
    // Overview
    console.log(`\n📈 Overview:`);
    console.log(`   Total Orders: ${a.overview.totalOrders}`);
    console.log(`   Total Value: $${a.overview.totalValue.toLocaleString()}`);
    console.log(`   Average Order: $${a.overview.averageOrderValue.toLocaleString()}`);
    console.log(`   Order Frequency: ${a.timeline.orderFrequency.toFixed(1)} orders/year`);
    
    // Status breakdown
    console.log(`\n📊 Order Status:`);
    Object.entries(a.overview.ordersByStatus).forEach(([status, count]) => {
      console.log(`   ${status}: ${count}`);
    });
    
    // Products
    console.log(`\n📦 Products:`);
    console.log(`   Unique Products: ${a.products.uniqueProducts.length}`);
    console.log(`   Total Assets: ${a.products.totalAssets} (${a.products.activeAssets} active)`);
    
    // Subscriptions
    if (a.subscription.activeSubscriptions > 0) {
      console.log(`\n🔄 Subscriptions:`);
      console.log(`   Active: ${a.subscription.activeSubscriptions}`);
      console.log(`   Monthly Value: $${a.subscription.subscriptionValue.toLocaleString()}`);
      console.log(`   Avg Length: ${a.subscription.averageSubscriptionLength.toFixed(1)} months`);
    }
    
    // Financial
    console.log(`\n💰 Financial:`);
    console.log(`   Total Invoiced: $${a.financial.totalInvoiced.toLocaleString()}`);
    console.log(`   Total Paid: $${a.financial.totalPaid.toLocaleString()}`);
    console.log(`   Outstanding: $${a.financial.outstandingBalance.toLocaleString()}`);
    
    // Insights
    if (analysis.insights && analysis.insights.length > 0) {
      console.log(`\n💡 Insights:`);
      analysis.insights.forEach(insight => {
        const icon = insight.type === 'positive' ? '✅' : 
                    insight.type === 'warning' ? '⚠️' : 
                    insight.type === 'action' ? '🎯' : 'ℹ️';
        console.log(`   ${icon} ${insight.message}`);
      });
    }
  }
  
  displaySummaryReport(reports) {
    console.log(`\n📊 Summary Report`);
    console.log('='.repeat(50));
    
    const validReports = reports.filter(r => !r.error);
    const totalCustomers = validReports.length;
    
    if (totalCustomers === 0) {
      console.log('No valid customer data found');
      return;
    }
    
    const totals = validReports.reduce((acc, r) => {
      const a = r.analysis;
      return {
        orders: acc.orders + a.overview.totalOrders,
        value: acc.value + a.overview.totalValue,
        assets: acc.assets + a.products.totalAssets,
        activeAssets: acc.activeAssets + a.products.activeAssets,
        subscriptions: acc.subscriptions + a.subscription.activeSubscriptions
      };
    }, { orders: 0, value: 0, assets: 0, activeAssets: 0, subscriptions: 0 });
    
    console.log(`\n📈 Portfolio Summary:`);
    console.log(`   Total Customers: ${totalCustomers}`);
    console.log(`   Total Orders: ${totals.orders}`);
    console.log(`   Total Value: $${totals.value.toLocaleString()}`);
    console.log(`   Avg per Customer: $${(totals.value / totalCustomers).toLocaleString()}`);
    console.log(`   Total Assets: ${totals.assets} (${totals.activeAssets} active)`);
    console.log(`   Active Subscriptions: ${totals.subscriptions}`);
  }
}

// Usage examples
const orderAnalysis = new OrderAnalysisService("YOUR_API_KEY_HERE");

// Single customer analysis
const singleAnalysis = await orderAnalysis.analyzeCustomerOrders(
  "d2e04653-ae90-49df-a986-134cf64f6d03",
  { includeOrderDetails: false }
);

console.log('Customer analysis completed');

// Multi-customer report
const customerIds = [
  "d2e04653-ae90-49df-a986-134cf64f6d03",
  "cc5e1f0f-5e14-48cc-ab98-9e5b191aa46f"
];

const reports = await orderAnalysis.generateOrderReport(customerIds);
console.log(`Portfolio analysis completed for ${customerIds.length} customers`);
```

## Query Parameters Reference

| Parameter     | Type           | Required | Description                        | Options                                     |
| ------------- | -------------- | -------- | ---------------------------------- | ------------------------------------------- |
| `customerIds` | Array\[String] | Yes      | JSON-encoded array of customer IDs | `["customer-uuid-1", "customer-uuid-2"]`    |
| `status`      | String         | No       | Filter orders by status            | `"activated"`, `"draft"`, `"canceled"`      |
| `includes`    | String         | No       | Related data to include            | `"orderProducts"`, `"assets"`, `"invoices"` |

## Response Structure

### Success Response (200 OK)

```json
{
  "status": "SUCCESS",
  "data": [
    {
      "id": "order-uuid",
      "orderNumber": "ORD-000001",
      "customerId": "customer-uuid",
      "customerName": "Customer Name",
      "status": "Active",
      "orderStartDate": "2025-01-01",
      "activatedDate": "2025-01-01T10:30:00Z",
      "grandTotal": 9720.00,
      "netTotal": 9000.00,
      "orderType": "New",
      "orderProducts": [],
      "assets": [],
      "invoices": []
    }
  ]
}
```

## Error Handling

### Common Retrieval Errors

| Error                   | Description                | Resolution                      |
| ----------------------- | -------------------------- | ------------------------------- |
| `INVALID_CUSTOMER_ID`   | Customer ID format invalid | Verify customer ID format       |
| `CUSTOMER_NOT_FOUND`    | Customer does not exist    | Check customer ID exists        |
| `INVALID_STATUS_FILTER` | Invalid status value       | Use valid status values         |
| `INVALID_INCLUDES`      | Invalid include parameter  | Check available include options |

### Robust Order Fetching

```javascript
async function safeOrderFetch(customerIds, options = {}) {
  try {
    // Validate inputs
    if (!Array.isArray(customerIds) || customerIds.length === 0) {
      throw new Error('CustomerIds must be a non-empty array');
    }
    
    const encodedIds = encodeURIComponent(JSON.stringify(customerIds));
    let url = `https://api.nue.io/orders?customerIds=${encodedIds}`;
    
    // Add optional parameters
    if (options.status) {
      url += `&status=${options.status}`;
    }
    
    if (options.includes) {
      url += `&includes=${options.includes}`;
    }
    
    const response = await fetch(url, {
      method: 'GET',
      headers: myHeaders
    });
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
    
    const result = await response.json();
    
    if (result.status !== 'SUCCESS') {
      throw new Error(`API Error: ${result.message || 'Unknown error'}`);
    }
    
    return {
      orders: result.data || [],
      found: result.data?.length || 0,
      requested: customerIds.length
    };
    
  } catch (error) {
    console.error('Order fetch error:', error);
    return {
      orders: [],
      found: 0,
      requested: customerIds.length,
      error: error.message
    };
  }
}
```

## Best Practices

### Data Retrieval

1. **Use specific status filters** to reduce data transfer
2. **Include related data** only when needed to optimize performance
3. **Batch customer queries** efficiently
4. **Cache frequently accessed** order data

### Performance Optimization

1. **Limit includes** to required data only
2. **Implement pagination** for large result sets
3. **Use appropriate timeout** settings for API calls
4. **Monitor API usage** and respect rate limits

### Business Intelligence

1. **Analyze order patterns** for customer insights
2. **Track subscription renewals** proactively
3. **Monitor order status** transitions
4. **Generate actionable insights** from order data

This comprehensive guide enables you to efficiently retrieve and analyze order data using the Nue Lifecycle Management API, supporting everything from simple order lookups to complex portfolio analysis and business intelligence operations.
