Fetching Contacts
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 customerFiltering
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: 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 = ["[email protected]", "[email protected]"];
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 = "[email protected]";
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 = [
"[email protected]",
"[email protected]",
"[email protected]"
];
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([
"[email protected]",
"invalid-email",
"[email protected]"
]).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 |
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 informationCommunication Planning
// Build communication profiles for marketing campaigns
const campaign = await commHub.planCommunicationCampaign(emails, 'newsletter');
// Plan multi-channel outreachContact Directory
// Build comprehensive contact directory
const directory = await contactDirectory.buildContactDirectory(customerIds);
// Enable search and organization featuresPerformance 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: Rate limits apply; contact Nue support to confirm your limits or request an increase
- 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.