Metadata-Version: 2.4
Name: s6r-hubspot
Version: 1.1.6
Summary: Hubspot API client
Author-email: Michel Perrocheau <michel@scalizer.fr>
License:                    GNU LESSER GENERAL PUBLIC LICENSE
                               Version 3, 29 June 2007
        
         Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
         Everyone is permitted to copy and distribute verbatim copies
         of this license document, but changing it is not allowed.
        
        
          This version of the GNU Lesser General Public License incorporates
        the terms and conditions of version 3 of the GNU General Public
        License, supplemented by the additional permissions listed below.
        
          0. Additional Definitions.
        
          As used herein, "this License" refers to version 3 of the GNU Lesser
        General Public License, and the "GNU GPL" refers to version 3 of the GNU
        General Public License.
        
          "The Library" refers to a covered work governed by this License,
        other than an Application or a Combined Work as defined below.
        
          An "Application" is any work that makes use of an interface provided
        by the Library, but which is not otherwise based on the Library.
        Defining a subclass of a class defined by the Library is deemed a mode
        of using an interface provided by the Library.
        
          A "Combined Work" is a work produced by combining or linking an
        Application with the Library.  The particular version of the Library
        with which the Combined Work was made is also called the "Linked
        Version".
        
          The "Minimal Corresponding Source" for a Combined Work means the
        Corresponding Source for the Combined Work, excluding any source code
        for portions of the Combined Work that, considered in isolation, are
        based on the Application, and not on the Linked Version.
        
          The "Corresponding Application Code" for a Combined Work means the
        object code and/or source code for the Application, including any data
        and utility programs needed for reproducing the Combined Work from the
        Application, but excluding the System Libraries of the Combined Work.
        
          1. Exception to Section 3 of the GNU GPL.
        
          You may convey a covered work under sections 3 and 4 of this License
        without being bound by section 3 of the GNU GPL.
        
          2. Conveying Modified Versions.
        
          If you modify a copy of the Library, and, in your modifications, a
        facility refers to a function or data to be supplied by an Application
        that uses the facility (other than as an argument passed when the
        facility is invoked), then you may convey a copy of the modified
        version:
        
           a) under this License, provided that you make a good faith effort to
           ensure that, in the event an Application does not supply the
           function or data, the facility still operates, and performs
           whatever part of its purpose remains meaningful, or
        
           b) under the GNU GPL, with none of the additional permissions of
           this License applicable to that copy.
        
          3. Object Code Incorporating Material from Library Header Files.
        
          The object code form of an Application may incorporate material from
        a header file that is part of the Library.  You may convey such object
        code under terms of your choice, provided that, if the incorporated
        material is not limited to numerical parameters, data structure
        layouts and accessors, or small macros, inline functions and templates
        (ten or fewer lines in length), you do both of the following:
        
           a) Give prominent notice with each copy of the object code that the
           Library is used in it and that the Library and its use are
           covered by this License.
        
           b) Accompany the object code with a copy of the GNU GPL and this license
           document.
        
          4. Combined Works.
        
          You may convey a Combined Work under terms of your choice that,
        taken together, effectively do not restrict modification of the
        portions of the Library contained in the Combined Work and reverse
        engineering for debugging such modifications, if you also do each of
        the following:
        
           a) Give prominent notice with each copy of the Combined Work that
           the Library is used in it and that the Library and its use are
           covered by this License.
        
           b) Accompany the Combined Work with a copy of the GNU GPL and this license
           document.
        
           c) For a Combined Work that displays copyright notices during
           execution, include the copyright notice for the Library among
           these notices, as well as a reference directing the user to the
           copies of the GNU GPL and this license document.
        
           d) Do one of the following:
        
               0) Convey the Minimal Corresponding Source under the terms of this
               License, and the Corresponding Application Code in a form
               suitable for, and under terms that permit, the user to
               recombine or relink the Application with a modified version of
               the Linked Version to produce a modified Combined Work, in the
               manner specified by section 6 of the GNU GPL for conveying
               Corresponding Source.
        
               1) Use a suitable shared library mechanism for linking with the
               Library.  A suitable mechanism is one that (a) uses at run time
               a copy of the Library already present on the user's computer
               system, and (b) will operate properly with a modified version
               of the Library that is interface-compatible with the Linked
               Version.
        
           e) Provide Installation Information, but only if you would otherwise
           be required to provide such information under section 6 of the
           GNU GPL, and only to the extent that such information is
           necessary to install and execute a modified version of the
           Combined Work produced by recombining or relinking the
           Application with a modified version of the Linked Version. (If
           you use option 4d0, the Installation Information must accompany
           the Minimal Corresponding Source and Corresponding Application
           Code. If you use option 4d1, you must provide the Installation
           Information in the manner specified by section 6 of the GNU GPL
           for conveying Corresponding Source.)
        
          5. Combined Libraries.
        
          You may place library facilities that are a work based on the
        Library side by side in a single library together with other library
        facilities that are not Applications and are not covered by this
        License, and convey such a combined library under terms of your
        choice, if you do both of the following:
        
           a) Accompany the combined library with a copy of the same work based
           on the Library, uncombined with any other library facilities,
           conveyed under the terms of this License.
        
           b) Give prominent notice with the combined library that part of it
           is a work based on the Library, and explaining where to find the
           accompanying uncombined form of the same work.
        
          6. Revised Versions of the GNU Lesser General Public License.
        
          The Free Software Foundation may publish revised and/or new versions
        of the GNU Lesser General Public License from time to time. Such new
        versions will be similar in spirit to the present version, but may
        differ in detail to address new problems or concerns.
        
          Each version is given a distinguishing version number. If the
        Library as you received it specifies that a certain numbered version
        of the GNU Lesser General Public License "or any later version"
        applies to it, you have the option of following the terms and
        conditions either of that published version or of any later version
        published by the Free Software Foundation. If the Library as you
        received it does not specify a version number of the GNU Lesser
        General Public License, you may choose any version of the GNU Lesser
        General Public License ever published by the Free Software Foundation.
        
          If the Library as you received it specifies that a proxy can decide
        whether future versions of the GNU Lesser General Public License shall
        apply, that proxy's public statement of acceptance of any version is
        permanent authorization for you to choose that version for the
        Library.
        
Project-URL: Homepage, https://github.com/ScalizerOrg/s6r-hubspot
Keywords: hubspot
Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests
Provides-Extra: dev
Requires-Dist: twine; extra == "dev"
Requires-Dist: bumpver; extra == "dev"
Requires-Dist: pip-tools; extra == "dev"
Requires-Dist: pytest; extra == "dev"
Requires-Dist: check-manifest; extra == "dev"
Dynamic: license-file

# s6r-hubspot

Python client for the [HubSpot API](https://developers.hubspot.com/docs/api/overview), 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](#installation)
- [Connection](#connection)
- [Generic request](#generic-request)
- [CRM objects](#crm-objects)
- [Associations](#associations)
- [Properties](#properties)
- [Owners](#owners)
- [Account and object schemas](#account-and-object-schemas)
- [Pipelines](#pipelines)
- [Custom objects](#custom-objects)
- [Files](#files)
- [HubDB](#hubdb)
- [CSV import](#csv-import)
- [Errors](#errors)
- [Standard objects and scopes](#standard-objects-and-scopes)
- [Tests](#tests)
- [Tests in Odoo](#tests-in-odoo)

## Installation

```bash
pip install s6r-hubspot
```

Python 3.9 or later; the only dependency is `requests`.

## Connection

With the access token of a HubSpot Private App:

```python
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.

```python
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:

```python
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`).

```python
# 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.

  ```python
  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

```python
# 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

```python
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.

```python
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

```python
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

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

## Custom objects

```python
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

```python
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

```python
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

```python
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 |

```python
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:

```python
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:

```bash
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.

```bash
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](img/run_unit_tests.png)

## Tests in Odoo

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

```bash
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:

```bash
docker compose build
```

## License

This project is licensed under the [GNU Lesser General Public License (LGPL) Version 3](https://www.gnu.org/licenses/lgpl-3.0.html).


## Contributing

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

- GitHub Repository: [ScalizerOrg/s6r-hubspot](https://github.com/ScalizerOrg/s6r-hubspot)

Notable changes are listed in the [CHANGELOG](CHANGELOG.md).


## Contributors

* David Halgand - [GitHub](https://github.com/halgandd)
* Morgane Goujon - [GitHub](https://github.com/MorganeGoujon)
* Khalid Bentaleb - [GitHub](https://github.com/kbentaleb)
* Michel Perrocheau - [GitHub](https://github.com/myrrkel)


## Maintainer

This software is maintained by [Scalizer](https://www.scalizer.fr).


<div style="text-align: center;">

[![Scaliser](./img/logo_scalizer.png)](https://www.scalizer.fr)

</div>
