Guides and Examples
...
Contacts
Fetching Contacts
19 min
this guide provides comprehensive instructions for retrieving contact data using the nue lifecycle management api learn how to fetch contacts by email, include contacts with customer data, and implement efficient contact data retrieval patterns prerequisites before you begin, ensure you have a valid nue api key contact email addresses or customer ids with associated contacts basic understanding of rest apis and json familiarity with contact data structures authentication all contact operations 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"); rest endpoints the nue api provides rest endpoints for flexible contact data access // global contact endpoints get https //api nue io/contacts // get all contacts with pagination get https //api nue io/contacts/{contactid} // get a specific contact by id // customer scoped contact endpoints get https //api nue io/customers/{customerid}/contacts // get contacts for a customer get https //api nue io/customers/{customerid}/contacts/{contactid} // get a specific contact for a customer filtering contact endpoints support filtering using query parameters query parameters emails array of email addresses to search for customerid filter by customer id page page number for pagination limit number of results per page contact retrieval methods fetch contacts by email try it now https //api docs nue io/fetch contacts const myheaders = new headers(); myheaders append("nue api key", "your api key here"); myheaders append("content type", "application/json"); // fetch contacts by email addresses const emails = \["john doe\@acme com", "jane smith\@techcorp io"]; const encodedemails = encodeuricomponent(json stringify(emails)); fetch(`https //api nue io/contacts?emails=${encodedemails}`, { method 'get', headers myheaders }) then(response => response json()) then(result => { if (result status === 'success') { const contacts = result data; console log(`retrieved ${contacts length} contacts`); contacts foreach(contact => { console log(`\n ${contact firstname} ${contact lastname} `); console log(`email ${contact email}`); console log(`customer id ${contact customerid}`); console log(`title ${contact title || 'not specified'}`); console log(`phone ${contact phone || 'not specified'}`); console log(`mobile ${contact mobilephone || 'not specified'}`); // display address if available if (contact billingstreet) { console log(`address ${contact billingstreet}, ${contact billingcity}, ${contact billingstate} ${contact billingpostalcode}`); } }); // handle any warnings if (result warnings && result warnings length > 0) { console warn('warnings ', result warnings); } } else { console error('failed to fetch contacts ', result error); } }) catch(error => console log('error ', error)); fetch single contact by email retrieve a specific contact by their email address const contactemail = "billing\@acme com"; const emails = \[contactemail]; const encodedemails = encodeuricomponent(json stringify(emails)); fetch(`https //api nue io/contacts?emails=${encodedemails}`, { method 'get', headers myheaders }) then(response => response json()) then(result => { if (result status === 'success') { const contacts = result data; if (contacts length > 0) { const contact = contacts\[0]; console log('ā
contact found '); console log(`name ${contact firstname} ${contact lastname}`); console log(`email ${contact email}`); console log(`contact id ${contact id}`); console log(`customer id ${contact customerid}`); console log(`title ${contact title || 'not specified'}`); console log(`created ${contact createddate}`); console log(`last modified ${contact lastmodifieddate}`); } else { console log('ā contact not found'); } // handle any warnings if (result warnings && result warnings length > 0) { console warn('warnings ', result warnings); } } else { console error('failed to fetch contact ', result error); } }) catch(error => console log('error ', error)); fetch contacts with customer data include contacts in customer retrieval get customer information along with all associated contacts const myheaders = new headers(); myheaders append("nue api key", "your api key here"); myheaders append("content type", "application/json"); // fetch customers with their contacts included const customerids = \["d2e04653 ae90 49df a986 134cf64f6d03"]; const encodedcustomerids = encodeuricomponent(json stringify(customerids)); fetch(`https //api nue io/customers?customerids=${encodedcustomerids}\&includes=contacts`, { method 'get', headers myheaders }) then(response => response json()) then(result => { if (result status === 'success') { const customers = result data; customers foreach(customer => { console log(`\nš¢ customer ${customer name}`); console log(`account number ${customer accountnumber}`); if (customer contacts && customer contacts length > 0) { console log(`\nš„ contacts (${customer contacts length}) `); customer contacts foreach((contact, index) => { console log(`\n${index + 1} ${contact firstname} ${contact lastname}`); console log(` email ${contact email}`); console log(` phone ${contact phone || 'not provided'}`); console log(` mobile ${contact mobilephone || 'not provided'}`); console log(` title ${contact title || 'not specified'}`); console log(` birthday ${contact birthday || 'not specified'}`); // display billing address if available if (contact billingstreet) { console log(` billing address `); console log(` ${contact billingstreet}`); console log(` ${contact billingcity}, ${contact billingstate} ${contact billingpostalcode}`); console log(` ${contact billingcountry}`); } // display shipping address if different if (contact shippingstreet && contact shippingstreet !== contact billingstreet) { console log(` shipping address `); console log(` ${contact shippingstreet}`); console log(` ${contact shippingcity}, ${contact shippingstate} ${contact shippingpostalcode}`); console log(` ${contact shippingcountry}`); } }); } else { console log('no contacts found for this customer'); } }); }) catch(error => console log('error ', error)); advanced contact retrieval patterns contact directory builder build a comprehensive contact directory with search and filtering capabilities class contactdirectory { constructor(apikey) { this apikey = apikey; this headers = new headers(); this headers append("nue api key", apikey); this headers append("content type", "application/json"); this contactcache = new map(); } async buildcontactdirectory(customerids) { try { console log('š building contact directory '); // fetch customers with contacts const encodedids = encodeuricomponent(json stringify(customerids)); const response = await fetch( `https //api nue io/customers?customerids=${encodedids}\&includes=contacts`, { method 'get', headers this headers } ); if (!response ok) { throw new error(`failed to fetch customers ${response status}`); } const customers = await response json(); // build comprehensive directory const directory = { contacts \[], customers {}, byrole {}, bydepartment {}, statistics { totalcontacts 0, totalcustomers customers length, contactspercustomer 0, withphone 0, withmobile 0, withtitle 0 } }; customers foreach(customer => { directory customers\[customer id] = { name customer name, accountnumber customer accountnumber, industry customer industry, contacts \[] }; if (customer contacts) { customer contacts foreach(contact => { // enrich contact with customer info const enrichedcontact = { contact, customername customer name, customeraccountnumber customer accountnumber, customerindustry customer industry }; directory contacts push(enrichedcontact); directory customers\[customer id] contacts push(enrichedcontact); // categorize by role/title const role = this normalizerole(contact title); if (!directory byrole\[role]) { directory byrole\[role] = \[]; } directory byrole\[role] push(enrichedcontact); // update statistics directory statistics totalcontacts++; if (contact phone) directory statistics withphone++; if (contact mobilephone) directory statistics withmobile++; if (contact title) directory statistics withtitle++; // cache contact for quick lookup this contactcache set(contact email tolowercase(), enrichedcontact); }); } }); directory statistics contactspercustomer = directory statistics totalcontacts / directory statistics totalcustomers; // display directory summary console log('\nš contact directory summary '); console log(` total contacts ${directory statistics totalcontacts}`); console log(` total customers ${directory statistics totalcustomers}`); console log(` avg contacts/customer ${directory statistics contactspercustomer tofixed(1)}`); console log(` with phone ${directory statistics withphone} (${(directory statistics withphone/directory statistics totalcontacts 100) tofixed(1)}%)`); console log(` with mobile ${directory statistics withmobile} (${(directory statistics withmobile/directory statistics totalcontacts 100) tofixed(1)}%)`); console log(` with title ${directory statistics withtitle} (${(directory statistics withtitle/directory statistics totalcontacts 100) tofixed(1)}%)`); console log(`\nš contacts by role `); object entries(directory byrole) sort((\[,a], \[,b]) => b length a length) foreach((\[role, contacts]) => { console log(` ${role} ${contacts length} contacts`); }); return directory; } catch (error) { console error('failed to build contact directory ', error); throw error; } } searchcontacts(directory, searchterm) { const term = searchterm tolowercase(); return directory contacts filter(contact => { return contact firstname? tolowercase() includes(term) || contact lastname? tolowercase() includes(term) || contact email? tolowercase() includes(term) || contact title? tolowercase() includes(term) || contact customername? tolowercase() includes(term); }); } getcontactsbycustomer(directory, customerid) { return directory customers\[customerid]? contacts || \[]; } getcontactsbyrole(directory, role) { const normalizedrole = this normalizerole(role); return directory byrole\[normalizedrole] || \[]; } normalizerole(title) { if (!title) return 'unknown'; const lower = title tolowercase(); if (lower includes('ceo') || lower includes('chief executive')) return 'ceo'; if (lower includes('cfo') || lower includes('chief financial')) return 'cfo'; if (lower includes('cto') || lower includes('chief technology')) return 'cto'; if (lower includes('vp') || lower includes('vice president')) return 'vp'; if (lower includes('director')) return 'director'; if (lower includes('manager')) return 'manager'; if (lower includes('engineer')) return 'engineer'; if (lower includes('developer')) return 'developer'; if (lower includes('analyst')) return 'analyst'; if (lower includes('coordinator')) return 'coordinator'; if (lower includes('specialist')) return 'specialist'; if (lower includes('admin')) return 'admin'; return 'other'; } } // usage const contactdirectory = new contactdirectory("your api key here"); const customerids = \[ "d2e04653 ae90 49df a986 134cf64f6d03", "cc5e1f0f 5e14 48cc ab98 9e5b191aa46f" ]; contactdirectory buildcontactdirectory(customerids) then(directory => { console log('\nš contact directory built successfully'); // search example const searchresults = contactdirectory searchcontacts(directory, 'john'); console log(`\nš search for "john" ${searchresults length} results`); // get contacts by role const managers = contactdirectory getcontactsbyrole(directory, 'manager'); console log(`\nš managers ${managers length} contacts`); return directory; }); contact communication hub create a system for managing contact communications class contactcommunicationhub { constructor(apikey) { this apikey = apikey; this headers = new headers(); this headers append("nue api key", apikey); this headers append("content type", "application/json"); } async getcontactcommunicationprofile(emails) { try { const encodedemails = encodeuricomponent(json stringify(emails)); const response = await fetch( `https //api nue io/contacts?emails=${encodedemails}`, { method 'get', headers this headers } ); if (!response ok) { throw new error(`failed to fetch contacts ${response status}`); } const result = await response json(); if (result status !== 'success') { throw new error(`failed to fetch contacts ${result error}`); } const contacts = result data; // build communication profiles const profiles = contacts map(contact => { const profile = { contact { id contact id, name `${contact firstname} ${contact lastname}`, email contact email, title contact title, customerid contact customerid }, communication { primary contact email, phone contact phone, mobile contact mobilephone, preferredmethod this determinepreferredmethod(contact), timezone this infertimezone(contact), businesshours this getbusinesshours(contact) }, preferences { hasphone !!contact phone, hasmobile !!contact mobilephone, canreceivesms !!contact mobilephone, canreceivecalls !!(contact phone || contact mobilephone) }, engagement { lastmodified contact lastmodifieddate, created contact createddate, isrecent this isrecentcontact(contact createddate) } }; return profile; }); return { profiles, summary this generatecommunicationsummary(profiles) }; } catch (error) { console error('failed to get communication profiles ', error); throw error; } } determinepreferredmethod(contact) { // business logic to determine preferred communication method if (contact mobilephone && contact phone) { return 'multi channel'; // can use both } else if (contact mobilephone) { return 'mobile'; // mobile preferred } else if (contact phone) { return 'phone'; // office phone } else { return 'email only'; // email only } } infertimezone(contact) { // in real implementation, you might use address or other data // for now, return default business timezone return 'america/new york'; } getbusinesshours(contact) { // standard business hours could be customized based on contact data return { start '09 00', end '17 00', timezone this infertimezone(contact), days \['monday', 'tuesday', 'wednesday', 'thursday', 'friday'] }; } isrecentcontact(createddate) { const created = new date(createddate); const now = new date(); const daysago = (now created) / (1000 60 60 24); return daysago <= 30; // consider recent if created within 30 days } generatecommunicationsummary(profiles) { const summary = { totalcontacts profiles length, withphone 0, withmobile 0, emailonly 0, multichannel 0, recentcontacts 0 }; profiles foreach(profile => { if (profile preferences hasphone) summary withphone++; if (profile preferences hasmobile) summary withmobile++; if (profile communication preferredmethod === 'email only') summary emailonly++; if (profile communication preferredmethod === 'multi channel') summary multichannel++; if (profile engagement isrecent) summary recentcontacts++; }); return summary; } async plancommunicationcampaign(emails, campaigntype) { const { profiles, summary } = await this getcontactcommunicationprofile(emails); console log('\nš¢ communication campaign planning'); console log('====================================='); console log(`\nš profile summary `); console log(` total contacts ${summary totalcontacts}`); console log(` with phone ${summary withphone}`); console log(` with mobile ${summary withmobile}`); console log(` email only ${summary emailonly}`); console log(` multi channel ${summary multichannel}`); console log(` recent contacts ${summary recentcontacts}`); // generate campaign recommendations const recommendations = this generatecampaignrecommendations(profiles, campaigntype); console log(`\nš campaign recommendations for "${campaigntype}" `); recommendations foreach(rec => { console log(` ⢠${rec method} ${rec contacts length} contacts ${rec description}`); }); return { profiles, summary, recommendations }; } generatecampaignrecommendations(profiles, campaigntype) { const recommendations = \[]; // email campaign (always available) recommendations push({ method 'email', contacts profiles, description 'primary communication method for all contacts' }); // phone campaign for urgent communications if (campaigntype === 'urgent') { const phonecontacts = profiles filter(p => p preferences canreceivecalls); if (phonecontacts length > 0) { recommendations push({ method 'phone calls', contacts phonecontacts, description 'follow up calls for urgent matters' }); } } // sms for quick notifications if (campaigntype === 'notification') { const smscontacts = profiles filter(p => p preferences canreceivesms); if (smscontacts length > 0) { recommendations push({ method 'sms', contacts smscontacts, description 'quick notifications and reminders' }); } } return recommendations; } } // usage const commhub = new contactcommunicationhub("your api key here"); const contactemails = \[ "john doe\@acme com", "jane smith\@techcorp io", "billing\@startup com" ]; commhub plancommunicationcampaign(contactemails, 'urgent') then(campaign => { console log('communication campaign planned successfully'); }); error handling and best practices robust contact fetching async function safecontactfetch(emails, options = {}) { const myheaders = new headers(); myheaders append("nue api key", "your api key here"); myheaders append("content type", "application/json"); try { // validate input if (!array isarray(emails) || emails length === 0) { throw new error('emails must be a non empty array'); } // validate email formats const emailregex = /^\[^\s@]+@\[^\s@]+\\ \[^\s@]+$/; const invalidemails = emails filter(email => !emailregex test(email)); if (invalidemails length > 0) { console warn('invalid email formats detected ', invalidemails); } const validemails = emails filter(email => emailregex test(email)); if (validemails length === 0) { throw new error('no valid email addresses provided'); } const encodedemails = encodeuricomponent(json stringify(validemails)); const response = await fetch( `https //api nue io/contacts?emails=${encodedemails}`, { method 'get', headers myheaders, timeout 30000 // 30 second timeout } ); if (!response ok) { throw new error(`http ${response status} ${response statustext}`); } const contacts = await response json(); // validate response if (!array isarray(contacts)) { throw new error('invalid response format expected array'); } // check for missing contacts const foundemails = contacts map(c => c email tolowercase()); const missingemails = validemails filter(email => !foundemails includes(email tolowercase()) ); return { contacts, found contacts length, requested validemails length, missing missingemails, invalid invalidemails }; } catch (error) { console error('contact fetch error ', error); return { contacts \[], found 0, requested emails length, missing emails, invalid \[], error error message }; } } // usage with error handling safecontactfetch(\[ "valid\@email com", "invalid email", "another\@valid email" ]) then(result => { if (result error) { console error('fetch failed ', result error); } else { console log(`successfully fetched ${result found}/${result requested} contacts`); if (result missing length > 0) { console log('missing contacts ', result missing); } if (result invalid length > 0) { console log('invalid emails ', result invalid); } } }); query parameters reference parameter type required description example emails array\[string] yes json encoded array of email addresses \["john\@example com", "jane\@example com"] response structure contact object fields core identity id unique contact identifier (uuid) customerid associated customer id firstname first name (max 40 chars) lastname last name (max 80 chars) name full name (max 255 chars) email email address additional information middlename middle name (max 40 chars) suffix name suffix (max 40 chars) title professional title birthday birth date (iso format yyyy mm dd) contact methods phone primary phone number mobilephone mobile phone number address information billing billingstreet , billingcity , billingstate , billingpostalcode , billingcountry shipping shippingstreet , shippingcity , shippingstate , shippingpostalcode , shippingcountry system fields createddate , createdbyid creation tracking lastmodifieddate , lastmodifiedbyid modification tracking common use cases customer support lookup // quick contact lookup for support tickets const result = await safecontactfetch(\[ticketemail]); const contact = result contacts\[0]; // display contact and customer information communication planning // build communication profiles for marketing campaigns const campaign = await commhub plancommunicationcampaign(emails, 'newsletter'); // plan multi channel outreach contact directory // build comprehensive contact directory const directory = await contactdirectory buildcontactdirectory(customerids); // enable search and organization features performance optimization efficient contact operations batch email lookups include multiple emails in single api call validate email formats client side validation before api calls cache contact data store frequently accessed contact information error recovery implement graceful handling of missing contacts rate limiting respect limits 1000 requests per minute in production implement backoff use exponential backoff for retry logic monitor usage track api consumption patterns this comprehensive guide enables you to efficiently retrieve and manage contact data using the nue lifecycle management api, supporting everything from simple email lookups to complex communication planning and contact directory management