Skip to content

Marina Mele's site

Reflections on family, values, and personal growth

Menu
  • Home
  • About
Menu

How to use the HubSpot API with Python

Posted on February 2, 2014September 26, 2014 by Marina Mele

In this post I will explain how to use the HubSpot API using Pyhton.

I will focus in two diferent API requests: the total number of contacts in your database and the number of contacts that belong to one of your HubSpot lists.

Introduction

You must have an active HubSpot account in order to follow this post, as the main idea is to obtain information of your Portal – like contact’s information, lists of contacts, number of visits, etc – but using Python.

We will use two packages: urllib2 and json. Probably, you have both already installed, as they usually come by default with Python. You can check this by opening Python from your terminal and importing both packages:

$ python

>>> import urllib2, json

If no error is displayed, then you have both packages installed 🙂

In order to have access to the HubSpot API, we need a Key that identify us. You can obtain your HubSpot API Key here. It will ask you to introduce an email and the Hub ID, which you can find at the botom-right of your HubSpot Dashboard page. If you manage multiple accounts, you should select the Dashboard of the account of interest.

Once you receive the Key in your email, create a file named hsapi.py and open it with your favorite text editor:

In linux I prefer emacs:

$ emacs hsapi.py &

In Mac, I normally use Xcode:

$ touch hsapi.py

$ open -a Xcode hsapi.py

Once you opened the file, import the two packages urllib2 and json, and replace the APIKEY_VALUE variable with your API Key.

import urllib2, json

APIKEY_VALUE = “example-api-key-value-0000”

APIKEY = “?hapikey=” + APIKEY_VALUE

HS_API_URL = “http://api.hubapi.com”

The last two lines will help us build the correct url to make the requests.

Total number of contacts

Let us obtain from HubSpot the number of contacts in our database. If you look at the HubSpot Developers documentation endpoints, you will see a list of all the available endpoints. The one that interests us now is:

GET /contacts/v1/contacts/statistics

which for a given portal, returns statistics about the portal’s contacts, including the total number of contacts.

This means that we can access to this information through the url:

http://api.hubapi.com/contacts/v1/contacts/statistics?hapikey=”example-api-key-value-0000″

which is a string that contains the HS_API_URL, the endpoint of interest and the APIKEY.

When you access this url, you will get a response containing the requested information as a json file.

Let us see how this transforms into Python code: We define a function, getTotalNumberOfContacts, that builds the correct url, requests the information to the HubSpot API, and returns the total number of contacts. After defining the function, we print its results at the end:

def getTotalNumberOfContacts():

    # First, we build the correct url

    xulr = “/contacts/v1/contacts/statistics”

    url = HS_API_URL + xurl + APIKEY

    # Now we use urllib2 to open the url and read it

    response = urllib2.urlopen(url).read()

    # Transform the response, a JSON object, into a Python dictionary object

    statistics = json.loads(response)

    # Finally, return the number of contacts

    return statistics[“contacts”]

print getTotalNumberOfContacts()

Save the file and run it from your terminal:

$ python hsapi.py

You should see the amount of contacts on the screen.

How to use the HubSpot API with Python #hubspot #inboundmarketing http://t.co/p1XztZpSrF

— Marina Mele (@Marina_Mele) March 12, 2014

Number of contacts in a given list

Another information that we can request to the HubSpot API is the number of contacts that belong to a given HubSpot list.

Go to your HubSpot account and into Contacts –> Lists. Find the list from which you want to request the number of contacts and select it. Look at your browser, at the url of the list’s information page. You should see something like:

https://app.hubspot.com/contacts/000000/lists/000/

where the first number, here 000000, corresponds to your Hub ID and the second one, here 000, corresponds to the list ID (a unique identifyer of your list).

Go back to the hsapi.py file and write the following code, replacing your list ID in the variable LIST_ID:

LIST_ID = 000
def getNumberOfContactsInList(list_id):
    xulr = “/contacts/v1/lists/” + str(list_id)
    url = HS_API_URL + xurl + APIKEY
    response = urllib2.urlopen(url).read()
    list_info = json.loads(response)
    return list_info[“metaData”][“size”]

print getNumberOfContactsInList(LIST_ID)

We have defined a function that builds the correct url and requests the information to the HubSpot API. Then, it returns the total number of contacts that belong to that list.
Save the file and run it from your terminal:
$ python hsapi.py
You should see first the amount of contacts on the screen and then, the number of contacts in that list.
The full code used in this post is:


File: marinamele_hsapi.py
------------------------

import urllib2, json

# Change the APIKEY_VALUE by your API key
APIKEY_VALUE = "example-api-key-value-0000"

APIKEY = "?hapikey=" + APIKEY_VALUE
HS_API_URL = "http://api.hubapi.com"

def getTotalNumberOfContacts():
    # First, we build the correct url
    xulr = "/contacts/v1/contacts/statistics"
    url = HS_API_URL + xurl + APIKEY
    # Now we use urllib2 to open the url and read it
    response = urllib2.urlopen(url).read()
    # Transform the response, a JSON object, into a Python dictionary object
    statistics = json.loads(response)
    # Finally, return the number of contacts
    return statistics["contacts"]

print getTotalNumberOfContacts()

# Change the LIST_ID by the ID of your list
LIST_ID = 000

def getNumberOfContactsInList(list_id):
    xulr = "/contacts/v1/lists/" + str(list_id)
    url = HS_API_URL + xurl + APIKEY
    response = urllib2.urlopen(url).read()
    list_info = json.loads(response)
    return list_info["metaData"]["size"]

print getNumberOfContactsInList(LIST_ID)

However, I would like that you could also access to visits information using the API. If you would be also interested in this functionality, please vote this Idea!!

I hope this post was usefull, and you liked it 🙂

Please, give it a +1!!
Marina Melé
Marina Mele

Marina Mele has experience in artificial intelligence implementation and has led tech teams for over a decade. On her personal blog (marinamele.com), she writes about personal growth, family values, AI, and other topics she’s passionate about. Marina also publishes a weekly AI newsletter featuring the latest advancements and innovations in the field (marinamele.substack.com)

Leave a Reply Cancel reply

You must be logged in to post a comment.

Categories

  • Personal Growth and Development
  • Artificial Intelligence
  • Mindful Parenting and Family Life
  • Productivity and Time Management
  • Mindfulness and Wellness
  • Values and Life Lessons
  • Posts en català
  • Other things to learn

Recent Posts

  • BlueSky Social – A Sneak Peek at the Future of Social Media
  • The Incredible Journey of AI Image Generation
  • AI and Fundamental Rights: How the AI Act Aims to Protect Individuals
  • Overcoming Regrets: Finding the Strength to Move Forward
  • Thinking Outside the Box: Creative Problem-Solving with Critical Thinking

RSS

  • Entries RSS
Follow @marina_mele
  • Cookie Policy
  • Privacy Policy
©2023 Marina Mele's site | Built using WordPress and Responsive Blogily theme by Superb
This website uses cookies to improve your experience. If you keep navigating through this website, we'll assume you're ok with this, but you can opt-out if you wish.Accept Read More
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT