CRM

realtebo
Participant

How to retrieve, using api, all contacts of a company?

SOLVE

I am doing this

const companyId = context.propertiesToSend.hs_object_id;

const properties = undefined;

const propertiesWithHistory = undefined;

const associations = [

"contacts"

];

const archived = false;

const idProperty = undefined;

apiResponse = await hubspotClient.crm.companies.basicApi.getById(companyId, properties, propertiesWithHistory, associations, archived, idProperty);
 
In the returned object I have an object associations, with an array of contacts, something like
 
"associations": {
"contacts": {
"results": [
{
"id": "144659380512",
"type": "company_to_contact"
},
{
"id": "144629380512",
"type": "company_to_contact"
},


....


How can I retriev all contact now? (I need only hubspot id an the first and last name for now

0 Upvotes
1 Accepted solution
realtebo
Solution
Participant

How to retrieve, using api, all contacts of a company?

SOLVE

I found this working solution. I am using js sdk 

TDLR;

I am calling hubspotClient.crm.contacts.batchApi.read method passing an array of objects, where each object has a single "id" field which is the contact id

LONG VERSION:

const hubspot = require("@hubspot/api-client");

 

...


const hubspotClient = new hubspot.Client({
accessToken: context.secrets.PRIVATE_APP_ACCESS_TOKEN,
});

// Leggo la company e gli id dei vari suoi contatti

const companyId = context.propertiesToSend.hs_object_id;
const properties = undefined;
const propertiesWithHistory = undefined;
const associations = ["contacts", "meetings"]; // si noti che leggo sia i contatti che i meeting
const archived = false;
const idProperty = undefined;

let companyApiResponse = {};
try {
companyApiResponse = await hubspotClient.crm.companies.basicApi.getById(
companyId,
properties,
propertiesWithHistory,
associations,
archived,
idProperty
);
} catch (e) {
return {
context: context,
data: e,
debug: "error retrieving company",
};
}

if (typeof companyApiResponse.associations.contacts.results === "undefined") {
return {
context: context,
data: [],
debug: "non contactIds found",
};
}

// Ora recupero la lista degli id dei contatti dell'azienda e quindi ne chiedo i dettagli via api
const contactIds = companyApiResponse.associations.contacts.results.map(
(item) => {
return { id: item.id };
}
);
let contactsApiResponse = {};
try {
contactsApiResponse = await hubspotClient.crm.contacts.batchApi.read({
inputs: contactIds,
});
} catch (e) {
return {
inputs: contactIds,
// context: context,
data: e,
debug: "error retrieving contacts",
};
}

if (typeof contactsApiResponse.results === "undefined") {
return {
// context: context,
data: [],
debug: "unable to retrieve contacts",
};
}

const contacts = contactsApiResponse.results.map((contact) => {
return {
label: `${contact.properties.firstname} ${contact.properties.lastname} (${contact.properties.email})`,
value: contact.id,
};
});


 

 

View solution in original post

0 Upvotes
2 Replies 2
realtebo
Solution
Participant

How to retrieve, using api, all contacts of a company?

SOLVE

I found this working solution. I am using js sdk 

TDLR;

I am calling hubspotClient.crm.contacts.batchApi.read method passing an array of objects, where each object has a single "id" field which is the contact id

LONG VERSION:

const hubspot = require("@hubspot/api-client");

 

...


const hubspotClient = new hubspot.Client({
accessToken: context.secrets.PRIVATE_APP_ACCESS_TOKEN,
});

// Leggo la company e gli id dei vari suoi contatti

const companyId = context.propertiesToSend.hs_object_id;
const properties = undefined;
const propertiesWithHistory = undefined;
const associations = ["contacts", "meetings"]; // si noti che leggo sia i contatti che i meeting
const archived = false;
const idProperty = undefined;

let companyApiResponse = {};
try {
companyApiResponse = await hubspotClient.crm.companies.basicApi.getById(
companyId,
properties,
propertiesWithHistory,
associations,
archived,
idProperty
);
} catch (e) {
return {
context: context,
data: e,
debug: "error retrieving company",
};
}

if (typeof companyApiResponse.associations.contacts.results === "undefined") {
return {
context: context,
data: [],
debug: "non contactIds found",
};
}

// Ora recupero la lista degli id dei contatti dell'azienda e quindi ne chiedo i dettagli via api
const contactIds = companyApiResponse.associations.contacts.results.map(
(item) => {
return { id: item.id };
}
);
let contactsApiResponse = {};
try {
contactsApiResponse = await hubspotClient.crm.contacts.batchApi.read({
inputs: contactIds,
});
} catch (e) {
return {
inputs: contactIds,
// context: context,
data: e,
debug: "error retrieving contacts",
};
}

if (typeof contactsApiResponse.results === "undefined") {
return {
// context: context,
data: [],
debug: "unable to retrieve contacts",
};
}

const contacts = contactsApiResponse.results.map((contact) => {
return {
label: `${contact.properties.firstname} ${contact.properties.lastname} (${contact.properties.email})`,
value: contact.id,
};
});


 

 
0 Upvotes
briannester
Participant | Diamond Partner
Participant | Diamond Partner

How to retrieve, using api, all contacts of a company?

SOLVE

Hi Mirko,

 

You would want to make an additonal API call using the IDs in the results Object. I would recommed running the follwing ( don't forget to install axios):

 

const axios = require('axios');

// Replace with your actual access token
const accessToken = 'YOUR_API_KEY';
const companyId = 'COMPANY_ID';

// Define the endpoint to get associated contacts
const endpointUrl = `https://api.hubapi.com/crm/v3/objects/companies/${companyId}/associations/contacts`;

// Define the endpoint for getting contact details
const contactDetailsUrl = (contactId) => `https://api.hubapi.com/crm/v3/objects/contacts/${contactId}`;

// Function to get associated contacts
const getAssociatedContacts = async () => {
  try {
    const response = await axios.get(endpointUrl, {
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': 'application/json'
      }
    });

    const contacts = response.data.results;
    const contactDetails = [];

    for (const contact of contacts) {
      const contactId = contact.id;
      try {
        const contactResponse = await axios.get(contactDetailsUrl(contactId), {
          headers: {
            'Authorization': `Bearer ${accessToken}`,
            'Content-Type': 'application/json'
          }
        });

        const properties = contactResponse.data.properties;
        const firstName = properties.firstname || 'N/A';
        const lastName = properties.lastname || 'N/A';
        const email = properties.email || 'N/A';

        contactDetails.push({
          id: contactId,
          first_name: firstName,
          last_name: lastName,
          email: email
        });
      } catch (contactError) {
        console.error(`Failed to retrieve details for contact ID ${contactId}:`, contactError.response.status, contactError.response.statusText);
      }
    }

    console.log('Contact Details:', contactDetails);
  } catch (error) {
    console.error('Failed to retrieve contacts:', error.response.status, error.response.statusText);
  }
};

// Execute the function
getAssociatedContacts();
 


Brian Nester

Senior Client Delivery Specialist

@ Measured Results Marketing

bnester@measuredresults.com
https://www.measuredresultsmarketing.com/
0 Upvotes