Install the hubspot-api-client
masterInstall the HubSpot Python SDK using pip to interact with HubSpot APIs.
Requirements
- Python 3.7+
- pip
pip install --upgrade hubspot-api-clientrepository·master·Indexed 19 days ago
https://github.com/hubspot/hubspot-api-pythonA Python client for interacting with HubSpot API v3, including CRM, OAuth, CMS, and Files APIs. The SDK provides a Client class to manage authentication via access tokens or Private Apps, handles pagination for CRM contacts, and supports custom HTTP retry middleware via urllib3. It includes modules for automation, conversations, events, marketing, and settings, with an api_request method for accessing unmapped endpoints.
Install the HubSpot Python SDK using pip to interact with HubSpot APIs.
Requirements
pip install --upgrade hubspot-api-clientInitialize the HubSpot client using an access token. You can provide the token during instantiation or set it on the instance later. Access tokens can be obtained via a Private App or OAuth2.
Note on Hapikey: hapikey is no longer supported as of version 5.1.0. Use Private Apps or OAuth2 instead.
from hubspot import HubSpot
# Initialize with access token
api_client = HubSpot(access_token='your_access_token')
# Or initialize without and set it later
api_client = HubSpot()
api_client.access_token = 'your_access_token'You can configure HTTP retries by passing an instance of urllib3.util.retry.Retry to the HubSpot client constructor.
Internal Error Retry (e.g., 500, 502, 504):
from hubspot import HubSpot
from urllib3.util.retry import Retry
retry = Retry(
total=3,
backoff_factor=0.3,
status_forcelist=(500, 502, 504),
)
api_client = HubSpot(retry=retry)Rate Limit Retry (e.g., 429):
retry = Retry(
total=5,
status_forcelist=(429,),
)
api_client = HubSpot(retry=retry)The Client provides access to various HubSpot API domains through properties. Each property returns a discovery object that allows you to interact with that specific functional area of the HubSpot API.
Available modules include:
crm: CRM API (Contacts, Companies, Deals, etc.)oauth: OAuth APIautomation: Automation APIcms: CMS APIcommunication_preferences: Communication Preferences APIconversations: Conversations APIevents: Events APIfiles: Files APImarketing: Marketing APIsettings: Settings APIwebhooks: Webhooks APIfrom hubspot import Client
client = Client(access_token='your_access_token')
# Access the CRM module
crm_module = client.crm
# Access the Files module
files_module = client.filesThe do_search method is available for all CRM objects (Companies, Contacts, Deals, etc.). When searching by date, ensure the timestamp is provided in milliseconds.
import hubspot
from dateutil import parser
from pprint import pprint
from hubspot.crm.contacts import PublicObjectSearchRequest, ApiException
api_client = hubspot.Client.create(access_token="YOUR_ACCESS_TOKEN")
# Convert date to timestamp in milliseconds
date = str(int(parser.isoparse("XXXX-XX-XXTXX:XX:XX.XXXZ").timestamp() * 1000))
public_object_search_request = PublicObjectSearchRequest(
filter_groups=[
{
"filters": [
{
"value": date,
"propertyName": "lastmodifieddate",
"operator": "EQ"
}
]
}
],
limit=10
)
try:
api_response = api_client.crm.contacts.search_api.do_search(public_object_search_request=public_object_search_request)
pprint(api_response)
except ApiException as e:
print("Exception when calling search_api->do_search: %s\n" % e)The CRM API allows you to create and retrieve contacts.
Create a contact
Use SimplePublicObjectInputForCreate to define properties like email.
Get a contact by ID
Use basic_api.get_by_id(contact_id) to fetch a specific contact.
Get all contacts
Use get_all() to retrieve all contacts. This method handles pagination automatically.
from hubspot.crm.contacts import SimplePublicObjectInputForCreate
from hubspot.crm.contacts.exceptions import ApiException
# Create contact
try:
simple_public_object_input_for_create = SimplePublicObjectInputForCreate(
properties={"email": "email@example.com"}
)
api_response = api_client.crm.contacts.basic_api.create(
simple_public_object_input_for_create=simple_public_object_input_for_create
)
except ApiException as e:
print("Exception when creating contact: %s\n" % e)
# Get contact by id
try:
contact_fetched = api_client.crm.contacts.basic_api.get_by_id('contact_id')
except ApiException as e:
print("Exception when requesting contact by id: %s\n" % e)
# Get all contacts (handles pagination)
all_contacts = api_client.crm.contacts.get_all()Use the files.files_api.upload method to upload files. The options parameter must be a JSON-encoded string containing configuration like access (e.g., 'PRIVATE') and overwrite.
import hubspot
import json
from pprint import pprint
from hubspot.crm.contacts import ApiException
client = hubspot.Client.create(access_token="your_access_token")
options = json.dumps(
{'access': 'PRIVATE',
"overwrite": False}
)
try:
response = client.files.files_api.upload(
file="/file/path/file.jpeg",
file_name="name_in_hubspot",
folder_path="folder_in_hubspot",
options=options,
)
pprint(response)
except ApiException as e:
print("Exception when calling basic_api->get_page: %s\n" % e)Use the oauth.tokens_api.create method to exchange an authorization code for access tokens.
from hubspot.oauth import ApiException
try:
tokens = api_client.oauth.tokens_api.create(
grant_type="authorization_code",
redirect_uri='http://localhost',
client_id='client_id',
client_secret='client_secret',
code='code'
)
except ApiException as e:
print("Exception when calling create_token method: %s\n" % e)If the SDK does not yet have a wrapper for a specific endpoint, you can use the api_request method to make direct calls. This method uses the client's existing configuration (like access tokens).
# GET request example
response = client.api_request({"path": "/crm/v3/objects/contacts"})
# POST request example
response = client.api_request(
{
"path": "/crm/v3/objects/contacts",
"method": "POST",
"body": {
"properties": {
"email": "some_email@some.com",
"lastname": "some_last_name"
},
}
}
)Most response objects in the SDK provide a to_dict() method to convert the object into a standard Python dictionary.
contacts = api_client.crm.contacts.basic_api.get_page()
for contact in contacts.results:
print(contact.to_dict())The Client class is the primary entrypoint for the HubSpot SDK. You can initialize it by providing either an api_key or an access_token. You can also pass a retry object (from urllib3.util.retry.Retry) to configure request retries and other configuration via **kwargs.
from hubspot import Client
# Using an access token (recommended for OAuth)
client = Client(access_token='your_access_token')
# Using an API key
client = Client(api_key='your_api_key')
# Using the create classmethod
client = Client.create(access_token='your_access_token')You can dynamically update the authentication credentials of an existing Client instance using the access_token or api_key properties.
from hubspot import Client
client = Client(api_key='old_key')
# Update to use an access token instead
client.access_token = 'new_access_token'
# Or update the API key
client.api_key = 'new_api_key'