GithubHelp home page GithubHelp logo

hubspot / hubspot-api-python Goto Github PK

View Code? Open in Web Editor NEW
306.0 15.0 99.0 4.99 MB

HubSpot API Python Client Libraries for V3 version of the API

License: Apache License 2.0

Python 100.00% Makefile 0.01%

hubspot-api-python's Introduction

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.5+ 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 protected]"}
    )
    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)

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 datetime import datetime
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=datetime.now().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

hubspot-api-python's People

Contributors

abenbecker avatar alzheltkovskiy-hubspot avatar atanasiuk-hubspot avatar cclauss avatar cconrad avatar fakepop avatar james-d-f avatar jtruty avatar ksvirkou-hubspot avatar navan0 avatar plaurynovich-hubspot avatar ronfer avatar rwiggers avatar spark-c avatar tony-romanovych avatar twolfson avatar yfaktor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hubspot-api-python's Issues

Webhooks triggered by Workflows

Hello!

I was wondering if webhooks via automated workflows are supported by this library?

I could only find webhooks via subscriptions.

Thank you!

CRM Owners missing **kwargs for archived

owners get_page function does not accept parameter archived like other crm items

def get_page(self, **kwargs): # noqa: E501

:param bool archived: Whether to return only results that have been archived.

import requests
url = "https://api.hubapi.com/crm/v3/owners/"
querystring = {"limit":"100","archived":"false","hapikey":"YOUR_HUBSPOT_API_KEY"}
headers = {'accept': 'application/json'}
response = requests.request("GET", url, headers=headers, params=querystring)
print(response.text)

get_all response to dict

Hey,
I'm new to the HS SDK and I'm wondering if I can get a python dict or JSON out of a hsClient.crm.deals.get_all() call instead of a SimplePublicObject type. 🙏

Getting invalid input JSON on line 1 when i do use contacts.search_api.do_search

Hello, I want to filter my contacts by email but I get this error. I can create a contact without error.

from hubspot.crm.contacts.models import SimplePublicObjectInput, PublicObjectSearchRequest, Filter, FilterGroup

class UpdateContact(HubSpotCommand):
    def __init__(self, member_type, email, contact_id=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.member_type = member_type
        self.email = email
        self.contact_id = contact_id

    @property
    def public_object_search_request(self):
        email_filter = Filter(property_name="email", operator="EQ", value=self.email)
        filter_group = FilterGroup(filters=[email_filter])
        return PublicObjectSearchRequest(
            filter_groups=filter_group
        )

    def run(self):
        response = self.api_client.crm.contacts.search_api.do_search(public_object_search_request=self.public_object_search_request)
        return response
HTTP response body: {"status":"error","message":"Invalid input JSON on line 1, column 18: Cannot deserialize instance of `java.util.HashSet` out of START_OBJECT token","correlationId":"04e000f4-7d37-4a91-b76e-0db60a0fa7be"}

Example for creating a deal + trello example doesnt work

Looking for an example of creating a deal. While searching this repo I found this

https://github.com/HubSpot/hubspot-api-python/blob/master/sample-apps/trello-integration-app/src/routes/trello/webhooks.py#L29

In [11]: hubspot.crm.deals.basic_api
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-11-16000a60ab80> in <module>
----> 1 hubspot.crm.deals.basic_api

AttributeError: module 'hubspot.crm.deals' has no attribute 'basic_api'

Seems like it should be hubspot.crm.deals.api.basic_api

Create a contact and associate it with a company

When I create a new contact with 'company': 'Company name', it doesn't list it as an associated company in the contacts overview. How do I associate a contact with a company during/after create?

Discovery API support for ignoring SSL Verification

When creating a HubSpot API client using hubspot.Client.create() we are able to bypass SSL verification for subsequent calls using that client by passing the kwarg verify_ssl=False; however, we are unable to do the same when creating a Discovery object as the _configure_api_client method of the DiscoveryBase class only pulls api_key, access_token, and retry from the config property of the object, ignoring any other configurations set during the creation of the Discovery object, thus dropping the verify_ssl kwarg if it was present on create of the object.

I propose updating the code of the DiscoveryBase._configure_api_client method to either use the entire config property of the object when creating the api_client_package.ApiClient object or minimally adding the following conditional to ensure the verify_ssl kwarg is propagated to the resulting Discovery object, allowing us to bypass SSL verification as needed:

if "verify_ssl" in config:
    configuration.verify_ssl = config["verify_ssl"]

Some background on why this is needed in my case - I am working behind a corporate VPN which occasionally results in SSL verification issues. Since the HubSpot API is build on top of urllib3 instead of requests I'm unable to leverage the REQUESTS_CA_BUNDLE env var for working around this issue as I've been able to with other packages that do leverage requests

types_api not available under crm/associations

Hi!
I have been playing with the API today and has been quite smooth, except when I trying to query association types.
I'm trying do something like this:

api_client.crm.associations.types_api.get_all(from_object_type="deals", to_object_type="companies")

or this

api_client.crm.associations.get_all(from_object_type="deals", to_object_type="companies")

But then I realised that under crm.associations, the api only sees the batch_api methods and not the types_api ones, maybe something is missing?

Screenshot 2021-09-24 at 18 37 39

Many thanks!

HubDB API does not seem to authenticate properly

With this code:

hubspot = HubSpot(api_key='...')
hubspot.cms.hubdb.default_api.get_all_tables()

I get an error in response:

Authentication credentials not found. This API supports both API Key and OAuth 2.0 authentication and you can find more details at https://developers.hubspot.com/docs/methods/auth/oauth-overview

Am I doing something wrong or is this a bug?

Getting better error messages when creating users by batch

When creating contacts using:

hubspot_api.crm.contacts.batch_api.create()

If the batch_input_simple_public_object_input objects contains multiple users that already exist the error message only tells you the first one it encounters.

Meaning its hard to know which users we need to update instead of create.

Custom Object Creation Fails for required attributes not set[label]

Hi there, I am using hubspot api in python using hubspot-api-client 3.4.2 from Pypi.
I am trying to create a custom object. I am trying to create a custom object from the given example here :
https://developers.hubspot.com/docs/api/crm/crm-custom-objects

Although first time my lambda failed with this Error : Cannot deserialize instance of java.util.ArrayList out of START_OBJECT token
After that I enclosed my properties inside the ObjectSchemaEgg with [] like following:

from hubspot.crm.schemas import ObjectSchema
from hubspot.crm.schemas import ObjectSchemaEgg
from hubspot.crm.schemas import CoreApi
def _create_catapult_sub_product_custObject_schema_hs(self):
     hubspot = self.get_hubspot_client()     
     sub_product_custObj_schema = ObjectSchemaEgg(
               properties=[{
                    "name": "my_object",
                    "labels": {
                        "singular": "My object",
                        "plural": "My objects"
                    },
                    "primaryDisplayProperty": "my_object_property",
                    "requiredProperties": ["my_object_property"],
                    "properties": [{
                            "name": "my_object_property",
                            "label": "My object property",
                            "isPrimaryDisplayLabel": True
                        }
                    ],
                    "associatedObjects": ["CONTACT"],
                    "metaType": "PORTAL_SPECIFIC"
                }]
        )
        api_response = None
        try:
            api_response = hubspot.crm.schemas.core_api.create(object_schema_egg = sub_product_custObj_schema)
        except Exception as e:
            print("API Exception Happened:", (str(e))) 
        return api_response

But again, my custom object creation is failing in lambda with Cannot build ObjectTypePropertyCreate, some of required attributes are not set [label]"*

Expected Result: The custom object should be created with 200 SUCCESS

Actual Result: Request fails with 400 Error with final message in stacktrace: Cannot build ObjectTypePropertyCreate, some of required attributes are not set [label]

Version I am using : hubspot-api-client 3.4.2

How to get a company by a domain?

I am trying to get a company by domain is there an easier way to do this than using these complex filters?

    def get_company_by_domain(self, domain: str):

        domain_filter = hubspot.crm.companies.models.Filter(
            property_name="domain",
            operator="EQ",
            value=domain
        )

        filter_group = hubspot.crm.companies.models.FilterGroup(
            filters=[domain_filter]
        )

        public_object_search_request = hubspot.crm.companies.models.PublicObjectSearchRequest(
            filter_groups=[filter_group]
        )

        company_results = self.hubspot_api_client.crm.companies.search_api.do_search(
            public_object_search_request=public_object_search_request
        )
        return company_results

Custom Objects

With the new custom objects feature now live is there any plan on adding it into this library?

docker-compose command for sample apps was crashing

When running: docker-compose up --build web
in the sample apps, I was getting an error (see bottom of this issue).

I was able to fix it by adding:
ADD /sample-apps/oauth-app/README.md /sdk/

to the Dockerfile before the WORKDIR /sdk/ command

Error:

Creating network "rate-limit-app_default" with the default driver
Building web
Step 1/12 : FROM python:3.8
---> 9756fa8d7b9d
Step 2/12 : RUN mkdir -p /sdk
---> Using cache
---> d504848a32af
Step 3/12 : ADD ./hubspot /sdk/hubspot
---> Using cache
---> a2a9478a4011
Step 4/12 : ADD ./setup.py VERSION /sdk/
---> Using cache
---> 68c0d6307383
Step 5/12 : WORKDIR /sdk
---> Using cache
---> 820a681f7c2a
Step 6/12 : RUN pip install -e .
---> Running in 7ea5e6d88101
Obtaining file:///sdk
ERROR: Command errored out with exit status 1:
command: /usr/local/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/sdk/setup.py'"'"'; file='"'"'/sdk/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-1licyj80
cwd: /sdk/
Complete output (5 lines):
Traceback (most recent call last):
File "", line 1, in
File "/sdk/setup.py", line 34, in
with open(DIR_PATH + "/README.md", "r", encoding="utf-8") as f:
FileNotFoundError: [Errno 2] No such file or directory: '/sdk/README.md'
----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
ERROR: Service 'web' failed to build : The command '/bin/sh -c pip install -e .' returned a non-zero code: 1

3.7.0 seems broken

I had a non-pinned dependency, so I ran tests just now and got this big crash in tests:

Internal Server Error: /prospects/1/edit/1/data/
Traceback (most recent call last):
  File "/Users/boxed/Projects/dryft/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/Users/boxed/Projects/dryft/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 167, in _get_response
    callback, callback_args, callback_kwargs = self.resolve_request(request)
  File "/Users/boxed/Projects/dryft/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 290, in resolve_request
    resolver_match = resolver.resolve(request.path_info)
  File "/Users/boxed/Projects/dryft/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 545, in resolve
    for pattern in self.url_patterns:
  File "/Users/boxed/Projects/dryft/venv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/boxed/Projects/dryft/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 589, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/Users/boxed/Projects/dryft/venv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/boxed/Projects/dryft/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 582, in urlconf_module
    return import_module(self.urlconf_name)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/Users/boxed/Projects/dryft/dryft/urls.py", line 22, in <module>
    path('integrations/', include('dryft.integrations.urls')),
  File "/Users/boxed/Projects/dryft/venv/lib/python3.8/site-packages/django/urls/conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/Users/boxed/Projects/dryft/dryft/integrations/urls.py", line 10, in <module>
    path('hubspot/', include('dryft.integrations.hubspot.urls')),
  File "/Users/boxed/Projects/dryft/venv/lib/python3.8/site-packages/django/urls/conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/Users/boxed/Projects/dryft/dryft/integrations/hubspot/urls.py", line 2, in <module>
    from . import views
  File "/Users/boxed/Projects/dryft/dryft/integrations/hubspot/views.py", line 3, in <module>
    from hubspot import HubSpot
  File "/Users/boxed/Projects/dryft/venv/lib/python3.8/site-packages/hubspot/__init__.py", line 1, in <module>
    from .client import Client
  File "/Users/boxed/Projects/dryft/venv/lib/python3.8/site-packages/hubspot/client.py", line 5, in <module>
    from .discovery.conversations.discovery import Discovery as ConversationsDiscovery
  File "/Users/boxed/Projects/dryft/venv/lib/python3.8/site-packages/hubspot/discovery/conversations/discovery.py", line 2, in <module>
    from .visitor_identification.discovery import Discovery as VisitorIdentificationDiscovery
  File "/Users/boxed/Projects/dryft/venv/lib/python3.8/site-packages/hubspot/discovery/conversations/visitor_identification/discovery.py", line 1, in <module>
    import hubspot.conversations.visitor_identification as api_client
ModuleNotFoundError: No module named 'hubspot.conversations'

I've worked around it for now by pinning to 3.6.1

3.7.0 Initial import fails - dateparser throws syntax invalid alert.

Hi ! Thanks for making this package.

I've installed hubspot-api-client via pip
Using Python 3.7.0

I've added the line :

from hubspot import HubSpot

And I'm receiving this error. I'm unsure what the problem with dateutil is.

Traceback (most recent call last):
File "C:\Users\Hector\Documents\ergonomyx\ergonomyx-ecommerce\ergonomyx.py", line 15, in
from app import app
File "C:\Users\Hector\Documents\ergonomyx\ergonomyx-ecommerce\app_init_.py", line 310, in
from app import routes, models, errors, admin_center, ajax_handlers, assets, login_register, tax_helpers, gtag_helpers
File "C:\Users\Hector\Documents\ergonomyx\ergonomyx-ecommerce\app\routes.py", line 38, in
from hubspot import HubSpot
File "c:\users\hector\documents\ergonomyx\ergonomyx-ecommerce\venv\lib\site-packages\hubspot_init_.py", line 1, in
from .client import Client
File "c:\users\hector\documents\ergonomyx\ergonomyx-ecommerce\venv\lib\site-packages\hubspot\client.py", line 2, in
from .discovery.auth.discovery import Discovery as AuthDiscovery
File "c:\users\hector\documents\ergonomyx\ergonomyx-ecommerce\venv\lib\site-packages\hubspot\discovery\auth\discovery.py", line 1, in
from .oauth.discovery import Discovery as OAuthDiscovery
File "c:\users\hector\documents\ergonomyx\ergonomyx-ecommerce\venv\lib\site-packages\hubspot\discovery\auth\oauth\discovery.py", line 1, in
import hubspot.auth.oauth as api_client
File "c:\users\hector\documents\ergonomyx\ergonomyx-ecommerce\venv\lib\site-packages\hubspot\auth\oauth_init_.py", line 20, in
from hubspot.auth.oauth.api.default_api import DefaultApi
File "c:\users\hector\documents\ergonomyx\ergonomyx-ecommerce\venv\lib\site-packages\hubspot\auth\oauth\api_init_.py", line 6, in
from hubspot.auth.oauth.api.default_api import DefaultApi
File "c:\users\hector\documents\ergonomyx\ergonomyx-ecommerce\venv\lib\site-packages\hubspot\auth\oauth\api\default_api.py", line 20, in
from hubspot.auth.oauth.api_client import ApiClient
File "c:\users\hector\documents\ergonomyx\ergonomyx-ecommerce\venv\lib\site-packages\hubspot\auth\oauth\api_client.py", line 15, in
from dateutil.parser import parse
File "c:\users\hector\documents\ergonomyx\ergonomyx-ecommerce\venv\lib\site-packages\dateutil\parser.py", line 158
l.append("%s=%s" % (attr, value))

Unable to import ObjectType

In the sample applications this line appears a couple of times:

from hubspot.crm import ObjectType

But from version 3.8.0, this import fails

>>> from hubspot.crm import ObjectType
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'ObjectType'

Is it a bug or is better to import ObjectType from hubspot/crm/object_type.py?

hubspot/crm/object_type.py has gone too! It seems a bug.

Custom Object does not have get_all method

There is currently no way to get all records for a custom object, the get_all method is missing. Is that intentional?

Can this be added to discovery/crm/objects/discovery.py?

    def get_all(self, **kwargs):
        return fetch_all(self.basic_api, **kwargs)

Files API upload does not seem to use file_name attribute

When trying to upload a PNG file using the files API:

    file = hubspot.files.files.files_api.upload(file=open(image_path, 'rb').read(),
                                                file_name=os.path.basename(image_path),
                                                folder_path='folder',
                                                options=json.dumps({
                                                    "access": "PUBLIC_INDEXABLE",
                                                    "overwrite": True,
                                                    "duplicateValidationStrategy": "RETURN_EXISTING",
                                                    "duplicateValidationScope": "EXACT_FOLDER"
                                                }))

I get a bad request response:

"message":"Could not determine name from file"

While I clearly did specify a file name. I'm using version 3.6.1

release 3.4.0 is missing hubspot.crm.extensions

when installing the release 3.4.0 via pip, from hubspot import HubSpot throws "ModuleNotFoundError: No module named 'hubspot.crm.extensions'"

i took a look into the installed python packages and figured the folder is actually missing

i downgraded to 3.3.0 until the missing package is coming with the pip install

Get All not getting all properties

Hi everyone,

I'm getting all my contacts from Hubspot, but when I look into the properties, there is only basic properties and values. My custom properties, properties that I have created, is not in the object.

Someone knows how to get custom properties as well?

Thanks.
Rodrigo.

ImportError

----> 16 from hubspot import HubSpot

ImportError: cannot import name 'HubSpot' from 'hubspot'

Hubspot Filemanager Api

Hello, I've started using this package for my project (Thanks BTW).
And I'm wondering if Hubspot Filemanager api is available in this package ?
I can't find any example in Readme nor in the sample-apps directory.

Thank you !

How to submit parameters to get_page_with_http_info method

hi there,

Is there a way to get all contacts and provide parameters listed on the API - https://legacydocs.hubspot.com/docs/methods/contacts/get_contacts ?

I'm currently using this:

client = HubSpot(api_key=self.API_KEY)
all_contacts = client.crm.contacts.get_all()

Which I think calls the get_page_with_http_info method here: hubspot-api-python/hubspot/crm/contacts/api/basic_api.py . In that documentation, I only see properties and associations as lists, but can't control...

  • Property Mode | &propertyMode=x
  • Form Submission Mode | &formSubmissionMode=x
  • List Memberships | &showListMemberships=x
    ...as listed in the documentation.

Is that correct? I'm trying to loosely get 'all the information about all the contacts' or as close to that as possible. Is there currently a way to do that or no?

thanks!
Chris

api key issue

Hello, I developed a get request for some data from my companies HubSpot page. It works fine in one environment, but when trying to run the exact same code in another environment I get the following error (You must include a hapi_key or access_token attribute when initalizing the API).
code below. I have already checked the python versions and additional libraries (simplejson, delorean), it's not those. I have no idea what is causing this. Any ideas?
from hubspot import HubSpot
api_client = HubSpot(api_key= 'my key')

Unable to limit number of pulled records

I'm trying to pass the limit argument into the crm.contacts.get_all() function:

from hubspot import HubSpot
api_client = HubSpot(api_key=api_key)
contacts = api_client.crm.contacts.get_all(limit = 10)

However, this leads to the following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-32b78f179dda> in <module>
      1 from hubspot import HubSpot
      2 api_client = HubSpot(api_key=api_key)
----> 3 contacts = api_client.crm.contacts.get_all(limit = 10)
      4 #print(len(contacts))

~\anaconda3\lib\site-packages\hubspot\discovery\crm\contacts\discovery.py in get_all(self, **kwargs)
     22 
     23     def get_all(self, **kwargs):
---> 24         return fetch_all(self.basic_api, **kwargs)

~\anaconda3\lib\site-packages\hubspot\utils\objects.py in fetch_all(get_page_api_client, **kwargs)
      7 
      8     while True:
----> 9         page = get_page_api_client.get_page(after=after, limit=PAGE_MAX_SIZE, **kwargs)
     10         results.extend(page.results)
     11         if page.paging is None:

TypeError: get_page() got multiple values for keyword argument 'limit'

It seems that the PAGE_MAX_SIZE parameter in hubspot/utils/objects.py is hardcoded at 100 and when the user specifies the limit manually, this leads to the limit argument being duplicated.

Properties Name

Given this example previously,
api_response = client.crm.contacts.get_all(properties=["firstname", "lastname", "email", "address"])

is there a list of properties and their naming convention to use with this api?

Thank you,
Andrei

get_all doesnt bring details around lead source

Hi,
the contacts.get_all function does indeed bring all contacts however it doesn't take into account two columns in the contacts schema: Lead Status and Lead Source Detail.

Those are two important attributes and i'm not sure how to add them to the get_all function. Is there a way?

Thank you,
Eliano

Invalid JSON error when using an IN filter to get all deals from a number of deal_ids

I am trying to use an IN Filter for getting all deals from a list of deal_ids when trying this I get an invalid JSON error:

HTTP response body: {"status":"error","message":"Invalid input JSON on line 1, column 42: Cannot deserialize instance of `java.lang.String` out of START_ARRAY token","correlationId":"dd4d7def-6cc8-4b7e-a48d-658e0330e8cd"}

My code for getting the deals:

domain_filter = hubspot.crm.deals.models.Filter(
            property_name="id",
            operator="IN",
            value=deal_ids
        )

        filter_group = hubspot.crm.deals.models.FilterGroup(
            filters=[domain_filter]
        )

        public_object_search_request = hubspot.crm.companies.models.PublicObjectSearchRequest(
            filter_groups=[filter_group]
        )
        
        deal_results = self.hubspot_api_client.crm.companies.search_api.do_search(public_object_search_request=public_object_search_request)

This is what the dict repr of public_object_search_request looks like:

{'after': None,
 'filter_groups': [{'filters': [{'operator': 'IN',
                                 'property_name': 'id',
                                 'value': ['3651752129', '3741754830']}]}],
 'limit': None,
 'properties': None,
 'query': None,
 'sorts': None}

Subscription API - hubspot.communication_preferences.subscribe path does not exist

The path:

from hubspot.communication_preferences.subscribe import PublicUpdateSubscriptionStatusRequest, ApiException

mentioned in the tutorial below:
https://developers.hubspot.com/docs/api/marketing-api/subscriptions-preferences
does not exist. Is it a bug or this refers to some unreleased change?
It would be great if the code published in the official Hubspot webpages would be in sync with latest package version (there's a similar issue with the GDPR deletion endpoint).

Using get_all and a filter on contacts

Is there a way to use a filter such as

   server_filter = Filter(
        property_name="server",
        operator="EQ",
        value=
    )
    public_object_search_request = PublicObjectSearchRequest(
        filter_groups=[filter_group],
        properties=properties,
    )

and do something like:

 contacts_result = hubspot_api.crm.contacts.search_api.do_search(
            public_object_search_request=public_object_search_request,
        ).get_all()

or

hubspot_api.crm.contacts.get_all(filter=server_filter)

having 3k+ contacts makes it so that I sometimes trigger the secondly limit when using a while loop and the after param etc

Batch retrieving V1 models and initializing V3 objects?

How can I initialize V3 contact object models from the V1 API? (That's awesome that V1 will be supported but it seems the responses are incompatible with V3 responses.)

This doesn't seem to work or be the correct way to do it:

    from hubspot.crm.contacts import SimplePublicObject, CollectionResponseSimplePublicObject

    url = "https://api.hubspot.com/contacts/v1/contact/emails/batch/"
    emails = list(map(lambda registrant: registrant.email, group_of_100_registrants))
    params = {
        "hapikey": settings.HUBSPOT_API_KEY,
        "formSubmissionMode": "none",
        "email": emails,
        "property": "my_custom_property_to_check_if_contact_needs_update",
    }
    response = requests.get(
        url, params=params, timeout=settings.HUBSPOT_REQUEST_TIMEOUT
    )
    contacts = CollectionResponseSimplePublicObject(response.json())

And even if there's only one contact in my response, this doesn't work either (it sets the id to a dictionary of properties):

    contact = SimplePublicObject(response.json()['12345'])

Why: I need to retrieve a batch of contacts so I can determine which ones need to be updated via a custom field that is set by my external integration script each time it is run.

With the V3 API, I can only search on three filters at once, meaning going through a list of 3,000 contacts would cost 1,000 API calls.

With the V1 API (https://api.hubspot.com/contacts/v1/contact/emails/batch/), I can request 100 at a time, which is much more reasonable.

I can get the JSON back using Python requests just fine.

But how do I get these into the V3 contact models so I can do something with them and then batch-update them through this newer V3 API ... if possible?*

v3 contact properties history, form submissions and list memberships

Hi

I'm wondering if I can retrieve the custom property history for a contact.
The v1 allow that in multiple ways, the one I was using was getting a batch of contacts by id .

Also I was getting the form submission and listing the memberships, the params I was using:

propertyMode=value_and_history
formSubmissionMode=all
showListMemberships=true

But reading the v3 documentation looks that properties historic is not returned anymore.
Is that feature available? If not, that behavior will be ported to v3 in the future?

Also I want to know if possible when will be dropped the v1 contacts endpoint, if is planned to be dropped.

Thanks.

JSON serialize contacts.get_all output

Hi,

Is there a convenient way to JSON serialize the output from the hubspot.crm.contacts.get_all API? The updated_at and created_at dates are in datetime format by default, however interestingly enough the hs_analytics_last_timestamp property is already converted to string. I wish they were all strings.

Anyway, is there a way to convert from the SimplePublicObject object?

Please mention proper redirect_uri to be configured in the Hubspot App for all the example sample app in their README.md files

There were no mention how would we configure the redirect_uri for any app given in the sample-apps. I was trying with http://localhost:300. Many hubspot node examples have the pattern as http://localhost:3000/oauth-callback.

But the sample apps firstly works with only port = 5000 as the docker file named web runs on 5000 according to the docker-compose.yml file.
Also, the redirect_uri in the app should be specifically "http://localhost:5000/oauth/callback" for this python module sample apps. Would be really helpful for the developers who is a starter like me both in Webapps and Hubspot if this information is mentioned in the README.md file

Current build (3.6.0) unimportable

After installing the latest version of the hubspot api client (3.6.0) the hubspot package can no longer be imported.

Reproduced here within the current python:latest docker image:

root@b24251133b8c:/# pip3 install hubspot-api-client
Collecting hubspot-api-client
  Downloading hubspot_api_client-3.6.0-py3-none-any.whl (1.7 MB)
     |████████████████████████████████| 1.7 MB 4.3 MB/s
Collecting python-dateutil
  Downloading python_dateutil-2.8.1-py2.py3-none-any.whl (227 kB)
     |████████████████████████████████| 227 kB 12.6 MB/s
Collecting certifi
  Downloading certifi-2020.12.5-py2.py3-none-any.whl (147 kB)
     |████████████████████████████████| 147 kB 7.3 MB/s
Collecting urllib3>=1.15
  Downloading urllib3-1.26.3-py2.py3-none-any.whl (137 kB)
     |████████████████████████████████| 137 kB 9.3 MB/s
Collecting six>=1.10
  Downloading six-1.15.0-py2.py3-none-any.whl (10 kB)
Installing collected packages: six, urllib3, python-dateutil, certifi, hubspot-api-client
Successfully installed certifi-2020.12.5 hubspot-api-client-3.6.0 python-dateutil-2.8.1 six-1.15.0 urllib3-1.26.3
root@b24251133b8c:/# python3
Python 3.9.1 (default, Jan 12 2021, 16:45:25)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import hubspot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.9/site-packages/hubspot/__init__.py", line 1, in <module>
    from .client import Client
  File "/usr/local/lib/python3.9/site-packages/hubspot/client.py", line 6, in <module>
    from .discovery.files.discovery import Discovery as FilesDiscovery
  File "/usr/local/lib/python3.9/site-packages/hubspot/discovery/files/discovery.py", line 2, in <module>
    from .files.discovery import Discovery as FilesDiscovery
  File "/usr/local/lib/python3.9/site-packages/hubspot/discovery/files/files/discovery.py", line 1, in <module>
    import hubspot.files.files as api_client
ModuleNotFoundError: No module named 'hubspot.files'
>>>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.