Skip to main content

s6r-hubspot

Python client for the HubSpot API, used by the Scalizer Odoo ↔ HubSpot connector (s6r_connector_hubspot) and usable on its own.

It covers the CRM objects (batch create / read / update / archive, search, associations), properties, owners, pipelines, custom object schemas, files, HubDB and CSV imports — and any other endpoint through a generic request method. API calls renew an expired OAuth token, wait and retry on a rate limit, and raise typed errors telling which scope is missing — except the files, HubDB, archive and delete methods, which return HubSpot's response as is.

Installation

pip install s6r-hubspot

Python 3.9 or later; the only dependency is requests.

Connection

With the access token of a HubSpot Private App:

from s6r_hubspot import HubspotConnection

hubspot = HubspotConnection(token='pat-eu1-...')

With an OAuth token, renewed automatically when it expires: get_token returns the current token, and set_token stores the renewed one.

def get_token():
    return {
        'access_token': '...',
        'refresh_token': '...',
        'client_id': '...',
        'client_secret': '...',
    }

def set_token(access_token, refresh_token, client_id, client_secret):
    ...  # persist the renewed token

hubspot = HubspotConnection(get_token=get_token, set_token=set_token)
Parameter Default Description
token False Private App access token
get_token / set_token False OAuth token callbacks (see above)
timeout (10, 120) requests timeout of every HTTP call, in seconds: a number or a (connect, read) tuple (s6r_hubspot.DEFAULT_TIMEOUT)
debug False log at DEBUG level

Without a refresh token, an expired token raises HubSpotAuthError.

Generic request

Any endpoint without a dedicated method is reachable through request, with the same token renewal, rate-limit retries and typed errors as the other methods:

quotes = hubspot.request(
    'POST', '/crm/v3/objects/quotes/search',
    json={'filterGroups': [], 'properties': ['hs_title'], 'limit': 100},
    required_scope='crm.objects.quotes.read',
)
hubspot.request('DELETE', '/crm/v3/objects/quotes/123')
  • method: GET, POST, PATCH, PUT or DELETE.
  • path: relative to https://api.hubapi.com, or a full URL.
  • params: query string parameters; json: JSON body.
  • required_scope / hubspot_section: reported by HubSpotScopeError when the scope is missing.
  • max_retries (3) / retry_delay (1.5 s): retries on an expired token or a rate limit.
  • Returns the JSON response, {} for an empty one (e.g. 204 No Content).

CRM objects

model is the object type: contacts, companies, deals, products, line_items… or the fully qualified name of a custom object (p12345678_invoice).

# Create, update: batches of 95 inputs
created = hubspot.create('contacts', [{'properties': {'email': 'jane@example.com', 'firstname': 'Jane'}}])
hubspot.update('contacts', [{'id': created[0]['id'], 'properties': {'lastname': 'Doe'}}])

# Read by id, or by a unique property
contacts = hubspot.read('contacts', ['101', '102'], ['email', 'firstname'])
contacts = hubspot.read('contacts', ['jane@example.com'], ['firstname'], property_name='email')

# Search
deals = hubspot.search(
    'deals',
    filters=[{'propertyName': 'amount', 'operator': 'GT', 'value': '1000'}],
    properties=['dealname', 'amount'],
    sorts=[{'propertyName': 'createdate', 'direction': 'DESCENDING'}],
)
deals, total = hubspot.search('deals', filters=[...], get_total=True)

# Every record of a type, page by page
products = hubspot.get_all('products', ['name', 'price'])

# Archive
hubspot.archive('contacts', ['101', '102'])
  • Batch results. create, update and read return a BatchResult: a list of the records that succeeded, with the errors of the inputs that failed (HubSpot answers a partial failure with HTTP 207) in its errors attribute. These errors are also logged as warnings.

    result = hubspot.create('contacts', vals_list)
    for error in result.errors:
        print(error['category'], error['message'])
    
  • Search. filters is one group of filters (AND); filterGroups several groups (OR). HubSpot allows 5 groups, 6 filters per group, 18 filters in total, and 100 values per IN filter. A search returns at most 10 000 records: beyond, get_total=True tells the real total, and get_all reads everything.

  • Associations while reading. search, read and get_all take associations=['companies', ...]: each record then carries a _companies key, the list of {'id', 'label'} of its associated records. With search(..., load_associations=True), these associated records are read too.

Associations

# Associated records, read in batch (v4 API)
links = hubspot.get_association('deals', 'companies', ['201', '202'])

# Create typed associations, in batches; returns a BatchResult
hubspot.association_batch_create('deals', 'companies', [{
    'types': [{'associationCategory': 'HUBSPOT_DEFINED', 'associationTypeId': 5}],
    'from': {'id': '201'},
    'to': {'id': '301'},
}])

# Association types and labels between two object types
labels = hubspot.get_association_label('deals', 'companies')

# Remove associations
hubspot.delete_associations('deals', 'companies', [{'from': {'id': '201'}, 'to': [{'id': '301'}]}])

create_association(model_from, model_to, vals) creates associations too, in batches of 75, without reporting the inputs that failed.

Properties

properties = hubspot._get_properties('deals')            # every property of an object type
found = hubspot._search_properties('deals', 'amount')    # by keyword, in the name or the description
hubspot._create_properties('deals', {'inputs': [{
    'name': 'id_odoo', 'label': 'Odoo ID', 'type': 'string', 'fieldType': 'text', 'groupName': 'dealinformation',
}]})
hubspot._update_properties('deals', 'id_odoo', {'label': 'Odoo identifier'})
hubspot._archive_properties('deals', 'id_odoo')

Owners

HubSpot owners are the users of the account. A deactivated user is an archived owner.

owners = hubspot.get_owners()                        # active owners, every page
owners = hubspot.get_owners(include_archived=True)   # then the archived ones
owner = hubspot.get_owner('29651049')                # by id, archived included by default
owner = hubspot.get_owner_by_email('Jane@Example.com')

get_owner_by_email ignores the case of the email and returns an active owner first, then an archived one (include_archived=True by default), or None. All of them need the crm.objects.owners.read scope.

Account and object schemas

details = hubspot.get_account_details()
details['portalId'], details['uiDomain']   # 12345678, 'app-eu1.hubspot.com'

schema = hubspot.get_schema('deals')
schema['objectTypeId']                     # '0-3' ('2-…' for a custom object)

With the portal id, the app domain and the objectTypeId, the URL of a record in HubSpot is https://{uiDomain}/contacts/{portalId}/record/{objectTypeId}/{record_id}.

Pipelines

pipelines = hubspot.get_pipelines('deals')                  # pipelines and their stages
pipeline = hubspot.get_pipeline('deals', 'default')
stage = hubspot.get_stage('deals', 'default', 'appointmentscheduled')

Custom objects

schemas = hubspot.get_custom_object()          # every custom object schema
hubspot.create_custom_object('invoice', 'Invoice')
hubspot.update_custom_object('p12345678_invoice', 'invoice', properties)

create_custom_object creates the schema with a unique id_odoo property as primary display property. Records of a custom object are handled like any CRM object, with its fully qualified name as model.

Files

folder = hubspot.create_folder('Invoices', parent_folder_id='')
folders = hubspot.search_folder()
hubspot.update_folder_name('Invoices 2026', folder['id'])
with open('invoice.pdf', 'rb') as file:
    uploaded = hubspot.upload_file(file, 'invoice.pdf', folder['id'])   # public, overwritten
hubspot.delete_folder(folder['id'])

HubDB

tables = hubspot.get_hub_db()
table = hubspot.create_table_hub_db('Products', 'products')
hubspot.update_table_hub_db(table['id'], 'Products', 'products', columns)
row = hubspot.create_hub_db(table['id'], {'values': {'name': 'Chair'}})
hubspot.update_hub_db(table['id'], row['id'], {'values': {'name': 'Armchair'}})
hubspot.search_hub_db(table['id'], 'name', 'Armchair')
hubspot.delete_hub_db(table['id'], row['id'])
hubspot.publish_hub_db(table['id'])            # rows are edited as a draft until published

CSV import

hubspot.import_file('0-1', datas, keys)

Updates records of the object type model (an objectTypeId, e.g. 0-1 for contacts) through the HubSpot imports API, from datas (a list of dicts, one per CSV line); keys is the list of (property name, column label) tuples, the records being matched on id_odoo.

Errors

The errors raised by the library all derive from HubSpotError:

Exception Raised when
HubSpotAuthError the token is expired and cannot be renewed (no refresh token)
HubSpotScopeError the Private App lacks a scope: required_scope and hubspot_section tell which one, and where to grant it
HubSpotRateLimitError the rate limit is still reached after the retries
HubSpotNotFoundError the endpoint or the object does not exist (HTTP 404, request and the methods built on it)
HubSpotError any other HubSpot error, with its message
from s6r_hubspot import HubSpotError, HubSpotScopeError

try:
    owners = hubspot.get_owners()
except HubSpotScopeError as e:
    print("Grant the scope %s (%s)" % (e.required_scope, e.hubspot_section))
except HubSpotError as e:
    print("HubSpot error: %s" % e)

Standard objects and scopes

STANDARD_OBJECTS lists the HubSpot standard object types, with their label, API name and the scope needed to read them; get_scope_for_object gives the scope of an object type:

from s6r_hubspot import STANDARD_OBJECTS, get_scope_for_object

STANDARD_OBJECTS['deals']        # {'label': 'Deals', 'api_name': 'deals', 'scope': 'crm.objects.deals.read'}
get_scope_for_object('0-420')    # 'crm.objects.listings.read'

Tests

Offline tests, HubSpot being mocked — run from the repository root:

python -m unittest src.tests.test_request src.tests.test_batch_results

Tests against a real HubSpot account (src/tests/unit_test.py) create and delete records: run them on an empty test account, whose Private App token is set in the HUBSPOT_TOKEN environment variable. The scopes they need are listed at the top of the file.

export HUBSPOT_TOKEN='your_token'
python -m unittest src.tests.unit_test

A token of the test account is in Bitwarden: "s6r-hubspot Test Instance".

run_unit_tests.png

Tests in Odoo

To test the library in Odoo before publishing it, build the wheel:

python -m build --wheel

install it in the image (Dockerfile_test), replacing x.y.z with the version:

COPY docker/s6r_hubspot-x.y.z-py3-none-any.whl /tmp/s6r_hubspot-x.y.z-py3-none-any.whl
RUN pip3 install /tmp/s6r_hubspot-x.y.z-py3-none-any.whl

and rebuild the image:

docker compose build

License

This project is licensed under the GNU Lesser General Public License (LGPL) Version 3.

Contributing

Contributions are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request.

Notable changes are listed in the CHANGELOG.

Contributors

Maintainer

This software is maintained by Scalizer.

Scaliser

Metadata

Release files for s6r-hubspot 1.1.6

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for s6r-hubspot 1.1.6
File Size Uploaded Provenance Actions
s6r_hubspot-1.1.6.tar.gz 35.3 kB Without provenance Details for s6r_hubspot-1.1.6.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for s6r-hubspot 1.1.6
File Interpreter ABI Platform Actions
s6r_hubspot-1.1.6-py3-none-any.whl Python 3 none any Details for s6r_hubspot-1.1.6-py3-none-any.whl

Total release size: 69.2 kB

Release files / s6r_hubspot-1.1.6.tar.gz

Download URL s6r_hubspot-1.1.6.tar.gz
Size 35.3 kB
Tags Source
SHA-256 checksum
How to use checksums
6a55bc3f876725833064921cc99f585e416173d2288a0627127c84a3d90686c2
BLAKE2b-256 checksum
How to use checksums
5c8a646c50a41828793af0622c35a1f557bca8bc78605404e6b2df7861b39bd0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / s6r_hubspot-1.1.6-py3-none-any.whl

Download URL s6r_hubspot-1.1.6-py3-none-any.whl
Size 33.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ede9f9278173d18f381ab21a5df1c6053aeb6cfef2041cc625f01a010cd7c759
BLAKE2b-256 checksum
How to use checksums
df52af1cf4f38734187531518ae311fe7636e7dfe4c9cc357b55cc12a9b98ddc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Security for s6r-hubspot 1.1.6

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page