Guides and Examples
...
Credits
Fetching Credit Stats
19 min
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 stats path 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(); }