Creating Contacts
This guide provides comprehensive instructions for creating new contacts using the Nue Lifecycle Management API. Learn how to create single or multiple contacts for customers, set up complete contact profiles, and implement efficient contact onboarding workflows.
Prerequisites
Before you begin, ensure you have:
- A valid Nue API key with contact creation permissions
- Valid customer ID to associate contacts with
- Understanding of contact data requirements
- Basic knowledge of REST APIs and JSON
Authentication
All contact creation 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 Creation
Create Single Contact
Try it now: Create Customer Contacts →
const myHeaders = new Headers();
myHeaders.append("nue-api-key", "YOUR_API_KEY_HERE");
myHeaders.append("Content-Type", "application/json");
// Create a single contact for a customer
const customerId = "d2e04653-ae90-49df-a986-134cf64f6d03";
const contactData = [{
firstName: "John",
lastName: "Doe",
name: "John Doe", // Required: Full name
email: "[email protected]" // Required: Email address
}];
fetch(`https://api.nue.io/customers/${customerId}/contacts`, {
method: 'POST',
headers: myHeaders,
body: JSON.stringify(contactData)
})
.then(response => response.json())
.then(result => {
if (result.status === 'SUCCESS') {
const contacts = result.data;
console.log('Contact created successfully:', result);
if (contacts.length > 0) {
const contact = contacts[0];
console.log(`✅ Created: ${contact.name}`);
console.log(`Contact ID: ${contact.id}`);
console.log(`Email: ${contact.email}`);
console.log(`Customer ID: ${contact.customerId}`);
console.log(`Created Date: ${contact.createdDate}`);
}
// Handle any warnings
if (result.warnings && result.warnings.length > 0) {
console.warn('Warnings:', result.warnings);
}
} else {
console.error('Failed to create contact:', result.error);
}
})
.catch(error => console.log('Error:', error));Create Contact with Complete Information
Create a contact with comprehensive personal and address details:
const customerId = "d2e04653-ae90-49df-a986-134cf64f6d03";
const comprehensiveContact = [{
// Required fields
firstName: "Jane",
lastName: "Smith",
name: "Jane Smith",
email: "[email protected]",
// Optional personal information
middleName: "Elizabeth",
suffix: "Jr.",
title: "Chief Technology Officer",
birthday: "1985-03-15", // ISO format YYYY-MM-DD
// Contact information
phone: "+1-555-0123",
mobilePhone: "+1-555-0124",
// Billing address
billingStreet: "123 Business Plaza, Suite 400",
billingCity: "San Francisco",
billingState: "CA",
billingPostalCode: "94105",
billingCountry: "United States",
// Shipping address (if different)
shippingStreet: "456 Home Street",
shippingCity: "Oakland",
shippingState: "CA",
shippingPostalCode: "94612",
shippingCountry: "United States"
}];
fetch(`https://api.nue.io/customers/${customerId}/contacts`, {
method: 'POST',
headers: myHeaders,
body: JSON.stringify(comprehensiveContact)
})
.then(response => response.json())
.then(result => {
if (result.status === 'SUCCESS') {
const contacts = result.data;
console.log('Comprehensive contact created:', result);
const contact = contacts[0];
console.log(`\n✅ Contact Created Successfully`);
console.log(`Name: ${contact.firstName} ${contact.middleName} ${contact.lastName} ${contact.suffix}`);
console.log(`Title: ${contact.title}`);
console.log(`Email: ${contact.email}`);
console.log(`Phone: ${contact.phone}`);
console.log(`Mobile: ${contact.mobilePhone}`);
console.log(`Birthday: ${contact.birthday}`);
console.log(`Customer ID: ${contact.customerId}`);
// Handle any warnings
if (result.warnings && result.warnings.length > 0) {
console.warn('Warnings:', result.warnings);
}
} else {
console.error('Failed to create contact:', result.error);
}
})
.catch(error => console.log('Error:', error));Bulk Contact Creation
Create Multiple Contacts
Efficiently create multiple contacts for a customer in a single API call:
const customerId = "d2e04653-ae90-49df-a986-134cf64f6d03";
const bulkContacts = [
{
firstName: "Robert",
lastName: "Johnson",
name: "Robert Johnson",
email: "[email protected]",
title: "Chief Financial Officer",
phone: "+1-555-0200",
billingStreet: "123 Business Plaza, Suite 400",
billingCity: "San Francisco",
billingState: "CA",
billingPostalCode: "94105",
billingCountry: "United States"
},
{
firstName: "Sarah",
lastName: "Williams",
name: "Sarah Williams",
email: "[email protected]",
title: "VP of Operations",
phone: "+1-555-0201",
mobilePhone: "+1-555-0301",
billingStreet: "123 Business Plaza, Suite 400",
billingCity: "San Francisco",
billingState: "CA",
billingPostalCode: "94105",
billingCountry: "United States"
},
{
firstName: "Michael",
lastName: "Brown",
name: "Michael Brown",
email: "[email protected]",
title: "Director of Engineering",
phone: "+1-555-0202",
mobilePhone: "+1-555-0302",
birthday: "1988-07-22"
}
];
fetch(`https://api.nue.io/customers/${customerId}/contacts`, {
method: 'POST',
headers: myHeaders,
body: JSON.stringify(bulkContacts)
})
.then(response => response.json())
.then(result => {
if (result.status === 'SUCCESS') {
const contacts = result.data;
console.log(`\n✅ Successfully created ${contacts.length} contacts:`);
contacts.forEach((contact, index) => {
console.log(`\n${index + 1}. ${contact.name}`);
console.log(` ID: ${contact.id}`);
console.log(` Email: ${contact.email}`);
console.log(` Title: ${contact.title || 'Not specified'}`);
console.log(` Phone: ${contact.phone || 'Not provided'}`);
console.log(` Mobile: ${contact.mobilePhone || 'Not provided'}`);
});
// Handle any warnings
if (result.warnings && result.warnings.length > 0) {
console.warn('Warnings:', result.warnings);
}
} else {
console.error('Failed to create contacts:', result.error);
}
})
.catch(error => console.log('Error:', error));Advanced Contact Creation Patterns
Contact Onboarding Service
Implement a complete contact onboarding process with validation and enrichment:
class ContactOnboardingService {
constructor(apiKey) {
this.apiKey = apiKey;
this.headers = new Headers();
this.headers.append("nue-api-key", apiKey);
this.headers.append("Content-Type", "application/json");
}
async onboardNewContact(customerId, contactInput) {
try {
// Step 1: Validate contact data
const validatedData = this.validateContactData(contactInput);
// Step 2: Enrich with defaults and formatting
const enrichedData = this.enrichContactData(validatedData);
// Step 3: Check for duplicates
await this.checkForDuplicates(customerId, enrichedData.email);
// Step 4: Create contact
const createdContact = await this.createContact(customerId, enrichedData);
// Step 5: Set up additional configurations
await this.setupContactConfigurations(createdContact);
// Step 6: Send welcome communications
await this.sendWelcomeEmail(createdContact);
return {
success: true,
contact: createdContact,
message: `Contact ${createdContact.name} onboarded successfully`
};
} catch (error) {
console.error('Contact onboarding failed:', error);
return {
success: false,
error: error.message,
contactInput
};
}
}
validateContactData(input) {
const errors = [];
// Required field validation
if (!input.firstName || input.firstName.trim().length === 0) {
errors.push('firstName: First name is required');
}
if (!input.lastName || input.lastName.trim().length === 0) {
errors.push('lastName: Last name is required');
}
if (!input.name || input.name.trim().length === 0) {
errors.push('name: Full name is required');
}
if (!input.email || !this.isValidEmail(input.email)) {
errors.push('email: Valid email address is required');
}
// Length validations
if (input.firstName && input.firstName.length > 40) {
errors.push('firstName: Maximum 40 characters allowed');
}
if (input.lastName && input.lastName.length > 80) {
errors.push('lastName: Maximum 80 characters allowed');
}
if (input.name && input.name.length > 255) {
errors.push('name: Maximum 255 characters allowed');
}
if (input.middleName && input.middleName.length > 40) {
errors.push('middleName: Maximum 40 characters allowed');
}
if (input.suffix && input.suffix.length > 40) {
errors.push('suffix: Maximum 40 characters allowed');
}
// Phone validation
if (input.phone && !this.isValidPhone(input.phone)) {
errors.push('phone: Invalid phone number format');
}
if (input.mobilePhone && !this.isValidPhone(input.mobilePhone)) {
errors.push('mobilePhone: Invalid mobile phone number format');
}
// Birthday validation
if (input.birthday && !this.isValidDate(input.birthday)) {
errors.push('birthday: Invalid date format, use YYYY-MM-DD');
}
if (errors.length > 0) {
throw new Error(`Validation failed: ${errors.join(', ')}`);
}
return input;
}
enrichContactData(input) {
// Auto-generate full name if not provided
const enriched = {
...input,
name: input.name || `${input.firstName} ${input.lastName}`.trim()
};
// Normalize email to lowercase
enriched.email = enriched.email.toLowerCase().trim();
// Format phone numbers
if (enriched.phone) {
enriched.phone = this.formatPhoneNumber(enriched.phone);
}
if (enriched.mobilePhone) {
enriched.mobilePhone = this.formatPhoneNumber(enriched.mobilePhone);
}
// Standardize title case for names
enriched.firstName = this.toTitleCase(enriched.firstName);
enriched.lastName = this.toTitleCase(enriched.lastName);
if (enriched.middleName) {
enriched.middleName = this.toTitleCase(enriched.middleName);
}
return enriched;
}
async checkForDuplicates(customerId, email) {
// In a real implementation, you might want to check for existing contacts
// with the same email address for this customer
console.log(`Checking for duplicate contacts with email: ${email}`);
// For now, we'll just log - in practice you'd fetch existing contacts
// and compare email addresses
}
async createContact(customerId, contactData) {
const response = await fetch(`https://api.nue.io/customers/${customerId}/contacts`, {
method: 'POST',
headers: this.headers,
body: JSON.stringify([contactData])
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Contact creation failed: ${response.status} ${errorText}`);
}
const result = await response.json();
if (result.status === 'SUCCESS') {
return result.data[0];
} else {
throw new Error(`Contact creation failed: ${result.error}`);
}
}
async setupContactConfigurations(contact) {
// Additional setup steps could include:
// - Setting up communication preferences
// - Adding to distribution lists
// - Setting up access permissions
// - Integrating with external systems
console.log(`Setting up configurations for ${contact.name}...`);
console.log(`✅ Configurations completed for contact ${contact.id}`);
}
async sendWelcomeEmail(contact) {
// Integration with email service
console.log(`📧 Sending welcome email to ${contact.email}...`);
// Mock email service integration
const emailData = {
to: contact.email,
subject: `Welcome ${contact.firstName}!`,
template: 'contact_welcome',
data: {
firstName: contact.firstName,
contactId: contact.id,
title: contact.title
}
};
console.log(`✅ Welcome email queued for ${contact.email}`);
}
isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
isValidPhone(phone) {
const phoneRegex = /^\+?[\d\s\-\(\)]{10,}$/;
return phoneRegex.test(phone);
}
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;
}
formatPhoneNumber(phone) {
// Basic phone formatting - remove extra spaces and standardize format
return phone.replace(/\s+/g, ' ').trim();
}
toTitleCase(str) {
return str.replace(/\w\S*/g, (txt) =>
txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()
);
}
}
// Usage example
const onboardingService = new ContactOnboardingService("YOUR_API_KEY_HERE");
const newContactData = {
firstName: "alice",
lastName: "johnson",
email: "[email protected]",
title: "Senior Software Engineer",
phone: "555-0150",
mobilePhone: "+1 555 0250",
birthday: "1990-12-05",
billingStreet: "789 Tech Avenue",
billingCity: "Austin",
billingState: "TX",
billingPostalCode: "73301",
billingCountry: "United States"
};
onboardingService.onboardNewContact(
"d2e04653-ae90-49df-a986-134cf64f6d03",
newContactData
).then(result => {
if (result.success) {
console.log('\n🎉 Contact onboarding completed successfully!');
console.log(`Contact: ${result.contact.name}`);
console.log(`ID: ${result.contact.id}`);
console.log(`Email: ${result.contact.email}`);
} else {
console.error('❌ Onboarding failed:', result.error);
}
});Team Contact Creation Workflow
Create contacts for entire teams with role-based configurations:
class TeamContactManager {
constructor(apiKey) {
this.apiKey = apiKey;
this.headers = new Headers();
this.headers.append("nue-api-key", apiKey);
this.headers.append("Content-Type", "application/json");
}
async createTeamContacts(customerId, teamData) {
try {
console.log(`👥 Creating team contacts for customer ${customerId}...`);
// Prepare team contacts with role-based defaults
const teamContacts = teamData.members.map(member => {
const contact = {
firstName: member.firstName,
lastName: member.lastName,
name: `${member.firstName} ${member.lastName}`,
email: member.email,
title: member.title || this.getDefaultTitle(member.role),
phone: member.phone,
mobilePhone: member.mobilePhone,
...this.getRoleBasedDefaults(member.role),
...teamData.commonAddress
};
return contact;
});
// Create all contacts in batch
const response = await fetch(`https://api.nue.io/customers/${customerId}/contacts`, {
method: 'POST',
headers: this.headers,
body: JSON.stringify(teamContacts)
});
if (!response.ok) {
throw new Error(`Team creation failed: ${response.status}`);
}
const createdContacts = await response.json();
// Organize by role for reporting
const teamStructure = this.organizeTeamByRole(createdContacts, teamData.members);
console.log(`✅ Successfully created ${createdContacts.length} team contacts:`);
Object.entries(teamStructure).forEach(([role, contacts]) => {
console.log(`\n👔 ${role} (${contacts.length}):`);
contacts.forEach(contact => {
console.log(` • ${contact.name} - ${contact.email}`);
});
});
return {
contacts: createdContacts,
teamStructure,
summary: {
totalMembers: createdContacts.length,
roles: Object.keys(teamStructure),
customerId: customerId
}
};
} catch (error) {
console.error('Team contact creation failed:', error);
throw error;
}
}
getDefaultTitle(role) {
const roleTitleMap = {
'executive': 'Executive',
'manager': 'Manager',
'lead': 'Team Lead',
'senior': 'Senior Specialist',
'regular': 'Specialist',
'admin': 'Administrator'
};
return roleTitleMap[role] || 'Team Member';
}
getRoleBasedDefaults(role) {
// Role-based default configurations
const roleDefaults = {
'executive': {
// Executives might need special handling
},
'manager': {
// Managers might have different requirements
},
'admin': {
// Administrators might need specific access
}
};
return roleDefaults[role] || {};
}
organizeTeamByRole(createdContacts, originalMembers) {
const teamStructure = {};
createdContacts.forEach((contact, index) => {
const memberData = originalMembers[index];
const role = memberData.role || 'regular';
if (!teamStructure[role]) {
teamStructure[role] = [];
}
teamStructure[role].push({
...contact,
role: role
});
});
return teamStructure;
}
}
// Usage example
const teamManager = new TeamContactManager("YOUR_API_KEY_HERE");
const teamData = {
commonAddress: {
billingStreet: "100 Corporate Plaza",
billingCity: "Seattle",
billingState: "WA",
billingPostalCode: "98101",
billingCountry: "United States"
},
members: [
{
firstName: "David",
lastName: "Chen",
email: "[email protected]",
role: "executive",
title: "CEO",
phone: "+1-555-0300"
},
{
firstName: "Lisa",
lastName: "Rodriguez",
email: "[email protected]",
role: "manager",
title: "VP Engineering",
phone: "+1-555-0301",
mobilePhone: "+1-555-0401"
},
{
firstName: "Tom",
lastName: "Wilson",
email: "[email protected]",
role: "lead",
title: "Technical Lead",
phone: "+1-555-0302"
},
{
firstName: "Emma",
lastName: "Davis",
email: "[email protected]",
role: "regular",
title: "Software Engineer",
mobilePhone: "+1-555-0402"
}
]
};
teamManager.createTeamContacts(
"d2e04653-ae90-49df-a986-134cf64f6d03",
teamData
).then(result => {
console.log(`\n🎉 Team setup completed!`);
console.log(`Total members: ${result.summary.totalMembers}`);
console.log(`Roles: ${result.summary.roles.join(', ')}`);
});Contact Creation with Validation
Implement comprehensive validation and error handling:
class ContactValidator {
static validate(contactData) {
const errors = [];
// Required fields
if (!contactData.firstName?.trim()) {
errors.push('firstName: First name is required');
}
if (!contactData.lastName?.trim()) {
errors.push('lastName: Last name is required');
}
if (!contactData.name?.trim()) {
errors.push('name: Full name is required');
}
if (!contactData.email?.trim()) {
errors.push('email: Email address is required');
} else if (!this.isValidEmail(contactData.email)) {
errors.push('email: Invalid email format');
}
// Length validations
if (contactData.firstName && contactData.firstName.length > 40) {
errors.push('firstName: Maximum 40 characters allowed');
}
if (contactData.lastName && contactData.lastName.length > 80) {
errors.push('lastName: Maximum 80 characters allowed');
}
if (contactData.name && contactData.name.length > 255) {
errors.push('name: Maximum 255 characters allowed');
}
if (contactData.middleName && contactData.middleName.length > 40) {
errors.push('middleName: Maximum 40 characters allowed');
}
if (contactData.suffix && contactData.suffix.length > 40) {
errors.push('suffix: Maximum 40 characters allowed');
}
// Phone validations
if (contactData.phone && !this.isValidPhone(contactData.phone)) {
errors.push('phone: Invalid phone number format');
}
if (contactData.mobilePhone && !this.isValidPhone(contactData.mobilePhone)) {
errors.push('mobilePhone: Invalid mobile phone number format');
}
// Birthday validation
if (contactData.birthday && !this.isValidDate(contactData.birthday)) {
errors.push('birthday: Invalid date format, use YYYY-MM-DD');
}
// Address validation
if (contactData.billingStreet && !contactData.billingCity) {
errors.push('billingCity: Required when billing street is provided');
}
return {
isValid: errors.length === 0,
errors
};
}
static isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
static isValidPhone(phone) {
const phoneRegex = /^\+?[\d\s\-\(\)]{10,}$/;
return phoneRegex.test(phone);
}
static 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;
}
}
async function createValidatedContact(customerId, contactData) {
const myHeaders = new Headers();
myHeaders.append("nue-api-key", "YOUR_API_KEY_HERE");
myHeaders.append("Content-Type", "application/json");
try {
// Validate input data
const validation = ContactValidator.validate(contactData);
if (!validation.isValid) {
throw new Error(`Validation failed:\n${validation.errors.join('\n')}`);
}
// Create contact
const response = await fetch(`https://api.nue.io/customers/${customerId}/contacts`, {
method: 'POST',
headers: myHeaders,
body: JSON.stringify([contactData])
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`API Error ${response.status}: ${errorText}`);
}
const contacts = await response.json();
const contact = contacts[0];
console.log('✅ Contact created and validated successfully:');
console.log(` Name: ${contact.name}`);
console.log(` ID: ${contact.id}`);
console.log(` Email: ${contact.email}`);
console.log(` Customer ID: ${contact.customerId}`);
return contact;
} catch (error) {
console.error('❌ Contact creation failed:', error.message);
throw error;
}
}
// Usage with validation
const contactToCreate = {
firstName: "Valid",
lastName: "Contact",
name: "Valid Contact",
email: "[email protected]",
title: "Test Contact",
phone: "+1-555-0100",
birthday: "1990-01-01",
billingStreet: "123 Valid Street",
billingCity: "Valid City",
billingState: "CA",
billingPostalCode: "90210",
billingCountry: "United States"
};
createValidatedContact(
"d2e04653-ae90-49df-a986-134cf64f6d03",
contactToCreate
).then(contact => {
console.log('Contact ready for use:', contact.id);
}).catch(error => {
console.log('Handle creation failure appropriately');
});Request Body Schema
Required Fields
Field | Type | Description | Example |
|---|---|---|---|
firstName | String | First name (max 40 chars) | "John" |
lastName | String | Last name (max 80 chars) | "Doe" |
name | String | Full name (max 255 chars) | "John Doe" |
String | Email address |
Optional Personal Information
Field | Type | Description | Format/Constraints |
|---|---|---|---|
middleName | String | Middle name | Max 40 characters |
suffix | String | Name suffix | Max 40 characters |
title | String | Professional title | Free text |
birthday | String | Birth date | ISO format YYYY-MM-DD |
Contact Information
Field | Type | Description | Format |
|---|---|---|---|
phone | String | Primary phone number | International format recommended |
mobilePhone | String | Mobile phone number | International format recommended |
Address Information
Billing Address Fields:
- billingStreet, billingCity, billingState, billingPostalCode, billingCountry
Shipping Address Fields:
- shippingStreet, shippingCity, shippingState, shippingPostalCode, shippingCountry
Response Structure
Success Response (201 Created)
[
{
"id": "contact-uuid-here",
"customerId": "customer-uuid-here",
"firstName": "John",
"lastName": "Doe",
"name": "John Doe",
"email": "[email protected]",
"title": "Software Engineer",
"phone": "+1-555-0123",
"mobilePhone": "+1-555-0124",
"birthday": "1990-01-01",
"billingStreet": "123 Main St",
"billingCity": "San Francisco",
"billingState": "CA",
"billingPostalCode": "94105",
"billingCountry": "United States",
"createdDate": "2025-06-25T12:00:00Z",
"createdById": "user-id",
"lastModifiedDate": "2025-06-25T12:00:00Z",
"lastModifiedById": "user-id"
}
]Error Handling
Common Error Scenarios
Error | Description | Resolution |
|---|---|---|
400 Bad Request | Invalid request data or missing customer ID | Check required fields and customer ID |
401 Unauthorized | Invalid API key | Verify API key and permissions |
404 Not Found | Customer ID not found | Verify customer exists |
422 Validation Error | Data validation failed | Review field constraints |
429 Rate Limited | Too many requests | Implement retry with backoff |
Validation Errors
- Missing required fields: Ensure firstName, lastName, name, and email are provided
- Invalid email format: Use proper email validation
- Field length exceeded: Check character limits for each field
- Invalid date format: Use ISO format YYYY-MM-DD for birthday
- Invalid phone format: Use international phone number format
Best Practices
Data Quality
- Validate input data before sending to API
- Use consistent formatting for names and contact information
- Normalize email addresses to lowercase
- Standardize phone number formats for consistency
Performance
- Batch contact creation when possible (multiple contacts per request)
- Implement retry logic for transient failures
- Cache customer information to reduce lookup calls
- Monitor rate limits and implement backoff
Security
- Validate all input data to prevent injection
- Log creation activities for audit trails
- Implement proper error handling without exposing sensitive data
- Use HTTPS for all API communications
Organization
- Use consistent naming conventions for contact data
- Implement role-based contact organization for teams
- Set up proper address hierarchies for multi-location customers
- Maintain data relationships between contacts and customers
This comprehensive guide enables you to efficiently create and onboard contacts using the Nue Lifecycle Management API, supporting everything from simple contact creation to complex team onboarding workflows.