Updating Contact
This guide provides comprehensive instructions for updating existing contacts using the Nue Lifecycle Management API. Learn how to modify contact information, update professional details, and implement efficient contact management workflows.
Prerequisites
Before you begin, ensure you have:
- A valid Nue API key with contact update permissions
- Valid contact ID (UUID)
- Understanding of contact data structures
- Basic knowledge of REST APIs and JSON
Authentication
All contact update 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");Basic Contact Updates
Update Basic Information
Try it now: Update Contact →
const myHeaders = new Headers();
myHeaders.append("nue-api-key", "YOUR_API_KEY_HERE");
myHeaders.append("Content-Type", "application/json");
// Update basic contact information
const contactId = "contact-uuid-12345";
const updateData = {
firstName: "Jane", // Updated first name
lastName: "Smith-Johnson", // Updated last name (married)
name: "Jane Smith-Johnson", // Updated full name
email: "[email protected]", // New email
title: "Senior Software Engineer", // Promotion
phone: "+1-555-0199" // Updated phone number
};
fetch(`https://api.nue.io/contacts/${contactId}`, {
method: 'PATCH',
headers: myHeaders,
body: JSON.stringify(updateData)
})
.then(response => response.json())
.then(result => {
if (result.status === 'SUCCESS') {
const contact = result.data[0];
console.log('Contact updated successfully:', result);
console.log(`Updated: ${contact.name}`);
console.log(`Email: ${contact.email}`);
console.log(`Title: ${contact.title}`);
console.log(`Phone: ${contact.phone}`);
console.log(`Last Modified: ${contact.lastModifiedDate}`);
// Handle any warnings
if (result.warnings && result.warnings.length > 0) {
console.warn('Warnings:', result.warnings);
}
} else {
console.error('Failed to update contact:', result.error);
}
})
.catch(error => console.log('Error:', error));Update Professional Information
Modify title, role, and work-related details:
const contactId = "contact-uuid-12345";
const professionalUpdateData = {
title: "VP of Engineering", // Promoted
phone: "+1-555-0200", // New direct line
mobilePhone: "+1-555-0300", // Added mobile
// Updated business address
billingStreet: "456 Corporate Center, Suite 1200",
billingCity: "New York",
billingState: "NY",
billingPostalCode: "10001",
billingCountry: "United States"
};
fetch(`https://api.nue.io/contacts/${contactId}`, {
method: 'PATCH',
headers: myHeaders,
body: JSON.stringify(professionalUpdateData)
})
.then(response => response.json())
.then(result => {
if (result.status === 'SUCCESS') {
const contact = result.data[0];
console.log('✅ Professional information updated:');
console.log(`Name: ${contact.name}`);
console.log(`New Title: ${contact.title}`);
console.log(`Phone: ${contact.phone}`);
console.log(`Mobile: ${contact.mobilePhone}`);
console.log(`Business Address: ${contact.billingStreet}, ${contact.billingCity}, ${contact.billingState}`);
// Handle any warnings
if (result.warnings && result.warnings.length > 0) {
console.warn('Warnings:', result.warnings);
}
} else {
console.error('Failed to update professional information:', result.error);
}
})
.catch(error => console.log('Error:', error));Update Personal Information
Modify personal details and home address:
const contactId = "contact-uuid-12345";
const personalUpdateData = {
middleName: "Marie", // Added middle name
suffix: "PhD", // Added suffix for degree
birthday: "1985-07-15", // Corrected birthday
mobilePhone: "+1-555-0350", // Updated mobile number
// Updated home/shipping address
shippingStreet: "789 Residential Lane",
shippingCity: "Brooklyn",
shippingState: "NY",
shippingPostalCode: "11201",
shippingCountry: "United States"
};
fetch(`https://api.nue.io/contacts/${contactId}`, {
method: 'PATCH',
headers: myHeaders,
body: JSON.stringify(personalUpdateData)
})
.then(response => response.json())
.then(result => {
if (result.status === 'SUCCESS') {
const contact = result.data[0];
console.log('✅ Personal information updated:');
console.log(`Full Name: ${contact.firstName} ${contact.middleName} ${contact.lastName} ${contact.suffix}`);
console.log(`Birthday: ${contact.birthday}`);
console.log(`Mobile: ${contact.mobilePhone}`);
console.log(`Home Address: ${contact.shippingStreet}, ${contact.shippingCity}, ${contact.shippingState}`);
// Handle any warnings
if (result.warnings && result.warnings.length > 0) {
console.warn('Warnings:', result.warnings);
}
} else {
console.error('Failed to update personal information:', result.error);
}
})
.catch(error => console.log('Error:', error));Advanced Contact Update Patterns
Contact Lifecycle Management
Handle contact role changes and career progression:
class ContactLifecycleManager {
constructor(apiKey) {
this.apiKey = apiKey;
this.headers = new Headers();
this.headers.append("nue-api-key", apiKey);
this.headers.append("Content-Type", "application/json");
}
async promoteContact(contactId, promotionData) {
try {
console.log(`🚀 Promoting contact ${contactId}...`);
// Prepare promotion update
const promotionUpdate = {
title: promotionData.newTitle,
// Update contact methods for new role
phone: promotionData.newPhone || undefined,
mobilePhone: promotionData.newMobile || undefined,
// Update address if new office location
...(promotionData.newAddress && {
billingStreet: promotionData.newAddress.street,
billingCity: promotionData.newAddress.city,
billingState: promotionData.newAddress.state,
billingPostalCode: promotionData.newAddress.postalCode,
billingCountry: promotionData.newAddress.country
})
};
const response = await fetch(`https://api.nue.io/contacts/${contactId}`, {
method: 'PATCH',
headers: this.headers,
body: JSON.stringify(promotionUpdate)
});
if (!response.ok) {
throw new Error(`Promotion failed: ${response.status} ${response.statusText}`);
}
const updatedContact = await response.json();
console.log('✅ Promotion completed:');
console.log(` Contact: ${updatedContact.name}`);
console.log(` Previous Title: ${promotionData.previousTitle || 'Unknown'}`);
console.log(` New Title: ${updatedContact.title}`);
console.log(` Effective Date: ${new Date().toISOString().split('T')[0]}`);
// Log promotion for audit trail
await this.logContactChange(contactId, 'promotion', {
from: promotionData.previousTitle,
to: updatedContact.title,
date: new Date().toISOString()
});
return updatedContact;
} catch (error) {
console.error('❌ Contact promotion failed:', error);
throw error;
}
}
async updateContactLocation(contactId, relocationData) {
try {
console.log(`📍 Relocating contact ${contactId}...`);
const relocationUpdate = {
// Update business address
billingStreet: relocationData.newOffice.street,
billingCity: relocationData.newOffice.city,
billingState: relocationData.newOffice.state,
billingPostalCode: relocationData.newOffice.postalCode,
billingCountry: relocationData.newOffice.country,
// Update personal address if provided
...(relocationData.newHome && {
shippingStreet: relocationData.newHome.street,
shippingCity: relocationData.newHome.city,
shippingState: relocationData.newHome.state,
shippingPostalCode: relocationData.newHome.postalCode,
shippingCountry: relocationData.newHome.country
}),
// Update phone numbers if they changed due to location
...(relocationData.newPhone && { phone: relocationData.newPhone }),
...(relocationData.newMobile && { mobilePhone: relocationData.newMobile })
};
const response = await fetch(`https://api.nue.io/contacts/${contactId}`, {
method: 'PATCH',
headers: this.headers,
body: JSON.stringify(relocationUpdate)
});
if (!response.ok) {
throw new Error(`Relocation failed: ${response.status}`);
}
const contact = await response.json();
console.log('✅ Contact relocation completed:');
console.log(` Contact: ${contact.name}`);
console.log(` New Office: ${contact.billingCity}, ${contact.billingState}`);
if (contact.shippingCity) {
console.log(` New Home: ${contact.shippingCity}, ${contact.shippingState}`);
}
return contact;
} catch (error) {
console.error('❌ Contact relocation failed:', error);
throw error;
}
}
async updateContactDetails(contactId, personalChanges) {
try {
console.log(`👤 Updating personal details for contact ${contactId}...`);
// Handle name changes (marriage, legal name change, etc.)
const nameUpdate = {};
if (personalChanges.nameChange) {
nameUpdate.firstName = personalChanges.nameChange.firstName || undefined;
nameUpdate.lastName = personalChanges.nameChange.lastName || undefined;
nameUpdate.middleName = personalChanges.nameChange.middleName || undefined;
nameUpdate.suffix = personalChanges.nameChange.suffix || undefined;
// Reconstruct full name
const nameParts = [
personalChanges.nameChange.firstName,
personalChanges.nameChange.middleName,
personalChanges.nameChange.lastName,
personalChanges.nameChange.suffix
].filter(Boolean);
nameUpdate.name = nameParts.join(' ');
}
const personalUpdate = {
...nameUpdate,
...(personalChanges.newEmail && { email: personalChanges.newEmail }),
...(personalChanges.newBirthday && { birthday: personalChanges.newBirthday }),
...(personalChanges.newMobile && { mobilePhone: personalChanges.newMobile })
};
const response = await fetch(`https://api.nue.io/contacts/${contactId}`, {
method: 'PATCH',
headers: this.headers,
body: JSON.stringify(personalUpdate)
});
if (!response.ok) {
throw new Error(`Personal update failed: ${response.status}`);
}
const contact = await response.json();
console.log('✅ Personal details updated:');
console.log(` Name: ${contact.name}`);
console.log(` Email: ${contact.email}`);
if (contact.birthday) {
console.log(` Birthday: ${contact.birthday}`);
}
return contact;
} catch (error) {
console.error('❌ Personal details update failed:', error);
throw error;
}
}
async logContactChange(contactId, changeType, changeData) {
// In a real implementation, this would log to an audit system
console.log(`📝 Logging ${changeType} for contact ${contactId}:`, changeData);
}
}
// Usage examples
const lifecycleManager = new ContactLifecycleManager("YOUR_API_KEY_HERE");
// Promote contact
lifecycleManager.promoteContact(
"contact-uuid-12345",
{
previousTitle: "Senior Software Engineer",
newTitle: "Engineering Manager",
newPhone: "+1-555-0400",
newAddress: {
street: "100 Executive Plaza, Suite 2000",
city: "San Francisco",
state: "CA",
postalCode: "94105",
country: "United States"
}
}
).then(contact => {
console.log('Promotion completed successfully');
});
// Relocate contact
lifecycleManager.updateContactLocation(
"contact-uuid-12345",
{
newOffice: {
street: "200 Tech Park Drive",
city: "Austin",
state: "TX",
postalCode: "73301",
country: "United States"
},
newHome: {
street: "456 Residential Circle",
city: "Austin",
state: "TX",
postalCode: "73344",
country: "United States"
},
newMobile: "+1-512-555-0200"
}
).then(contact => {
console.log('Relocation completed successfully');
});
// Update personal details (marriage, name change)
lifecycleManager.updateContactDetails(
"contact-uuid-12345",
{
nameChange: {
firstName: "Jane",
lastName: "Smith-Johnson", // Married name
middleName: "Marie"
},
newEmail: "[email protected]",
newMobile: "+1-555-0555"
}
).then(contact => {
console.log('Personal details updated successfully');
});Bulk Contact Updates
Efficiently update multiple contacts with similar changes:
class BulkContactUpdater {
constructor(apiKey) {
this.apiKey = apiKey;
this.headers = new Headers();
this.headers.append("nue-api-key", apiKey);
this.headers.append("Content-Type", "application/json");
}
async updateMultipleContacts(contactUpdates, options = {}) {
const results = {
successful: [],
failed: [],
total: contactUpdates.length
};
console.log(`📝 Starting bulk update of ${contactUpdates.length} contacts...`);
// Process updates with controlled concurrency
const concurrency = options.concurrency || 5;
for (let i = 0; i < contactUpdates.length; i += concurrency) {
const batch = contactUpdates.slice(i, i + concurrency);
const batchPromises = batch.map(update =>
this.updateSingleContact(update.contactId, update.data)
.then(contact => ({ contactId: update.contactId, contact, success: true }))
.catch(error => ({ contactId: update.contactId, error: error.message, success: false }))
);
const batchResults = await Promise.all(batchPromises);
batchResults.forEach(result => {
if (result.success) {
results.successful.push(result);
console.log(`✅ Updated: ${result.contact.name}`);
} else {
results.failed.push(result);
console.log(`❌ Failed: ${result.contactId} - ${result.error}`);
}
});
// Add delay between batches to respect rate limits
if (i + concurrency < contactUpdates.length) {
await this.delay(1000); // 1 second delay
}
}
console.log(`\n📊 Bulk update completed:`);
console.log(` Successful: ${results.successful.length}`);
console.log(` Failed: ${results.failed.length}`);
console.log(` Total: ${results.total}`);
return results;
}
async updateSingleContact(contactId, updateData) {
const response = await fetch(`https://api.nue.io/contacts/${contactId}`, {
method: 'PATCH',
headers: this.headers,
body: JSON.stringify(updateData)
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const result = await response.json();
if (result.status === 'SUCCESS') {
return result.data[0];
} else {
throw new Error(`Contact update failed: ${result.error}`);
}
}
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
// Usage example - Update office address for multiple contacts
const bulkUpdater = new BulkContactUpdater("YOUR_API_KEY_HERE");
const contactUpdates = [
{
contactId: "contact-1-id",
data: {
billingStreet: "New Corporate Campus, Building A",
billingCity: "Seattle",
billingState: "WA",
billingPostalCode: "98101"
}
},
{
contactId: "contact-2-id",
data: {
billingStreet: "New Corporate Campus, Building A",
billingCity: "Seattle",
billingState: "WA",
billingPostalCode: "98101"
}
},
{
contactId: "contact-3-id",
data: {
billingStreet: "New Corporate Campus, Building A",
billingCity: "Seattle",
billingState: "WA",
billingPostalCode: "98101"
}
}
];
bulkUpdater.updateMultipleContacts(contactUpdates, { concurrency: 3 })
.then(results => {
console.log('Bulk update process completed');
if (results.failed.length > 0) {
console.log('Failed updates need attention:', results.failed);
}
});Contact Data Synchronization
Keep contact information synchronized across systems:
class ContactSyncManager {
constructor(apiKey) {
this.apiKey = apiKey;
this.headers = new Headers();
this.headers.append("nue-api-key", apiKey);
this.headers.append("Content-Type", "application/json");
}
async syncContactFromExternalSystem(contactId, externalContactData) {
try {
console.log(`🔄 Syncing contact ${contactId} from external system...`);
// Map external data to Nue contact format
const syncUpdate = this.mapExternalToNueFormat(externalContactData);
// Validate changes before applying
const currentContact = await this.getCurrentContact(contactId);
const changeSet = this.detectChanges(currentContact, syncUpdate);
if (Object.keys(changeSet).length === 0) {
console.log('✅ Contact is already in sync - no changes needed');
return currentContact;
}
console.log(`📝 Detected changes:`, Object.keys(changeSet));
// Apply changes
const response = await fetch(`https://api.nue.io/contacts/${contactId}`, {
method: 'PATCH',
headers: this.headers,
body: JSON.stringify(changeSet)
});
if (!response.ok) {
throw new Error(`Sync failed: ${response.status}`);
}
const updatedContact = await response.json();
console.log('✅ Contact synchronized successfully');
console.log(` Contact: ${updatedContact.name}`);
console.log(` Updated fields: ${Object.keys(changeSet).join(', ')}`);
return updatedContact;
} catch (error) {
console.error('❌ Contact sync failed:', error);
throw error;
}
}
async getCurrentContact(contactId) {
// In practice, you might fetch the current contact to compare
// For this example, we'll simulate it
return {
id: contactId,
name: "Current Name",
email: "[email protected]",
title: "Current Title"
};
}
mapExternalToNueFormat(externalData) {
// Map external system fields to Nue contact fields
return {
firstName: externalData.first_name,
lastName: externalData.last_name,
name: `${externalData.first_name} ${externalData.last_name}`,
email: externalData.email_address,
title: externalData.job_title,
phone: externalData.work_phone,
mobilePhone: externalData.mobile_phone,
billingStreet: externalData.office_address?.street,
billingCity: externalData.office_address?.city,
billingState: externalData.office_address?.state,
billingPostalCode: externalData.office_address?.zip_code,
billingCountry: externalData.office_address?.country
};
}
detectChanges(current, updated) {
const changes = {};
Object.keys(updated).forEach(key => {
if (updated[key] !== undefined && current[key] !== updated[key]) {
changes[key] = updated[key];
}
});
return changes;
}
}
// Usage
const syncManager = new ContactSyncManager("YOUR_API_KEY_HERE");
const externalContactData = {
first_name: "John",
last_name: "Smith",
email_address: "[email protected]",
job_title: "Senior Director",
work_phone: "+1-555-0600",
mobile_phone: "+1-555-0700",
office_address: {
street: "300 Innovation Drive",
city: "Boston",
state: "MA",
zip_code: "02101",
country: "United States"
}
};
syncManager.syncContactFromExternalSystem("contact-uuid-12345", externalContactData)
.then(contact => {
console.log('Contact sync completed successfully');
});Error Handling and Validation
Robust Contact Update Implementation
async function safeContactUpdate(contactId, updateData, options = {}) {
const myHeaders = new Headers();
myHeaders.append("nue-api-key", "YOUR_API_KEY_HERE");
myHeaders.append("Content-Type", "application/json");
try {
// Validate contact ID
if (!contactId || typeof contactId !== 'string') {
throw new Error('Valid contact ID is required');
}
// Validate update data
if (!updateData || typeof updateData !== 'object') {
throw new Error('Update data is required and must be an object');
}
// Remove read-only fields if present
const sanitizedData = { ...updateData };
delete sanitizedData.id;
delete sanitizedData.customerId;
delete sanitizedData.createdDate;
delete sanitizedData.createdById;
delete sanitizedData.lastModifiedDate;
delete sanitizedData.lastModifiedById;
// Validate specific fields
if (sanitizedData.email && !isValidEmail(sanitizedData.email)) {
throw new Error('Invalid email format');
}
if (sanitizedData.phone && !isValidPhone(sanitizedData.phone)) {
throw new Error('Invalid phone number format');
}
if (sanitizedData.mobilePhone && !isValidPhone(sanitizedData.mobilePhone)) {
throw new Error('Invalid mobile phone number format');
}
if (sanitizedData.birthday && !isValidDate(sanitizedData.birthday)) {
throw new Error('Invalid birthday format, use YYYY-MM-DD');
}
// Validate field lengths
if (sanitizedData.firstName && sanitizedData.firstName.length > 40) {
throw new Error('firstName cannot exceed 40 characters');
}
if (sanitizedData.lastName && sanitizedData.lastName.length > 80) {
throw new Error('lastName cannot exceed 80 characters');
}
if (sanitizedData.name && sanitizedData.name.length > 255) {
throw new Error('name cannot exceed 255 characters');
}
// Perform update
const response = await fetch(`https://api.nue.io/contacts/${contactId}`, {
method: 'PATCH',
headers: myHeaders,
body: JSON.stringify(sanitizedData)
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Update failed: ${response.status} ${errorText}`);
}
const updatedContact = await response.json();
// Log successful update
if (options.verbose) {
console.log(`✅ Contact ${updatedContact.name} updated successfully`);
console.log(` Last Modified: ${updatedContact.lastModifiedDate}`);
}
return {
success: true,
contact: updatedContact,
contactId: contactId
};
} catch (error) {
console.error(`❌ Failed to update contact ${contactId}:`, error.message);
return {
success: false,
error: error.message,
contactId: contactId
};
}
}
function isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
function isValidPhone(phone) {
const phoneRegex = /^\+?[\d\s\-\(\)]{10,}$/;
return phoneRegex.test(phone);
}
function isValidDate(dateString) {
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
if (!dateRegex.test(dateString)) return false;
const date = new Date(dateString);
return date instanceof Date && !isNaN(date) && date.toISOString().split('T')[0] === dateString;
}
// Usage with error handling
safeContactUpdate(
"contact-uuid-12345",
{
email: "[email protected]",
title: "Senior Manager",
phone: "+1-555-0199",
mobilePhone: "+1-555-0299"
},
{ verbose: true }
).then(result => {
if (result.success) {
console.log('Update completed:', result.contact.name);
} else {
console.log('Update failed, implement retry or escalation logic');
}
});Updatable Fields Reference
Personal Information
- firstName - First name (max 40 chars)
- lastName - Last name (max 80 chars)
- middleName - Middle name (max 40 chars)
- suffix - Name suffix (max 40 chars)
- name - Full name (max 255 chars)
- birthday - Birth date (YYYY-MM-DD format)
Contact Information
- email - Email address
- phone - Primary phone number
- mobilePhone - Mobile phone number
Professional Information
- title - Professional title
Address Information
- Billing: billingStreet, billingCity, billingState, billingPostalCode, billingCountry
- Shipping: shippingStreet, shippingCity, shippingState, shippingPostalCode, shippingCountry
Common Update Scenarios
Name Change (Marriage/Legal)
// Marriage or legal name change
const nameChange = {
firstName: "Jane",
lastName: "Smith-Johnson",
name: "Jane Smith-Johnson",
email: "[email protected]"
};Job Promotion
// Career advancement
const promotion = {
title: "Senior Director of Engineering",
phone: "+1-555-0400" // New direct line
};Office Relocation
// Company moved offices
const relocation = {
billingStreet: "New Office Building",
billingCity: "New City",
billingState: "NY",
phone: "+1-555-0500"
};Contact Method Updates
// New phone numbers or email
const contactUpdate = {
email: "[email protected]",
mobilePhone: "+1-555-0600"
};Best Practices
Update Strategy
- Validate data before sending updates
- Use partial updates - only send changed fields
- Implement retry logic for transient failures
- Log all updates for audit trails
- Handle concurrent updates appropriately
Performance
- Batch related updates when possible
- Respect rate limits (contact Nue support to confirm your limits or request an increase)
- Use controlled concurrency for bulk operations
- Implement proper error handling and recovery
Data Integrity
- Validate business rules before updates
- Maintain data consistency across related records
- Handle dependent data appropriately (e.g., email changes affecting logins)
- Implement proper versioning for audit trails
Communication
- Notify stakeholders of important changes (role changes, contact info)
- Update external systems when contact information changes
- Maintain communication preferences and opt-out lists
- Document change reasons for compliance
This comprehensive guide enables you to efficiently update contact information using the Nue Lifecycle Management API, supporting everything from simple field updates to complex lifecycle management and synchronization workflows.