This tutorial is a guest post by Michel Zurkirchen, digital analyst @ NRC media.

Chances are that you and your team have felt frustrated at some point because you’re struggling with data in your sales process and losing sales as a result. You know your data’s there, but you can’t utilize it because you’ve used HubSpot as your CRM of choice and one (or several data points) are stored in another system.

While not ideal, there are some steps you can take to leverage HubSpot’s flexibility to integrate data from your other systems into it, even if the data doesn’t fit HubSpot’s default properties. For example, this workflow can enable you to create a custom property to store trial end dates for your contacts, enabling you to reach out to them with an offer at just the right time.

In this article, we’ll take a look at how you can create a custom contact property and write data to it using the HubSpot API and Python by breaking down:

  • Getting set up with HubSpot API
  • Checking for existing HubSpot contact properties
  • Creating a HubSpot contact custom property
  • Updating a HubSpot contact’s property
  • Some general advice around the HubSpot API

Let’s get started.

Get set up with the HubSpot API and Python

We'll use Python to connect to the HubSpot API and make your data available where you need it most.

To connect to the API, you'll need your API key. Only Super Admins have access to the API key, but anyone with the key can use the API. There’s only one key for the entire HubSpot account, which you can find by logging into your account and selecting your company. Next, click the cogwheel next to your profile picture to go to settings. From there, click Integrations in the left-hand menu and finally API key. Here you can generate a key if one doesn't exist yet, or see the current key.

Next up: library installation. To work with the HubSpot API with Python, we'll need two libraries:

  1. The requests library to connect to the HubSpot API
  2. The json library to parse the responses from the API.

If you haven't installed the requests library yet, you can do so by running the below command in your terminal.

pip install requests
pip3 install requests # Use this if the first command doesn't work for you.

There are several ways to proceed. You can use a Jupyter Notebook for easy feedback, you can create a .py file and run that, and so on. We'll let you pick your favorite tool. Once you've made your choice, start by importing the requests and json libraries.

import requests
import json

From there, we'll make several requests to the HubSpot API. The variables have been prepended with the steps that we'll take to make it easier to distinguish between them. These steps are check_, create_, find_ and update_.

Check for existing HubSpot contact properties

Before we get started, we need to check to make sure the property we want to write data to doesn’t already exist.

While HubSpot will prevent you from accidentally overwriting an already existing property, it can lead to confusion within your organization if you have two (near) identical properties. You can complete this step with the API or in the HubSpot web interface.

If you wish to do this in the web interface, log in to your account, select your company, and then complete these steps.

  1. Click on Contacts in the navigation menu.
  2. Click on Contacts in the dropdown menu.
  3. Click on the Actions button on the right.
  4. Click Edit properties.
  5. Search for your property in the search box.

Here’s a video walkthrough if that’s more your jam:

If you prefer to use the API, you can use the below code to retrieve all your contact properties.

check_parameters = {
    'hapikey': 'your-api-key'
}

check_response = requests.get('https://api.hubapi.com/crm/v3/properties/contacts', params=check_parameters)

check_content = json.loads(check_response.content)['results']

While tedious, it's best to manually look through the properties, to make certain that you don't overlook anything, for example, when a property has a name that you didn't expect.

# Storing the name of every field in a list first, so that we can print them in alphabetical order. 

check_fields = []

for i in check_content:
    check_fields.append(i['name'])
    
for i in sorted(check_fields):
    print(i)

At this point, you should know whether the custom property that you want to write data to already exists. If it doesn’t, we’ll show you how to create one in the next section. If you’re lucky and it does already exist, go ahead and skip ahead to our section on updating a HubSpot contact’s property.

Create a HubSpot contact custom property

Didn't find the property that you were looking for? It's time to create one. If you used the web interface to search for the property in the previous step, you can click the Create property button on the same screen.

Again, if you prefer the API, the HubSpot API reference contains a full list of accepted data types for your property. Because our trial end date property will contain a date, the type and fieldType of our property will be date.

create_parameters = {
    'hapikey': 'your-api-key'
}

# You can manually format the dictionary as a string without using json.dumps. For readability's sake, we'll use json.dumps.

# Be aware that the HubSpot API will require you to use double quotes if you manually format the dictionary as a string.

create_payload = json.dumps({
    'name': "trial_end_date",
    'label': "Trial end date",
    'description': "The end date of a contact's trial",
    'type': "date",
    'fieldType': "date",
    'groupName': "contactinformation",
})
    
create_headers = {
    'accept': "application/json",
    'content-type': "application/json"
    }

create_response = requests.post('https://api.hubapi.com/crm/v3/properties/contacts', params=create_parameters, headers=create_headers, data=create_payload)

If everything went according to plan, the response will be the property that you just created, which will now be available for all your contacts. By default, it has no value until updated. If something went wrong along the way, have a close look at the API response, which should provide you with helpful feedback. Alternatively, try to create a custom property through the web interface, which will guide you through the process.

create_content = json.loads(create_response.content)
print(create_content)

You should now have a custom contact property in place, created using either the web interface or the API. If that’s the case, you’re ready for the final step: write custom data to a custom contact property.

Update a HubSpot contact's property

You're now all set to do what you came here to do: write custom data to a custom contact property. You write data to a contact by identifying them by their id. Of course, you're unlikely to just know the id of your contact within HubSpot (unless you have superhuman memory). We can search for the contact using an identifier that we do know, such as their email address. If we, for example, know that this particular contact's email address is emailmaria@hubspot.com, we can find her using the search endpoint.

find_parameters = {
    'hapikey': 'your-api-key'
}

find_payload = json.dumps(
    {'filterGroups': [{'filters': [{'value': 'emailmaria@hubspot.com', 'propertyName': 'email', 'operator': 'EQ'}]
                      }]
}
)

find_headers = {
    'accept': "application/json",
    'content-type': "application/json"
    }

find_response = requests.post('https://api.hubapi.com/crm/v3/objects/contacts/search', params=find_parameters, headers=find_headers, data=find_payload)

Our search yielded only one contact, but depending on your search settings and your contact data, you could get a response that includes multiple contacts, which may happen if multiple contacts within one company share a generic email address.

find_content = json.loads(find_response.content)['results']
print(find_content)

The id for our contact is the value of the id key, which in our case is 1. We'll place that at the end of the URL of our next request. We'll update our contact's data to reflect that her trial ends on 2021-07-01.

update_parameters = {
    'hapikey': 'your-api-key'
}

update_payload = json.dumps(
    {'properties': { 
    'trial_end_date': '2021-07-01'
}
                     })
    
update_headers = {
    'accept': "application/json",
    'content-type': "application/json"
    }

# 1 at the end of the url is the id of our contact
update_response = requests.patch('https://api.hubapi.com/crm/v3/objects/contacts/1', params=update_parameters, headers=update_headers, data=update_payload)

The response should be the contact you just wrote data to. If not, the response will indicate an error and point you in the direction of the issue you need to fix.

update_content = json.loads(update_response.content)
print(update_content)

If you made it this far, you’re now able to create any custom property and write custom data to it. You’re (almost) ready to use all this shiny new knowledge out in the wild.

Some final advice on the HubSpot API

Congrats! You just successfully wrote your data from one system to a custom property of your contact in HubSpot via the API. Easy enough, right? Before you run off to develop a full-blown, production-worthy solution, there are a few things you should take into consideration.

First off, there are per second and daily API rate limits. You should make sure you can go this route without having to worry about your limit - now and in the foreseeable future. Regardless of whether or not you think you’ll ever hit this limit, you'll need to implement error handling in case something goes wrong and your data doesn’t get written to HubSpot. This includes logging errors so you can find out why your process failed. And of course, any process that fails to write data to HubSpot, you'll want to run again.

You could reinvent the proverbial digital wheel, but the easier solution is to let Census handle everything for you. We can take all the engineering for custom connectors off your plate and make it easy to sync your customer data from your warehouse to your business tools. See if we integrate with your tools (like we do with HubSpot) or check out a demo.