Skip to main content

HubSpot API client

Project description

hubspot-api-python

Python HubSpot API v3 SDK(Client) files and sample apps

Sample Applications can be found in Sample apps

Documentation

See the API docs.

Installation

If you just want to use the package, run:

pip install --upgrade hubspot-api-client

Requirements

Make sure you have Python 3.7+ and pip installed.

Quickstart

Configuring HubSpot client

from hubspot import HubSpot

api_client = HubSpot(access_token='your_access_token')

# or set your access token later
api_client = HubSpot()
api_client.access_token = 'your_access_token'

You'll need to create a private app to get your access token or you can obtain OAuth2 access token.

Hapikey support:

Please, note that hapikey is no longer supported after v5.1.0. You can get more info about hapikey sunset here. Also, plese, visit a migration guide if you need help with a migration process.

OAuth API

Obtain OAuth2 access token:

from hubspot.auth.oauth import ApiException

try:
    tokens = api_client.auth.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)

CRM API

Create contact:

from hubspot.crm.contacts import SimplePublicObjectInputForCreate
from hubspot.crm.contacts.exceptions import ApiException

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:

from hubspot.crm.contacts import ApiException

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 custom objects page:

from hubspot.crm.objects import ApiException

try:
    my_custom_objects_page = api_client.crm.objects.basic_api.get_page(object_type="my_custom_object_type")
except ApiException as e:
    print("Exception when requesting custom objects: %s\n" % e)

Get all:

get_all method is available for all objects (Companies, Contacts, Deals and etc).

all_contacts = api_client.crm.contacts.get_all()

Please note that pagination is used under the hood to get all results.

Search:

do_search method is available for all objects (Companies, Contacts, Deals and etc).

Example Search by date:

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")

# 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)

CMS API

Get audit logs:

from hubspot.cms.audit_logs import ApiException

try:
    audit_logs_page = api_client.cms.audit_logs.default_api.get_page()
except ApiException as e:
    print("Exception when calling cards_api->create: %s\n" % e)

Not wrapped endpoint(s)

It is possible to access the hubspot request method directly, it could be handy if client doesn't have implementation for some endpoint yet. Exposed request method benefits by having all configured client params.

client.api_request({
    "method": "PUT",
    "path": "/some/api/not/wrapped/yet",
    "body": {"key": "value"}
})

{Example} for GET request

import hubspot
from pprint import pprint
from hubspot.crm.contacts import ApiException

client = hubspot.Client.create(access_token="your_access_token")

try:
    response = client.api_request(
        {"path": "/crm/v3/objects/contacts"}
    )
    pprint(response)
except ApiException as e:
    print(e)

{Example} for POST request

import hubspot
from pprint import pprint
from hubspot.crm.contacts import ApiException

client = hubspot.Client.create(access_token="your_access_token")

try:
    response = client.api_request(
        {
            "path": "/crm/v3/objects/contacts",
            "method": "POST",
            "body": {
                "properties":
                    {
                        "email": "some_email@some.com",
                        "lastname": "some_last_name"
                    },
            }
        }

    )
    pprint(response.json())
except ApiException as e:
    print(e)

Using utils

Get OAuth url:

from hubspot.utils.oauth import get_auth_url

auth_url = get_auth_url(
    scope=('contacts',),
    client_id='client_id',
    redirect_uri='http://localhost'
)

Validate HubSpot request signature

Example of usage from Webhooks Sample App:

import os
from flask import request
from hubspot.utils.signature import Signature

Signature.is_valid(
    signature=request.headers["X-HubSpot-Signature"],
    client_secret=os.getenv("HUBSPOT_CLIENT_SECRET"),
    request_body=request.data.decode("utf-8"),
    http_uri=request.base_url,
    signature_version=request.headers["X-HubSpot-Signature-Version"],
    timestamp=request.headers["X-HubSpot-Request-Timestamp"]
)

Retry middleware

You can pass an instance of urllib3.util.retry.Retry class to configure http client retries. With internal error retry middleware:

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)

Or with rate limit retry middleware:

from hubspot import HubSpot
from urllib3.util.retry import Retry

retry = Retry(
    total=5,
    status_forcelist=(429,),
)
api_client = HubSpot(retry=retry)

Convert response object to dict

to_dict method is available for most response objects

contacts = api_client.crm.contacts.basic_api.get_page()
for contact in contacts:
    print(contact.to_dict())

Sample Apps

Please, take a look at our Sample apps

Contributing

Install the package locally:

pip install -e .

Set up the development virtualenv:

make

Run tests:

make test

Run Black for code formatting:

make fmt

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

hubspot_api_client-11.1.0.tar.gz (1.7 MB view details)

Uploaded Source

Built Distribution

hubspot_api_client-11.1.0-py3-none-any.whl (3.9 MB view details)

Uploaded Python 3

File details

Details for the file hubspot_api_client-11.1.0.tar.gz.

File metadata

  • Download URL: hubspot_api_client-11.1.0.tar.gz
  • Upload date:
  • Size: 1.7 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.0.1 CPython/3.12.8

File hashes

Hashes for hubspot_api_client-11.1.0.tar.gz
Algorithm Hash digest
SHA256 93ed914f1cd4dad67bacf26b8a1ec8506847483fa801cb2bddd4b2d887d0f825
MD5 c46398f014d44a91508135434f8ec2cb
BLAKE2b-256 085211b0ecd4fd6e175813a0017ab4bc4697bfde058cac9b98938fa28460028a

See more details on using hashes here.

Provenance

The following attestation bundles were made for hubspot_api_client-11.1.0.tar.gz:

Publisher: pythonpublish.yml on HubSpot/hubspot-api-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file hubspot_api_client-11.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for hubspot_api_client-11.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0c49e2c2f511a56d249c6890d2dfdd62afd04f66edc69a591e8348e28804634b
MD5 5c0069a05b0ca43789b9ef7815785ad1
BLAKE2b-256 a1d3a2dbdea1f491d5bf362d74d4b7342ece6c043a43c8ee997f8fb8b776239d

See more details on using hashes here.

Provenance

The following attestation bundles were made for hubspot_api_client-11.1.0-py3-none-any.whl:

Publisher: pythonpublish.yml on HubSpot/hubspot-api-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page