Fetching Credit Stats
This guide explains how to retrieve aggregated credit statistics for a customer's account credit pools using the Nue API. Credit stats provide a summary view of credit balances, consumption, and other key metrics across one or more pools.
Prerequisites
Before you begin, ensure you have:
- A valid Nue API key with read permissions
- Customer ID for the account you want to query
- Account credit pool IDs to retrieve statistics for
- Basic understanding of REST APIs and JSON
Authentication
All requests require authentication using your Nue API key in the nue-api-key header:
const myHeaders = new Headers();
myHeaders.append("nue-api-key", "YOUR_API_KEY_HERE");
myHeaders.append("Content-Type", "application/json");Endpoint
GET https://api.nue.io/customers/{customerId}/credit-statsPath Parameters
Parameter | Type | Required | Description |
|---|---|---|---|
customerId | String | Yes | The unique identifier of the customer (UUID or Salesforce ID) |
Query Parameters
Parameter | Type | Required | Description |
|---|---|---|---|
accountPoolIds | Array[String] | Yes | JSON-encoded array of account credit pool IDs (max 50) |
Basic Usage
Fetch Credit Stats for a Single Pool
const myHeaders = new Headers();
myHeaders.append("nue-api-key", "YOUR_API_KEY_HERE");
myHeaders.append("Content-Type", "application/json");
const customerId = "001RK00001jt2i1YAA";
const poolIds = ["474935a8-16cc-46a6-927d-74c962cf460f"];
const encodedPoolIds = encodeURIComponent(JSON.stringify(poolIds));
fetch(`https://api.nue.io/customers/${customerId}/credit-stats?accountPoolIds=${encodedPoolIds}`, {
method: 'GET',
headers: myHeaders
})
.then(response => response.json())
.then(result => {
if (result.status === 'SUCCESS') {
// Access individual pool statistics
const poolStats = result.data.accountCreditPoolStats;
Object.entries(poolStats).forEach(([poolId, stats]) => {
console.log(`\nPool: ${poolId}`);
console.log(` Credit Pool: ${stats.creditPool.join(', ')}`);
console.log(` Credit Type: ${stats.creditType} (${stats.creditTypeLabel})`);
console.log(` Account Balance: ${stats.accountBalance}`);
console.log(` Active Credits: ${stats.activeCredits}`);
console.log(` Pending Credits: ${stats.pendingCredits}`);
console.log(` Consumed Credits: ${stats.consumedCredits}`);
console.log(` Expired Credits: ${stats.expiredCredits}`);
console.log(` Total Balance: ${stats.totalBalance}`);
});
// Access aggregated summary
const summary = result.data.summary;
console.log('\n=== Summary Across All Pools ===');
console.log(` Total Grant Credits: ${summary.totalGrantCredits}`);
console.log(` Active Credits: ${summary.activeCredits}`);
console.log(` Consumed Credits: ${summary.consumedCredits}`);
console.log(` Total Balance: ${summary.totalBalance}`);
}
})
.catch(error => console.log('Error:', error));Fetch Credit Stats for Multiple Pools
const customerId = "001RK00001jt2i1YAA";
const poolIds = [
"474935a8-16cc-46a6-927d-74c962cf460f",
"another-pool-id-here",
"third-pool-id-here"
];
const encodedPoolIds = encodeURIComponent(JSON.stringify(poolIds));
fetch(`https://api.nue.io/customers/${customerId}/credit-stats?accountPoolIds=${encodedPoolIds}`, {
method: 'GET',
headers: myHeaders
})
.then(response => response.json())
.then(result => {
// Check for partial success (some pools may have failed)
if (result.status === 'PARTIAL_SUCCESS') {
console.log('Warning: Some pools could not be retrieved');
result.warnings.forEach(warning => {
console.log(` - ${warning.code}: ${warning.message}`);
});
}
if (result.status === 'SUCCESS' || result.status === 'PARTIAL_SUCCESS') {
const summary = result.data.summary;
console.log('Aggregated Summary:');
console.log(` Credit Pools: ${summary.creditPool.join(', ')}`);
console.log(` Total Balance: ${summary.totalBalance}`);
console.log(` Active: ${summary.activeCredits}`);
console.log(` Consumed: ${summary.consumedCredits}`);
console.log(` Expired: ${summary.expiredCredits}`);
}
})
.catch(error => console.log('Error:', error));Building a Credit Dashboard
async function getCreditDashboard(customerId, poolIds) {
const encodedPoolIds = encodeURIComponent(JSON.stringify(poolIds));
const response = await fetch(
`https://api.nue.io/customers/${customerId}/credit-stats?accountPoolIds=${encodedPoolIds}`,
{ method: 'GET', headers: myHeaders }
);
const result = await response.json();
if (result.status === 'SUCCESS' || result.status === 'PARTIAL_SUCCESS') {
const { accountCreditPoolStats, summary } = result.data;
// Calculate utilization rate
const utilizationRate = summary.totalGrantCredits > 0
? ((summary.consumedCredits / summary.totalGrantCredits) * 100).toFixed(2)
: 0;
// Calculate health metrics
const healthyPools = Object.values(accountCreditPoolStats).filter(
stats => stats.activeCredits > 0
).length;
return {
totalPools: Object.keys(accountCreditPoolStats).length,
healthyPools,
summary: {
totalBalance: summary.totalBalance,
activeCredits: summary.activeCredits,
consumedCredits: summary.consumedCredits,
expiredCredits: summary.expiredCredits,
utilizationRate: `${utilizationRate}%`
},
poolDetails: accountCreditPoolStats,
warnings: result.warnings || []
};
}
throw new Error(result.message || 'Failed to fetch credit stats');
}
// Usage
getCreditDashboard("001RK00001jt2i1YAA", ["474935a8-16cc-46a6-927d-74c962cf460f"])
.then(dashboard => {
console.log('Credit Dashboard:', JSON.stringify(dashboard, null, 2));
})
.catch(error => console.error('Error:', error));Response Structure
Success Response (200 OK)
{
"status": "SUCCESS",
"data": {
"accountCreditPoolStats": {
"474935a8-16cc-46a6-927d-74c962cf460f": {
"accountBalance": 240000,
"activeCredits": 240000,
"canceledCredits": 0,
"committed": true,
"consumedCredits": 0,
"creditBackCredits": 0,
"creditPool": ["Default Committed Credit Pool"],
"creditType": "Cash",
"creditTypeLabel": "Cash",
"currencyIsoCode": "USD",
"expiredCredits": 0,
"isCash": true,
"pendingCredits": 0,
"totalBalance": 240000,
"totalGrantCredits": 240000
}
},
"summary": {
"accountBalance": 240000,
"creditPool": ["Default Committed Credit Pool"],
"totalGrantCredits": 240000,
"expiredCredits": 0,
"consumedCredits": 0,
"canceledCredits": 0,
"creditBackCredits": 0,
"activeCredits": 240000,
"pendingCredits": 0,
"totalBalance": 240000
}
},
"warnings": []
}Response Fields
Credit Pool Stats Object
Field | Type | Description |
|---|---|---|
accountBalance | Number | Current account balance |
activeCredits | Number | Currently active (usable) credits |
pendingCredits | Number | Credits that are pending activation |
totalBalance | Number | Sum of active and pending credits |
totalGrantCredits | Number | Total credits ever granted |
consumedCredits | Number | Total credits consumed |
expiredCredits | Number | Total credits that have expired |
canceledCredits | Number | Total credits that were canceled |
creditBackCredits | Number | Total credits returned/credited back |
committed | Boolean | Whether credits are committed/prepaid |
creditPool | Array[String] | Names of associated credit pools |
creditType | String | Type of credit (e.g., "Cash") |
creditTypeLabel | String | Display label for credit type |
currencyIsoCode | String | Currency code (e.g., "USD"). May be empty string if not set. |
isCash | Boolean | Whether this is a cash credit type |
Summary Object
The summary aggregates statistics across all requested pools:
Field | Type | Description |
|---|---|---|
accountBalance | Number | Combined account balance |
creditPool | Array[String] | Deduplicated list of all credit pool names |
totalGrantCredits | Number | Combined total grants |
activeCredits | Number | Combined active credits |
pendingCredits | Number | Combined pending credits |
totalBalance | Number | Combined total balance |
consumedCredits | Number | Combined consumed credits |
expiredCredits | Number | Combined expired credits |
canceledCredits | Number | Combined canceled credits |
creditBackCredits | Number | Combined credit backs |
HTTP Status Codes
Status | Condition |
|---|---|
200 | Full SUCCESS - all requested pools were retrieved |
207 | PARTIAL_SUCCESS - some pools retrieved, some failed (Multi-Status) |
400 | Bad request - invalid parameters |
404 | Customer not found or all pools failed |
500 | Server error |
Partial Success Response (207)
When some pools fail but at least one succeeds:
{
"status": "PARTIAL_SUCCESS",
"data": {
"accountCreditPoolStats": {
"474935a8-16cc-46a6-927d-74c962cf460f": { ... }
},
"summary": { ... }
},
"warnings": [
{
"code": "POOL_NOT_FOUND",
"message": "Account credit pool 'invalid-pool-id' was not found"
}
]
}Error Handling
Common Errors
Error Code | Description | Resolution |
|---|---|---|
CUSTOMER_NOT_FOUND | Customer ID does not exist | Verify the customer ID |
MISSING_PARAMETER | accountPoolIds not provided | Include required parameter |
INVALID_PARAMETER | Invalid parameter format or exceeds max (50) | Check encoding and array size |
AUTHENTICATION_ERROR | Invalid or missing API key | Verify your API key |
Error Response Example
{
"status": "FAILURE",
"errorType": "MISSING_PARAMETER",
"errorCode": "MISSING_FETCH_PARAMETER",
"message": "The accountPoolIds parameter is required."
}Best Practices
- Fetch pool IDs first - Use the account-credit-pools endpoint to get valid pool IDs
- Batch requests - Request up to 50 pools in a single call for efficiency
- Handle partial success - Always check for warnings when status is PARTIAL_SUCCESS
- Cache appropriately - Stats can change frequently; cache based on your use case
- Monitor utilization - Set up alerts based on consumption rates
Common Workflows
Get Stats for All Customer Pools
async function getAllCreditStats(customerId) {
// Step 1: Get all pool IDs for the customer
const poolsResponse = await fetch(
`https://api.nue.io/customers/${customerId}/account-credit-pools`,
{ method: 'GET', headers: myHeaders }
);
const poolsResult = await poolsResponse.json();
if (poolsResult.status !== 'SUCCESS' || poolsResult.data.length === 0) {
return { status: 'NO_POOLS', data: null };
}
// Step 2: Get stats for all pools
const poolIds = poolsResult.data.map(pool => pool.id);
const encodedPoolIds = encodeURIComponent(JSON.stringify(poolIds));
const statsResponse = await fetch(
`https://api.nue.io/customers/${customerId}/credit-stats?accountPoolIds=${encodedPoolIds}`,
{ method: 'GET', headers: myHeaders }
);
return await statsResponse.json();
}