HubSpot’s Python Library: Breaking Ground

Share

Share on facebook
Share on twitter
Share on linkedin

As a platform, HubSpot has a massive amount of UI-based functionality. But as any developer will tell you, no platform is truly complete without some kind of API. This allows users to have an even greater amount of control over their instances, and is essential to any top tier platform.

HubSpot’s REST API has gone through a few versions and is currently in a rock-solid iteration that is among the best that I have worked with. It gives you backend access to all of HubSpot’s default objects, in addition to custom objects, and is flexible enough to allow for myriad applications.

The API is currently in the midst of a change that is sunsetting API keys for accounts, and instead giving access to individual applications in order to bring greater flexibility in coding API-based projects, and give added security and accountability to the same.

Most platforms would consider this to be enough to make developers and clients happy, and rightfully so— but HubSpot has gone a step further. 

HubSpot has been building their own Python library for some time now, and we’ve been keeping an eye on it. It has now reached the stage where they’ve put it front and center in their API documentation, so we thought this would be the perfect time to dive into it and bring back some code examples and impressions.

This blog post will specifically evaluate the CRM base object capabilities in the library, although we plan to expand on this in future posts!

Contacts

We’ll kick things off with the Contact object in HubSpot. Unsurprisingly, this is a key aspect of any CRM, and carries a lot of importance with it. Almost all of the HubSpot development that I’ve personally done has involved contacts in one way or another. Because it’s such an important aspect of the CRM, it is often referenced when writing custom apps for HubSpot. 

There are a myriad of uses for contact-based API calls, so listing them all out is basically an impossible task. However, some very common ones include creating and updating contacts, searching through using unique field values and IDs, and archiving/deleting contacts. Moving on from this, a common one with larger projects is batch actions which allow for doing such tasks en masse.

Their library allows for these actions using basic function calls within your script, which can start with something as simple as a single contact creation with an array of field values, and expand beyond that with some basic coding. I wrote a simple example to get you started in which the library is called in a loop to create contacts using fields in a CSV.

				
					import hubspot
from pprint import pprint
import pandas as pd
from hubspot.crm.contacts import SimplePublicObjectInput, ApiException
import os

# setting up the connection to HubSpot
token = os.environ["private_key"]
client = hubspot.Client.create(access_token= token)


# reading in the csv using Pandas
df = pd.read_csv("Contact CSV.csv", header=0)

# looping through the dataframe
for index, row in df.iterrows():
   properties = {
       "company": row["Company"],
       "email": row["Email"],
       "firstname": row["First Name"],
       "lastname": row["Last Name"]
   }
   simple_public_object_input = SimplePublicObjectInput(properties=properties)

# attempting to create the contact, printing the error exception if unsuccessful
   try:
       api_response = client.crm.contacts.basic_api.create(simple_public_object_input=simple_public_object_input)
       pprint(api_response)
   except ApiException as e:
       print(f"Exception when calling basic_api->create: {e}\n")
				
			

As you can see above we’re using Pandas to load a CSV with mapped HubSpot fields into a dataframe. We are then looping through that dataframe and creating a contact with each row’s information.

Deals

The Deals object in HubSpot also sees a fair amount of traffic. Thanks to their built-in associations with the Company and Contact objects and native availability, they can be used in a number of ways outside of their original intended purpose of, well, tracking deals.

I’ve seen them used to take the place of a ticketing system, track donations, and even, through a specifically automated naming convention and duplicating workflow, be used to simulate a parent-child relationship that doesn’t currently exist for deals in HubSpot.

Due to this versatility, the Deals object can often show up in API calls in custom scripts. Luckily, the library has that pretty well covered. As an example, I wrote a simple script that searches for deals in the HubSpot instance, using a CSV of IDs, and returning a series of fields on the deal.

				
					import hubspot
from pprint import pprint
import pandas as pd
from hubspot.crm.deals import PublicObjectSearchRequest, ApiException
import os


# setting up the connection to HubSpot
token = os.environ["private_key"]
client = hubspot.Client.create(access_token= token)


# reading in the csv using Pandas
df = pd.read_csv("Deal CSV.csv", header=0)

# looping through the dataframe
for index, row in df.iterrows():

# attempting to get the deal, printing the error exception if unsuccessful
   try:
       api_response = client.crm.deals.basic_api.get_by_id(deal_id=row["ID"], properties=["amount", "dealname", "dealstage", "pipeline", "createdate", "closedate"], archived=False)
       pprint(api_response)
   except ApiException as e:
       print(f"Exception when calling basic_api->get_by_id: {e}\n")
				
			

Here we’re again using Pandas to load a CSV containing HubSpot deal IDs into a dataframe. We are then looping through that dataframe and searching for the matching deal, and displaying the desired properties.

Companies

The final member of the main three objects is Companies. Much like Deals and Contacts before it, Companies is an extremely commonly used object in HubSpot. It allows for a number of different associations, up to and including the coveted Parent-Child relationship. The most common of these is of course contacts who work at the company, and that was the focus of the code snippet I wrote for this demo.

Getting a list of associated items is a fairly common ask in the work that I do as a HubSpot developer, so I thought a good demo would be a small script loops through a CSV of companies, and then pulls the first ten contacts associated with each company. 

				
					import hubspot
from pprint import pprint
import pandas as pd
from hubspot.crm.companies import ApiException
import os


# setting up the connection to HubSpot
token = os.environ["private_key"]
client = hubspot.Client.create(access_token= token)


# reading in the csv using Pandas
df = pd.read_csv("Company CSV.csv", header=0)

# looping through the dataframe
for index, row in df.iterrows():

# attempting to get the associations, printing the error exception if unsuccessful
   try:
       api_response = client.crm.companies.associations_api.get_all(company_id=row["ID"], to_object_type="contact", limit=10)
       pprint(api_response)
   except ApiException as e:
       print(f"Exception when calling associations_api->get_all: {e}\n")
				
			

As before, we’re using Pandas to load a CSV containing a series of company IDs into a dataframe. We then loop through said dataframe, and pull the first ten contacts associated with the company.

Pointed Pros vs. Cons

Having now done some work with this library, I figured a more pointed Pros vs. Cons list would be a good idea to give a bit of a TLDR for those who want one.

Pros:

  • Standard Pip install
    • There isn’t any additional headache when setting up this library in your IDE. You just throw in the pip command, and away you go.
  • Easy to pick up and use
    • It’s a simple matter of calling the library in your code, and then going to town. They have a large amount of code examples in their API documentation, and a fully supported Github repository for further delving if you’re interested.
  • API Exception is a handy tool
    • The library has something of a built in logging/debugging tool in the form of the API Exception call that’s sitting on the end of each of the above scripts.

Cons:

  • Requires installation of the library
    • If you’re concerned about taking up unnecessary space on a server hosting your code, then installing an extra library could be a concern.
  • Requires Python 3.5+
    • If you prefer to use older builds of Python, then using this library isn’t going to be an option.
  • Less flexibility than straight up Requests
    • Using this library allows for less overall usability and flexibility than using the classic Requests
  • Engagements are no-go
    • If you want to get engagements on a record, i.e. calls on a contact record, you’ll still need to use Requests and their legacy API.

Closing Thoughts

Whew! Well, that was a bit of a journey, but I think we landed in a pretty good place.

I’ll say that my impressions of the HubSpot library so far have been almost entirely positive. There are a good number of important pros to using it, and a limited number of cons. I think there’s still a good bit more to unpack here, but I’m excited at the prospect of continuing to dig into the depths of HubSpot’s library on your behalf.

Keep a look out for the next post where we’ll take a look at custom objects, batch jobs, and more. Don’t worry though, on the advice of Gandalf I’ll be sure to delve neither too deep, nor too greedily.

Interested in joining the obo team?

Related Posts

Get the Latest.

Sign up for monthly blog notifications to learn more about the latest sales and marketing trends.

Ready to drive results?

We want to help your business be what you envision it to be.
Schedule your free consultation here now.

OutboundOps, LLC (dba obo.)

STANDARD TERMS AND CONDITIONS

These Standard Terms and Conditions (the “Terms”) set forth the terms and conditions that govern purchases by any purchaser (the “Client”) of outbound demand generation services and other related services (the “Services”) from OutboundOps, LLC dba obo. Agency (“obo. Agency”). The Terms and any purchase orders, scopes of work and other agreements regarding the Services shall be referred to as the “Agreement.”

1. OFFER FOR SALE.

All agreements between the Client and obo. Agency to purchase the Services shall be governed by the terms and conditions herein. The Client and obo. Agency agree that any modifications, changes, alterations of the terms and conditions herein, with respect to any specific proposal, must be in writing and signed by the Client and obo. Agency. obo. Agency hereby objects to any additional or different terms which may be contained in any of the Client’s purchase orders, acknowledgements or other documents or any communications received from the Client, and the Client and obo. Agency hereby agree that any such attempts shall be null and void and not deemed a part of the terms and conditions hereunder or any resulting order. 

Any offer hereunder shall expire thirty (30) days following its date, unless the Client executes and returns to obo. Agency that proposal for the applicable Services within such thirty (30) day period. No order may be cancelled, modified or altered by the Client, without written consent of obo. Agency, which may be withheld in its sole discretion.

2. FEES AND PAYMENT.

The fees for the Services are set forth in the applicable proposal provided by obo. Agency and otherwise are based on obo. Agency’s current fees, in effect at the time of order, for the Services. The Client acknowledges and agrees that, if it purchases Services with a minimum period for the Services, such amounts shall be due and payable if this Agreement is terminated sooner.

obo. Agency shall provide the Client with invoices, no more frequently than monthly, for the fees due from the Client under the Agreement. All payments for the Services are payable only in United States Dollars. The Client shall make payment for any and all monthly fees on or before the first day of the applicable month for Services. Unless obo. Agency requires payment in advance or upon different terms, for any other services, the Client shall make payment for all fees within thirty (30) days following the date of invoice.

Subject to the limitations above, payments may be made only in cash or by check or wire transfer or by certain credit cards provided that Client provides credit card authorization satisfactory to obo. Agency.

Charges will be assessed on past due accounts as follows: (i) a late charge at a rate equal to the lesser of one and one-half percent (1.5%) per month or the highest rate permitted by applicable law, and (ii) reasonable collection costs and expenses, including attorneys’ fees and court costs.

The Client’s failure to pay in accordance with the provisions of this Section 2 shall entitle obo.

Agency, without prejudice to its rights to damages, to suspend or cancel any outstanding orders or Services or require further assurance of payment from the Client.

3. TERM AND TERMINATION.

The term of this Agreement shall commence on the effective date as set forth in the applicable proposal, and if not specified, on the date that the proposal is signed (the “Effective Date”) and shall continue in effect, until terminated, in accordance with the terms and conditions set forth in this Agreement, until the date that is the time period specified in the applicable proposal following the Effective Date (and if not specified for six (6) months following the Effective Date, and shall automatically renew for additional terms of equal period unless either party provides thirty (30) days’ written notice to the other party at any time and for any reason whatsoever of its intention to terminate the agreement for convenience (the “Term”).

Either party may terminate this Agreement for a material breach of any provision of this Agreement by the other party upon fourteen (14) days’ prior written notice to the other party, such notice to set forth in detail such breach, and the breaching party’s failure to cure such breach. Either party may terminate this Agreement immediately without breach or penalty by written notice to the other party in the event the other party: (i) institutes or has instituted against it proceedings for bankruptcy (which, in the case of proceedings against it, shall remain for ninety (90) days undismissed), (ii) shall consent to the appointment of a receiver for all or substantially all of its property, (iii) shall make a general assignment for the benefit of its creditors, or shall admit in writing its inability to pay its debts as they become due; or (iv) shall be adjudged a bankrupt or insolvent by a court of competent jurisdiction.

At obo. Agency’s sole discretion, the Services may be immediately terminated or suspended if the Client violates any part of this Agreement. Upon termination of obo. Agency’s engagement hereunder, the Client shall pay to obo. Agency the fees payable to obo. Agency for the Services rendered through the date of termination in accordance with Section 2 hereof.

4. WARRANTY.

obo. Agency warrants to the Client that the Services shall meet the requirements of the applicable proposal and industry standards for a period of sixty (60) days from the date of delivery of the Services to the Client. For purposes of clarity, this limited warranty shall not be applicable to: (a) technical and other issues related to the Client’s website, hardware, software or data that are not related to the Services, including without limitation, development, creation and enhancement of the Client’s website, (b) technical and other issues resulting from any third party’s services or involvement regarding the Client’s website or (c) technical or other issues related to Client’s compliance with data security and other privacy laws that are not within the scope of the obo. Agency Services hereunder.

obo. Agency’s sole responsibility shall be, at its option, during the warranty period either: (i) to repair any warranty issues related to the Services or (ii) to refund to the Client the amounts paid during the warranty period, less a reasonable allowance for use, for such Services with warranty issues.

THIS WARRANTY IS THE SOLE AND EXCLUSIVE WARRANTY GIVEN BY OBO. AGENCY WITH RESPECT TO THE SERVICES PROVIDED BY OBO. AGENCY. EXCEPT AS EXPRESSLY SET FORTH HEREIN, TO THE MAXIMUM EXTENT PERMITTED BY LAW, OBO. AGENCY DISCLAIMS ALL WARRANTIES OF ANY KIND, EITHER EXPRESS, IMPLIED, STATUTORY OR COMMON LAW, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND TITLE. SOME JURISDICTIONS DO NOT ALLOW THE WAIVER OR EXCLUSION OF SOME WARRANTIES SO THEY MAY NOT APPLY. IF THIS EXCLUSION IS HELD TO BE UNENFORCEABLE BY A COURT OF COMPETENT JURISDICTION, THEN ALL EXPRESS, IMPLIED AND STATUTORY WARRANTIES SHALL BE LIMITED IN DURATION TO A PERIOD OF SIXTY (60) DAYS FROM THE DATE OF PROVISION OF EACH PORTION OF THE SERVICES, AND NO WARRANTIES SHALL APPLY AFTER THAT PERIOD.

5. LIMITATION OF LIABILITY.
THE CLIENT EXPRESSLY UNDERSTANDS AND AGREES THAT OBO. AGENCYSHALL NOT BE LIABLE TO THE CLIENT OR ANY THIRD PARTY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, PUNITIVE, CONSEQUENTIAL OR EXEMPLARY DAMAGES, EVEN IF OBO. AGENCY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, WHETHER SUCH LIABILITY IS BASED UPON CONTRACT, TORT, NEGLIGENCE OR OTHER LEGAL THEORY. THE CLIENT EXPRESSLY UNDERSTANDS AND AGREES THAT OBO. AGENCY’S CUMULATIVE LIABILITY TO THE CLIENT UNDER THIS AGREEMENT SHALL NOT EXCEED THE AGGREGATE AMOUNT PAID TO OBO. AGENCY UNDER THIS AGREEMENT DURING THE FOUR (4) MONTH PRIOR TO ANY CLAIM.

The Client acknowledges that all delivery dates are approximate. In no event shall obo. Agency be liable for any delays in delivery of the Services.

6. INTELLECTUAL PROPERTY.

obo. Agency agrees that the Client shall own all right, title and interest in and to any pre-existing works of Client, including without limitation, content owned by Client that is provided to obo. Agency (the “Pre-Existing Works”). In the event that any Pre-Existing Works are incorporated into or are used in conjunction with the Services under this Agreement, then during the Term, the Client hereby grants to obo. Agency a fully paid up, non-exclusive, non-transferable, non-sublicensable license to use the Pre-Existing Works solely to provide the Services hereunder.

Upon payment in full for all Services rendered under this Agreement, obo. Agency hereby transfers and assigns to the Client all right, title and interest in and to all work performed in conjunction with the Services, but not including the Licensed IP. For purposes of this Agreement, “Licensed IP” shall mean any and all photographs, artwork and other content and materials that were licensed (not purchased by obo. Agency) for the Services. During the Term, obo. Agency hereby grants to the Client a fully paid up, non-exclusive, non-transferable, non-sublicensable license to use the Licensed IP solely in connection with the Services.

The Client acknowledges that obo. Agency retains all right, title and interest in and to any and all processes, procedures, methods and know-how related to the performance of the Services and any and all related copyrights, trademarks, patents, trade secrets and other intellectual property and proprietary rights. obo. Agency’s name and logo, and all related service names, marks and slogans are the trademarks, service marks or registered trademarks of obo. Agency and may not be used or modified in any manner without the prior written consent of obo. Agency.

7. CONFIDENTIALITY.
At all times during the term of this Agreement and for two (2) years thereafter, the receiving party shall keep confidential and not disclose, directly or indirectly, and shall not use for the benefit of itself of any other third party any Confidential Information of the disclosing party, except that the receiving party may disclose Confidential Information of the disclosing party to its employees and subcontractors to the extent necessary to enable each party to exercise its rights hereunder. “Confidential Information” means any trade secrets or information whether in written, digital, oral or other form which is confidential or proprietary to the disclosing party, including, but not limited to, software, inventions, customer lists, financial information, business methods and processes, and any other materials or information related to any aspect of the business or activities of the disclosing party which are not generally known to others engaged in similar businesses or activities. Notwithstanding the foregoing, Confidential Information does not include information which: (i) was publicly known or generally known within the trade at the time of disclosure; (ii) becomes public knowledge or generally known within the trade without breach of this Agreement by either party or any of its directors, officers or employees; (iii) was information already known by the receiving party at the time of disclosure without a duty of confidentiality, or information independently developed by the receiving party’s personnel who did not have access to the information disclosed by the disclosing party; (iv) is required to be disclosed by law; or (v) is obtained by a party, its officers or employees from third parties who are under no obligation of confidentiality with respect to the information. If the receiving party is required to disclose any Confidential Information by a court order or other specific governmental action, the receiving party may comply with such disclosure requirement, unless the disclosing party, at its own expense, is successful in having the effect of such requirement stayed pending an appeal or further review thereof, or revised, rescinded or otherwise nullified. In all events, the receiving party agrees to notify the disclosing party promptly if at any time a request or demand of any kind is made to the receiving party to disclose any of the disclosing party’s Confidential Information. The disclosing party shall have the right, at its cost, to intervene in any proceeding in which the receiving party is being asked to disclose any of the disclosing party’s Confidential Information.

8. TAXES AND OTHER CHARGES.
The Client shall pay, in addition to the prices as set forth herein, any and all occupation tax, use tax, property tax, sales tax, excise tax, value-added tax, duty, custom, inspection or testing fee, or any other tax, fee or charge of any nature whatsoever, except for taxes on obo. Agency’s income, imposed by any governmental authority on or measured by the transaction between obo. Agency and the Client. The Client shall indemnify, defend and hold harmless obo. Agency against all claims, losses, damages, liabilities, costs and expenses, including reasonable attorneys’ fees, to the extent such claims arise out of any breach of this Section.

9. REPRESENTATIONS.
The Client represents and warrants to obo. Agency that: (i) he is at least 18 years old; (ii) in the event that the Client is an entity, that it has the full right, power and authority to enter into this Agreement; (iii) the performance by the Client of its obligations and duties hereunder, do not and will not violate any agreement to which the Client is a party or by which the Client is otherwise bound; and (iv) the Client’s use of the Services complies in all respects with all applicable laws, statutes, regulations, ordinances and other rules including without limitation, all Federal, state and international laws in connection with data security and privacy of personal data of any identifiable natural person. The Client further represents and warrants that the Client shall ensure that privacy notices posted on Client’s website shall inform users of their rights under all applicable laws.
.
The Client further represents and warrants to obo. Agency that the Client shall not violate, misappropriate or infringe upon any patent, copyright, trademark, trade secret and/or other intellectual property or proprietary rights of any third party.

10. INDEMNIFICATION.
The Client shall indemnify, defend and hold harmless obo.Agency and its directors, officers, employees and agents from and against any and all claims, losses, damages, liabilities, costs and expenses, including reasonable attorneys’ fees, that arise out of, result from or are related to (i) a breach by the Client of any warranty, representation or covenant set forth herein, (ii) the Client’s negligence or willful misconduct, and (iii) violation, misappropriation or infringement upon any patent, copyright, trademark, trade secret and/or other intellectual property or proprietary rights of any third party.

11. GOVERNING LAW.
THE PARTIES AGREE THAT THIS AGREEMENT AND THE RELATIONSHIP BETWEEN THE PARTIES SHALL BE GOVERNED BY AND CONSTRUED IN ACCORDANCE WITH THE LAWS OF THE STATE OF MARYLAND, WITHOUT REGARD TO ITS PRINCIPLES OF CONFLICTS OF LAWS AND WITHOUT REGARD TO THE UNIFORM COMPUTER INFORMATION TRANSACTIONS ACT. THE PARTIES AGREE THAT THE UNITED NATIONS CONVENTION ON CONTRACTS FOR THE INTERNATIONAL SALE OF GOODS SHALL NOT APPLY TO THIS AGREEMENT. THE PARTIES AGREE TO SUBMIT TO THE EXCLUSIVE  JURISDICTION AND VENUE OF THE FEDERAL AND/OR STATE COURTS IN THE STATE OF MARYLAND FOR THE RESOLUTION OF ANY DISPUTES AMONGST THE PARTIES UNDER THIS AGREEMENT.

12. NOTICES.
Any notice provided pursuant to this Agreement shall be in writing and shall be deemed given (i) if by hand delivery, upon receipt thereof; (ii) if mailed, two (2) days after deposit in the U.S. mails, postage prepaid, certified mail return receipt requested, or (iii) if sent via overnight courier, upon receipt.

13. GENERAL INFORMATION.
This Agreement constitutes the entire agreement between the parties with respect to the subject matter herein, superseding any prior agreements between the parties. The Client further acknowledges and agrees that the Client may not assign any part of this Agreement without obo. Agency’s prior written consent, which may be withheld at its sole discretion. This Agreement shall inure to the benefit of each party’s successors and assigns. obo. Agency shall not be deemed to be in breach of the Agreement and thereby liable to the Client or any third party for any delays in the performance of its obligations hereunder caused by fire, explosion, act of God, strikes, war, riot, government regulation, inability to obtain necessary labor, materials or manufacturing facilities or any other act or cause beyond the reasonable control of obo. Agency. The failure of obo. Agency to exercise or enforce any right or provision of this Agreement shall not constitute a waiver of such right or provision. If any provision of this Agreement is found by a court of competent jurisdiction to be invalid, the parties nevertheless agree that the court should endeavor to give effect to the parties’ intentions as reflected in the provision, and the other provisions of this Agreement shall remain in full force and effect.

14. CONTACTING OBO.AGENCY
If the Client has any questions about this Agreement, or any question or problem regarding the Services, the Client can contact obo. Agency by mail at:
obo. Agency
7165 Columbia Gateway Drive, Suite A

Columbia, MD 21046

Or by telephone at (410) 650-5708.

Effective: August 01, 2019.

obo. : Privacy Policy

Purpose

This privacy notice discloses the practices for obo. Agency (OBO) and applies to information collected by this website.

OBO places a high value on your privacy and the expectation that any information collected by OBO remains confidential and is made available only to persons who have a legitimate right to know. OBO recognizes that all employees have an ethical and legal obligation to keep your information confidential and to protect and safeguard this information against unauthorized use. 

Information We Collect

OBO only has access to collect confidential information that you choose to disclose. Confidential information includes, but is not limited to: name, email address, phone number, and address. 

OBO is the sole owner of the information collected and will not sell, trade, or give any confidential information to a third party without express permission. OBO will use gathered information to respond to you regarding the reason you contacted OBO or display/deliver materials, such as emails and content.

Disclosure of Information

An employee may access, discuss, use, and disclose confidential information only for OBO business as it relates to that employee’s specific job functions and/or responsibilities. Only “Minimally Necessary” information may be disclosed within OBO. “Minimally Necessary” means that only the amount of confidential information necessary to accomplish the intended purpose may be disclosed.

Access to Information

Confidential information may only be accessed by employees if related to specific job functions and responsibilities.

If you wish to correct, update, or otherwise modify information provided to OBO, please reach out via email or phone number. You may opt out of future correspondence at any time by contacting OBO via email or phone number.

Security

OBO has security measures in place to protect against the loss, misuse, or alteration of any information under our control, both online and offline.

Change to This Privacy Policy

This website privacy policy is effective as of the date of its posting. OBO may change this privacy policy over time.

How to Contact Us:

If you have any questions regarding this privacy policy, please contact OBO at office@oboagency.com or 410-650-5708 with a detailed description of your inquiry. 

Last Updated October 7th, 2021