Back to listing

Associate two objects

Category:
Custom-Coded Workflow Action, Operations Pro/Ent

ETL:
Load

Notes

Associations unlock many of HubSpot's most advanced capabilities. This code snippet allows you to create an association between two records. 

Note that this code snippet could be more efficient because it’s using the batch association endpoint to associate a single pair of records.

With that said, I tend to prefer this method because I can easily expand the function to include multiple associations but adding objects to the `inputs` array. 

Code

        

Language: JavaScript



 
const axios = require('axios');
const accessToken = `Bearer ${process.env.secretName}`;
 
exports.main = async (event, callback) => {
  const sourceRecordTicketId = event.inputFields['sourceRecordTicketId'];
  const targetRecordId = event.inputFields['targetRecordId'];
const associationCategory = "HUBSPOT_DEFINED";
const associationType = 15;
const url = 'https://api.hubapi.com/crm/v4/associations/contact/ticket/batch/create';
 
const headers = {
  'authorization': accessToken,
  'content-type': 'application/json'
};
 
const data = {
  "inputs": [
    {
      "from": {
        "id": sourceRecordId
      },
      "to": {
        "id": targetRecordId
      },
      "types": [
        {
          "associationCategory": associationCategory,
          "associationTypeId": associationType
        }
      ]
    }
  ]
};
 
axios.post(url, data, { headers })
  .then(response => {
    console.log(`Record ${sourceRecordId} and record ${targetRecordId} associated successfully.`);
  })
  .catch(error => {
    console.error('Error:', error.message);
    throw new Error('An error occurred while associating the records.');
  });
}

How can SpotDev support your business?

HubSpot Migrations

Move from Salesforce, Dynamics, Pipedrive or any CRM to HubSpot with SpotDev.

Learn more

HubSpot Integrations

Add advanced functionality to your HubSpot portal with API development services.

Learn more

RevOps

Align your sales, marketing and service teams to break down silos and trigger growth.

Learn more