Back to listing

Create a record if it doesn't already exist

Category:
CMS Enterprise

ETL:
Extract, Load

Notes

As a HubSpot developer, you'll frequently want to create new records in the CRM. 

But you'll only want to do that if the record you need to create doesn't already exist. 

This serverless function is the bare bones approach to solving for this. It searches the CRM for a property that you know if unique for that record type (email addresses for contacts, for example). If a record matches that, then it sends data back to the front end with that record's ID. 

If no record matches the search, then it create a new record based on the data that was used to conduct the search. 

This is a very routine process for a HubSpot developer, so make this a bread and butter part of your code collection. You can easily adjust the behaviour for if a record doesn't exist. For example, you could combine it with the 'Update Record' code snippet so that you update the record with additional information from the front end (perhaps updating the phone number or company name). 

Code

        

Language: JavaScript



 

const axios = require('axios');

const accessToken = `Bearer 1234`; // Make sure you're populating this variable with secrets

exports.main = (context, sendResponse) => {

 let objectType = "contacts";

  axios.post(`https://api.hubapi.com/crm/v3/objects/${objectType}/search`, {

    "filterGroups": [

      {

        "filters": [

          {

 

// Change the propertyName value to match the unique properties of the objectType that you're searching.

            "propertyName": "email",

            "operator": "EQ",

            "value": `${context.params.email}`

          }

        ]

      }

    ],

    "limit": 1

  }, {

    headers: {

      'authorization': accessToken,

      'content-type': 'application/json'

    }

  })

    .then(response => {

        if (response.data.total > 0) {

 

    // This is an ideal place to add additional handling. You may want to use the Update Record code snippet here. Or you might want to include handling for scenarios where more than one record is returned (which means you're not using a unique propertyName)

           sendResponse({ body: response.data.results[0].id, statusCode: 200 });

        } else {

          axios.post(`https://api.hubapi.com/crm/v3/objects/${objectType}`, {

            "properties": {

 

// Change these properties to match the objectType that you're updating

              "firstname": `${context.params.firstname}`,

              "lastname": `${context.params.lastname}`,

              "email": `${context.params.email}`,

              "phone": `${context.params.phone}`,

              "company": `${context.params.company}`

            }

          }, {

            headers: {

              'authorization': accessToken,

              'content-type': 'application/json'

            }

          })

            .then(response => {

              sendResponse({ body: response.data.id, statusCode: 200 });

          })

            .catch(error => {

// Ideally, you would include more sophisticated error handling here

            sendResponse({ body: error, statusCode: 400 });

            console.error(error);

          });

        }

  })

    .catch(error => {

// Ideally, you would include more sophisticated error handling here

    sendResponse({ body: error, statusCode: 400 });

    console.error(error);

  });

};

 

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