### Install hubspot-api-client Source: https://github.com/hubspot/hubspot-api-python/blob/master/README.md Installs or upgrades the HubSpot API Python client package. Ensure Python 3.7+ and pip are installed. ```bash pip install --upgrade hubspot-api-client ``` -------------------------------- ### GET Request Example with HubSpot Python Source: https://github.com/hubspot/hubspot-api-python/blob/master/README.md This example demonstrates how to perform a GET request to retrieve contacts using the HubSpot Python API. ```python 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) ``` -------------------------------- ### POST Request Example with HubSpot Python Source: https://github.com/hubspot/hubspot-api-python/blob/master/README.md This example shows how to perform a POST request to create a contact using the HubSpot Python API. ```python 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) ``` -------------------------------- ### Create Contact (Python) Source: https://context7.com/hubspot/hubspot-api-python/llms.txt Shows how to create a new contact in HubSpot CRM using properties like email, firstname, lastname, phone, company, and website. This example also demonstrates exception handling for API errors. ```python from hubspot import HubSpot from hubspot.crm.contacts import SimplePublicObjectInputForCreate from hubspot.crm.contacts.exceptions import ApiException client = HubSpot(access_token='your_token') try: contact_input = SimplePublicObjectInputForCreate( properties={ "email": "john.doe@example.com", "firstname": "John", "lastname": "Doe", "phone": "555-1234", "company": "Example Corp", "website": "https://example.com" } ) new_contact = client.crm.contacts.basic_api.create( simple_public_object_input_for_create=contact_input ) print(f"Contact created with ID: {new_contact.id}") print(f"Email: {new_contact.properties['email']}") print(f"Created at: {new_contact.created_at}") except ApiException as e: print(f"Exception when creating contact: {e}") print(f"Status: {e.status}, Reason: {e.reason}") ``` -------------------------------- ### Handle OAuth Tokens in HubSpot Python Source: https://context7.com/hubspot/hubspot-api-python/llms.txt Shows complete OAuth token lifecycle management including authorization URL generation, token exchange, refresh, and revocation. Requires OAuth client credentials and callback URL setup. ```python from hubspot import HubSpot from hubspot.oauth.exceptions import ApiException from hubspot.utils.oauth import get_auth_url # Generate authorization URL auth_url = get_auth_url( scope=('contacts', 'crm.objects.contacts.read', 'crm.objects.contacts.write'), optional_scope=('crm.objects.companies.write',), client_id='your_client_id', redirect_uri='http://localhost:8080/oauth-callback', state='random_state_string' ) print(f"Redirect user to: {auth_url}") # After user authorizes, exchange code for tokens client = HubSpot() try: tokens = client.oauth.tokens_api.create( grant_type="authorization_code", redirect_uri='http://localhost:8080/oauth-callback', client_id='your_client_id', client_secret='your_client_secret', code='authorization_code_from_callback' ) print(f"Access token: {tokens.access_token}") print(f"Refresh token: {tokens.refresh_token}") print(f"Expires in: {tokens.expires_in} seconds") # Use access token client.access_token = tokens.access_token # Refresh token new_tokens = client.oauth.tokens_api.create( grant_type="refresh_token", redirect_uri='http://localhost:8080/oauth-callback', client_id='your_client_id', client_secret='your_client_secret', refresh_token=tokens.refresh_token ) print(f"New access token: {new_tokens.access_token}") # Get token info token_info = client.oauth.access_tokens_api.get(tokens.access_token) print(f"Token expires at: {token_info.expires_at}") print(f"Scopes: {token_info.scopes}") # Archive refresh token (revoke) client.oauth.refresh_tokens_api.archive(tokens.refresh_token) print("Refresh token revoked") except ApiException as e: print(f"OAuth error: {e}") ``` -------------------------------- ### Interact with CRM Custom Objects using HubSpot Python API Source: https://context7.com/hubspot/hubspot-api-python/llms.txt This snippet sets up the HubSpot client and imports necessary classes for working with custom objects, including creation, search, and exception handling. It depends on the HubSpot Python library and a valid access token. Inputs would typically include custom object properties; outputs are custom object instances. Limitations: The example is incomplete and requires additional code for full operations like create or search. ```python from hubspot import HubSpot from hubspot.crm.objects import SimplePublicObjectInputForCreate, PublicObjectSearchRequest from hubspot.crm.objects.exceptions import ApiException client = HubSpot(access_token='your_token') ``` -------------------------------- ### Handle API Exceptions - Python Source: https://context7.com/hubspot/hubspot-api-python/llms.txt Demonstrates comprehensive exception handling for HubSpot API operations. Catches specific exceptions like NotFound, Unauthorized, Forbidden, and includes retry logic for transient failures. Requires hubspot-client-py installed. ```python from hubspot import HubSpot from hubspot.crm.contacts.exceptions import ( ApiException, NotFoundException, UnauthorizedException, ForbiddenException, ServiceException, ApiTypeError, ApiValueError ) client = HubSpot(access_token='your_token') try: # Attempt operation that may fail contact = client.crm.contacts.basic_api.get_by_id('invalid_id') except NotFoundException as e: print(f"Resource not found: {e}") print(f"Status: {e.status}") print(f"Reason: {e.reason}") except UnauthorizedException as e: print(f"Authentication failed: {e}") print("Check your access token") print(f"Body: {e.body}") except ForbiddenException as e: print(f"Access forbidden: {e}") print("You may not have the required scopes") except ServiceException as e: print(f"Server error: {e}") print(f"Status: {e.status}") print("Try again later") except ApiTypeError as e: print(f"Type error: {e}") print("Check parameter types") except ApiValueError as e: print(f"Value error: {e}") print("Check parameter values") except ApiException as e: # Generic catch-all print(f"API Exception: {e}") print(f"Status: {e.status}") print(f"Reason: {e.reason}") print(f"Body: {e.body}") print(f"Headers: {e.headers}") # With retry logic from urllib3.util.retry import Retry retry = Retry( total=3, backoff_factor=0.5, status_forcelist=(429, 500, 502, 503, 504), allowed_methods=["GET", "POST", "PUT", "PATCH", "DELETE"] ) robust_client = HubSpot(access_token='your_token', retry=retry) try: # This will automatically retry on failures contact = robust_client.crm.contacts.basic_api.get_by_id('123') except ApiException as e: print(f"Failed after retries: {e}") ``` -------------------------------- ### Create and Manage CRM Associations with HubSpot Python API Source: https://context7.com/hubspot/hubspot-api-python/llms.txt This example creates a contact with an association to a company; separately creates batch associations between contacts, companies, and deals using the v4 API; and retrieves associations for an object. It relies on the HubSpot Python library, access token, and predefined association types. Inputs are object IDs and association types; outputs include created contact IDs and association results. Limitations: Requires knowledge of association type IDs and handles general exceptions. ```python from hubspot import HubSpot from hubspot.crm.contacts import SimplePublicObjectInputForCreate, PublicAssociationsForObject from hubspot.crm.association_type import AssociationType from hubspot.crm.associations.v4 import BatchInputPublicAssociationMultiPost client = HubSpot(access_token='your_token') try: # Create contact with company association contact_input = SimplePublicObjectInputForCreate( properties={ "email": "employee@example.com", "firstname": "Jane", "lastname": "Smith" }, associations=[ PublicAssociationsForObject( to={"id": "company_123"}, types=[{ "associationCategory": "HUBSPOT_DEFINED", "associationTypeId": AssociationType.CONTACT_TO_COMPANY.value }] ) ] ) contact = client.crm.contacts.basic_api.create(contact_input) print(f"Created contact with company association: {contact.id}") # Create association separately using v4 API association_input = BatchInputPublicAssociationMultiPost( inputs=[ { "from": {"id": "contact_456"}, "to": {"id": "deal_789"}, "types": [{ "associationCategory": "HUBSPOT_DEFINED", "associationTypeId": 4 # CONTACT_TO_DEAL }] }, { "from": {"id": "company_123"}, "to": {"id": "deal_789"}, "types": [{ "associationCategory": "HUBSPOT_DEFINED", "associationTypeId": 6 # COMPANY_TO_DEAL }] } ] ) result = client.crm.associations.v4.batch_api.create( from_object_type="contacts", to_object_type="deals", batch_input_public_association_multi_post=association_input ) print(f"Created {len(result.results)} associations") # Get associations associations = client.crm.associations.v4.basic_api.get_page( object_type="contacts", object_id="contact_456", to_object_type="deals" ) print(f"Found {len(associations.results)} associated deals") except Exception as e: print(f"Association error: {e}") ``` -------------------------------- ### Search HubSpot CRM contacts with filters (Python) Source: https://context7.com/hubspot/hubspot-api-python/llms.txt Demonstrates searching HubSpot contacts using filter groups, sorting, and property selection. Shows two examples: searching by email domain and searching by modification date with multiple filters. Requires HubSpot API client and access token. ```python from hubspot import HubSpot from hubspot.crm.contacts import PublicObjectSearchRequest from hubspot.crm.contacts.exceptions import ApiException from dateutil import parser client = HubSpot(access_token='your_token') try: # Search by email domain search_request = PublicObjectSearchRequest( filter_groups=[ { "filters": [ { "propertyName": "email", "operator": "CONTAINS", "value": "@example.com" } ] } ], sorts=["createdate"], properties=["email", "firstname", "lastname", "company"], limit=50, after=0 ) results = client.crm.contacts.search_api.do_search( public_object_search_request=search_request ) print(f"Found {len(results.results)} contacts") for contact in results.results: print(f"- {contact.properties['email']}: {contact.properties.get('firstname')} {contact.properties.get('lastname')}") # Search by date with multiple filters date_ms = str(int(parser.isoparse("2024-01-01T00:00:00.000Z").timestamp() * 1000)) date_search = PublicObjectSearchRequest( filter_groups=[ { "filters": [ { "propertyName": "lastmodifieddate", "operator": "GTE", "value": date_ms }, { "propertyName": "email", "operator": "HAS_PROPERTY" } ] } ], limit=100 ) recent_contacts = client.crm.contacts.search_api.do_search(date_search) print(f"Found {len(recent_contacts.results)} contacts modified since 2024-01-01") except ApiException as e: print(f"Exception when searching: {e}") ``` -------------------------------- ### Get Contact by ID (Python) Source: https://context7.com/hubspot/hubspot-api-python/llms.txt Illustrates how to retrieve a contact by its ID, specifying properties and associations to fetch. This also includes exception handling for not found and API errors. ```python from hubspot import HubSpot from hubspot.crm.contacts.exceptions import ApiException, NotFoundException client = HubSpot(access_token='your_token') try: contact = client.crm.contacts.basic_api.get_by_id( contact_id='12345', properties=['email', 'firstname', 'lastname', 'phone', 'company'], associations=['companies', 'deals'] ) print(f"Contact ID: {contact.id}") print(f"Name: {contact.properties.get('firstname')} {contact.properties.get('lastname')}") print(f"Email: {contact.properties.get('email')}") print(f"Last updated: {contact.updated_at}") # Convert to dictionary contact_dict = contact.to_dict() print(f"Full contact data: {contact_dict}") except NotFoundException as e: print(f"Contact not found: {e}") except ApiException as e: print(f"API error: {e}") ``` -------------------------------- ### Get HubSpot CMS Audit Logs Source: https://github.com/hubspot/hubspot-api-python/blob/master/README.md Fetches a page of audit logs from the HubSpot CMS. Includes error handling for potential API exceptions. ```python 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) ``` -------------------------------- ### HubSpot Files API: Upload, Manage Files, and Folders in Python Source: https://context7.com/hubspot/hubspot-api-python/llms.txt Uploads files to HubSpot, creates folders, retrieves file information by ID, searches for files, and gets folder details by path using the HubSpot Python client. Requires a HubSpot access token and a valid file path. ```python from hubspot import HubSpot from hubspot.files.exceptions import ApiException import json from pprint import pprint client = HubSpot(access_token='your_token') try: # Upload file options = json.dumps({ 'access': 'PRIVATE', 'overwrite': False, 'duplicateValidationStrategy': 'NONE', 'duplicateValidationScope': 'ENTIRE_PORTAL' }) response = client.files.files_api.upload( file="/path/to/document.pdf", file_name="important_document", folder_path="/marketing/resources", options=options ) print(f"File uploaded successfully!") print(f"File ID: {response.id}") print(f"URL: {response.url}") print(f"Size: {response.size} bytes") # Create folder folder = client.files.folders_api.create( name="New Campaign Folder", parent_path="/marketing" ) print(f"Created folder: {folder.path}") # Get file by ID file_info = client.files.files_api.get_by_id(response.id) pprint(file_info.to_dict()) # Search files files = client.files.files_api.search() print(f"Total files: {len(files.results)}") # Get folder by path folder_info = client.files.folders_api.get_by_path("/marketing/resources") print(f"Folder ID: {folder_info.id}") except ApiException as e: print(f"File operation error: {e}") ``` -------------------------------- ### GET /oauth/v1/access-tokens/{token} Source: https://context7.com/hubspot/hubspot-api-python/llms.txt Retrieves information about an access token including its expiration time and granted scopes. ```APIDOC ## GET /oauth/v1/access-tokens/{token} ### Description Retrieves information about an access token including expiration time and granted scopes. ### Method GET ### Endpoint /oauth/v1/access-tokens/{token} #### Path Parameters - **token** (string) - Required - The access token to retrieve information for ### Request Example ``` GET /oauth/v1/access-tokens/access_token_value ``` ### Response #### Success Response (200) - **expires_at** (integer) - Unix timestamp when the token expires - **scopes** (array) - Array of scopes granted to the token #### Response Example { "expires_at": 1705305600, "scopes": [ "contacts", "crm.objects.contacts.read", "crm.objects.contacts.write" ] } ``` -------------------------------- ### GET /crm/v3/objects/{objectType} Source: https://context7.com/hubspot/hubspot-api-python/llms.txt Retrieves all custom objects of a specified type. Allows specifying which properties to include in the response. ```APIDOC ## GET /crm/v3/objects/{objectType} ### Description Retrieves all custom objects of a specified type with optional property filtering. ### Method GET ### Endpoint /crm/v3/objects/{objectType} #### Path Parameters - **objectType** (string) - Required - The ID of the custom object type #### Query Parameters - **properties** (array) - Optional - List of specific properties to retrieve ### Request Example ``` GET /crm/v3/objects/2-12345678?properties=custom_property_1,custom_property_2 ``` ### Response #### Success Response (200) - **results** (array) - Array of all objects of the specified type #### Response Example { "results": [ { "id": "12345", "properties": { "custom_property_1": "Value 1", "custom_property_2": "Value 2" } } ] } ``` -------------------------------- ### Get OAuth URL with HubSpot Python Source: https://github.com/hubspot/hubspot-api-python/blob/master/README.md This snippet demonstrates how to retrieve the OAuth URL for authenticating with HubSpot using the `get_auth_url` utility function. ```python from hubspot.utils.oauth import get_auth_url auth_url = get_auth_url( scope=('contacts', ), client_id='client_id', redirect_uri='http://localhost' ) ``` -------------------------------- ### GET /crm/v3/objects/{objectType}/{objectId} Source: https://context7.com/hubspot/hubspot-api-python/llms.txt Retrieves a specific custom object by its ID. Allows specifying which properties to include in the response. ```APIDOC ## GET /crm/v3/objects/{objectType}/{objectId} ### Description Retrieves a specific custom object by its ID, with optional property filtering. ### Method GET ### Endpoint /crm/v3/objects/{objectType}/{objectId} #### Path Parameters - **objectType** (string) - Required - The ID of the custom object type - **objectId** (string) - Required - The ID of the specific object #### Query Parameters - **properties** (array) - Optional - List of specific properties to retrieve ### Request Example ``` GET /crm/v3/objects/2-12345678/12345?properties=custom_property_1,custom_property_2 ``` ### Response #### Success Response (200) - **id** (string) - The ID of the object - **properties** (object) - The requested properties of the object #### Response Example { "id": "12345", "properties": { "custom_property_1": "Value 1", "custom_property_2": "Value 2" } } ``` -------------------------------- ### Get HubSpot Custom Object Page Source: https://github.com/hubspot/hubspot-api-python/blob/master/README.md Fetches a paginated list of custom objects from HubSpot CRM, specifying the object type. Includes error handling for API exceptions. ```python 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 HubSpot CRM Contacts Source: https://github.com/hubspot/hubspot-api-python/blob/master/README.md Retrieves all contacts from HubSpot CRM. This method utilizes pagination internally to fetch all results. No explicit error handling shown. ```python all_contacts = api_client.crm.contacts.get_all() ``` -------------------------------- ### Get HubSpot CRM Contact by ID Source: https://github.com/hubspot/hubspot-api-python/blob/master/README.md Retrieves a specific contact from HubSpot CRM using its unique ID. Includes error handling for API exceptions. ```python 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) ``` -------------------------------- ### Performing Direct API Requests for CRM Contacts in Python Source: https://context7.com/hubspot/hubspot-api-python/llms.txt This code shows how to use the api_request method for direct calls to unwrapped HubSpot endpoints, covering GET, POST, PATCH, and DELETE operations on contacts. It requires the HubSpot client with access token; inputs include path, method, query/body parameters, and optional headers; outputs are JSON responses with contact data; limitations apply to endpoints not covered by SDK wrappers and require proper authentication. ```python from hubspot import HubSpot from hubspot.crm.contacts.exceptions import ApiException client = HubSpot(access_token='your_token') try: # GET request response = client.api_request({ "path": "/crm/v3/objects/contacts", "method": "GET", "query": { "limit": 10, "properties": "email,firstname" } }) data = response.json() print(f"Retrieved {len(data['results'])} contacts") # POST request response = client.api_request({ "path": "/crm/v3/objects/contacts", "method": "POST", "body": { "properties": { "email": "direct@example.com", "firstname": "Direct", "lastname": "API" } } }) contact_data = response.json() print(f"Created contact: {contact_data['id']}") # PUT request response = client.api_request({ "path": f"/crm/v3/objects/contacts/{contact_data['id']}", "method": "PATCH", "body": { "properties": { "phone": "555-0000" } } }) updated = response.json() print(f"Updated contact phone: {updated['properties']['phone']}") # DELETE request response = client.api_request({ "path": f"/crm/v3/objects/contacts/{contact_data['id']}", "method": "DELETE" }) print(f"Deleted contact, status: {response.status_code}") # Custom headers response = client.api_request({ "path": "/crm/v3/objects/contacts", "headers": { "X-Custom-Header": "custom-value" } }) except ApiException as e: print(f"API request error: {e}") ``` -------------------------------- ### Initialize HubSpot Client (Python) Source: https://context7.com/hubspot/hubspot-api-python/llms.txt Demonstrates how to initialize the HubSpot client with an access token for authentication, including options for lazy loading and retry configurations. This client is the entry point for interacting with HubSpot APIs. ```python from hubspot import HubSpot from urllib3.util.retry import Retry # Basic initialization api_client = HubSpot(access_token='your_access_token') # Initialize without token, set later api_client = HubSpot() api_client.access_token = 'your_access_token' # Alternative using Client.create() from hubspot import Client client = Client.create(access_token='your_access_token') # With retry configuration for rate limits retry = Retry( total=5, backoff_factor=0.3, status_forcelist=(429, 500, 502, 504) ) api_client = HubSpot(access_token='your_token', retry=retry) ``` -------------------------------- ### Managing Webhooks Subscriptions and Handling Events in Python Source: https://context7.com/hubspot/hubspot-api-python/llms.txt This snippet demonstrates creating webhook subscriptions for events like contact creation, retrieving existing subscriptions, and configuring webhook settings using the HubSpot SDK. It also includes a Flask endpoint to handle incoming webhooks with signature validation for security. Dependencies include hubspot, flask, and hubspot.utils.signature; inputs are app_id and subscription details, outputs are subscription objects and event data; limitations include requiring valid access tokens and client secrets. ```python from hubspot import HubSpot from hubspot.webhooks.exceptions import ApiException from hubspot.utils.signature import Signature from flask import Flask, request client = HubSpot(access_token='your_token') try: # Create webhook subscription subscription = client.webhooks.subscriptions_api.create( app_id=12345, body={ "event_type": "contact.creation", "property_name": "email", "active": True } ) print(f"Created subscription: {subscription.id}") # Get all subscriptions subscriptions = client.webhooks.subscriptions_api.get_all(app_id=12345) print(f"Total subscriptions: {len(subscriptions.results)}") for sub in subscriptions.results: print(f"- {sub.event_type}: {sub.id}") # Configure webhook settings settings = client.webhooks.settings_api.configure( app_id=12345, body={ "target_url": "https://example.com/webhook", "throttling": { "period": "SECONDLY", "max_concurrent_requests": 10 } } ) print(f"Webhook URL: {settings.target_url}") except ApiException as e: print(f"Webhooks error: {e}") # Webhook endpoint with signature validation app = Flask(__name__) @app.route('/webhook', methods=['POST']) def handle_webhook(): # Validate signature is_valid = Signature.is_valid( signature=request.headers.get("X-HubSpot-Signature"), client_secret="your_client_secret", request_body=request.data.decode("utf-8"), http_uri=request.base_url, signature_version=request.headers.get("X-HubSpot-Signature-Version", "v2"), timestamp=request.headers.get("X-HubSpot-Request-Timestamp") ) if not is_valid: return "Invalid signature", 401 payload = request.json print(f"Received webhook: {payload['subscriptionType']}") for event in payload.get('events', []): print(f"Object ID: {event['objectId']}") print(f"Event: {event['eventId']}") return "OK", 200 ``` -------------------------------- ### Configure HubSpot Client in Python Source: https://github.com/hubspot/hubspot-api-python/blob/master/README.md Initializes the HubSpot client using an access token. The token can be provided during instantiation or set later. Requires a HubSpot private app or OAuth2 access token. ```python 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' ``` -------------------------------- ### Manage HubSpot CRM Pipelines in Python Source: https://context7.com/hubspot/hubspot-api-python/llms.txt This Python code snippet demonstrates how to retrieve, create, and audit deal pipelines using the HubSpot Python SDK. It requires the 'hubspot' library and a valid access token for authentication. The code fetches all pipelines, creates a new one with custom stages, and retrieves audit logs, handling potential API exceptions. ```python from hubspot import HubSpot from hubspot.crm.pipelines.exceptions import ApiException client = HubSpot(access_token='your_token') try: # Get all deal pipelines pipelines = client.crm.pipelines.pipelines_api.get_all( object_type="deals" ) print(f"Found {len(pipelines.results)} pipelines") for pipeline in pipelines.results: print(f"\nPipeline: {pipeline.label} (ID: {pipeline.id})") print(f"Stages: {len(pipeline.stages)}") for stage in pipeline.stages: print(f" - {stage.label} ({stage.display_order})") print(f" Probability: {stage.metadata.get('probability', 'N/A')} %") # Create new pipeline new_pipeline = client.crm.pipelines.pipelines_api.create( object_type="deals", body={ "label": "Enterprise Sales", "display_order": 3, "stages": [ { "label": "Initial Contact", "display_order": 0, "metadata": {"probability": "0.1"} }, { "label": "Qualified", "display_order": 1, "metadata": {"probability": "0.3"} }, { "label": "Proposal Sent", "display_order": 2, "metadata": {"probability": "0.6"} }, { "label": "Closed Won", "display_order": 3, "metadata": {"probability": "1.0", "isClosed": True} } ] } ) print(f"\nCreated pipeline: {new_pipeline.id}") # Get pipeline audit logs audits = client.crm.pipelines.pipeline_audits_api.get_page( object_type="deals" ) print(f"Found {len(audits.results)} audit entries") except ApiException as e: print(f"Pipelines error: {e}") ``` -------------------------------- ### Manage CRM Deals with HubSpot Python API Source: https://context7.com/hubspot/hubspot-api-python/llms.txt This snippet creates a new deal with properties like name, amount, close date, stage, and pipeline; updates the deal's stage and amount; and retrieves all deals with specified properties. It depends on the HubSpot Python library and a valid access token. Inputs include deal properties as dictionaries; outputs are deal objects with IDs and properties. Limitations include API rate limits and requirement for proper error handling via ApiException. ```python from hubspot import HubSpot from hubspot.crm.deals import SimplePublicObjectInputForCreate, SimplePublicObjectInput from hubspot.crm.deals.exceptions import ApiException client = HubSpot(access_token='your_token') try: # Create deal deal_input = SimplePublicObjectInputForCreate( properties={ "dealname": "New Enterprise Deal", "amount": "50000", "closedate": "2024-12-31", "dealstage": "appointmentscheduled", "pipeline": "default" } ) new_deal = client.crm.deals.basic_api.create(deal_input) print(f"Created deal: {new_deal.id}") print(f"Deal name: {new_deal.properties['dealname']}") print(f"Amount: ${new_deal.properties['amount']}") # Update deal update_input = SimplePublicObjectInput( properties={ "dealstage": "qualifiedtobuy", "amount": "75000" } ) updated_deal = client.crm.deals.basic_api.update(new_deal.id, update_input) print(f"Updated deal amount to: ${updated_deal.properties['amount']}") # Get all deals all_deals = client.crm.deals.get_all( properties=['dealname', 'amount', 'dealstage', 'closedate'] ) for deal in all_deals: print(f"- {deal.properties['dealname']}: ${deal.properties.get('amount', '0')}") except ApiException as e: print(f"Deal operation error: {e}") ``` -------------------------------- ### Manage CRM Properties - Python Source: https://context7.com/hubspot/hubspot-api-python/llms.txt Shows how to list, create, and update custom CRM properties in HubSpot. Includes property group management. Requires hubspot-client-py and proper API scopes. ```python from hubspot import HubSpot from hubspot.crm.properties.exceptions import ApiException client = HubSpot(access_token='your_token') try: # Get all contact properties properties = client.crm.properties.core_api.get_all( object_type="contacts", archived=False ) print(f"Found {len(properties.results)} contact properties") for prop in properties.results[:5]: print(f"- {prop.name}: {prop.label} ({prop.type})") # Create custom property new_property = client.crm.properties.core_api.create( object_type="contacts", body={ "name": "custom_score", "label": "Custom Score", "type": "number", "field_type": "number", "group_name": "contactinformation", "description": "Custom scoring field" } ) print(f"Created property: {new_property.name}") # Update property updated = client.crm.properties.core_api.update( object_type="contacts", property_name="custom_score", body={ "label": "Updated Score Label", "description": "Updated description" } ) print(f"Updated property: {updated.label}") # Get property groups groups = client.crm.properties.groups_api.get_all( object_type="contacts" ) print(f"\nProperty groups: {len(groups.results)}") for group in groups.results: print(f"- {group.name}: {group.label}") except ApiException as e: print(f"Properties error: {e}") ``` -------------------------------- ### Manage HubSpot Custom Objects in Python Source: https://context7.com/hubspot/hubspot-api-python/llms.txt Demonstrates CRUD operations for custom objects in HubSpot CRM. Shows object creation, retrieval by ID, search with filters, and bulk fetching. Requires HubSpot API client with proper permissions. ```python custom_object_type = "2-12345678" # Your custom object type ID try: # Create custom object custom_obj_input = SimplePublicObjectInputForCreate( properties={ "custom_property_1": "Value 1", "custom_property_2": "Value 2", "custom_date": "2024-01-15" } ) custom_obj = client.crm.objects.basic_api.create( object_type=custom_object_type, simple_public_object_input_for_create=custom_obj_input ) print(f"Created custom object: {custom_obj.id}") # Get custom object by ID obj = client.crm.objects.basic_api.get_by_id( object_type=custom_object_type, object_id=custom_obj.id, properties=['custom_property_1', 'custom_property_2'] ) print(f"Custom object properties: {obj.properties}") # Search custom objects search_request = PublicObjectSearchRequest( filter_groups=[{ "filters": [{ "propertyName": "custom_property_1", "operator": "EQ", "value": "Value 1" }] }], limit=50 ) results = client.crm.objects.search_api.do_search( object_type=custom_object_type, public_object_search_request=search_request ) print(f"Found {len(results.results)} matching custom objects") # Get all custom objects all_objects = client.crm.objects.get_all( object_type=custom_object_type, properties=['custom_property_1', 'custom_property_2'] ) print(f"Total custom objects: {len(all_objects)}") except ApiException as e: print(f"Custom object error: {e}") ``` -------------------------------- ### CRM Companies Management in Python Source: https://context7.com/hubspot/hubspot-api-python/llms.txt Shows how to create, retrieve, search, and list HubSpot CRM companies using the hubspot-api-python client. Uses SimplePublicObjectInputForCreate and PublicObjectSearchRequest, and includes error handling via ApiException. ```python from hubspot import HubSpot from hubspot.crm.companies import SimplePublicObjectInputForCreate, PublicObjectSearchRequest from hubspot.crm.companies.exceptions import ApiException client = HubSpot(access_token='your_token') try: # Create company company_input = SimplePublicObjectInputForCreate( properties={ "name": "Example Corp", "domain": "example.com", "city": "Boston", "state": "MA", "industry": "Technology", "phone": "555-1000" } ) new_company = client.crm.companies.basic_api.create(company_input) print(f"Created company: {new_company.id}") # Get company by ID company = client.crm.companies.basic_api.get_by_id( company_id=new_company.id, properties=['name', 'domain', 'city'] ) print(f"Company name: {company.properties['name']}") # Search companies by domain search_request = PublicObjectSearchRequest( filter_groups=[{ "filters": [{ "propertyName": "domain", "operator": "EQ", "value": "example.com" }] }], limit=10 ) results = client.crm.companies.search_api.do_search(search_request) print(f"Found {len(results.results)} companies with domain example.com") # Get all companies all_companies = client.crm.companies.get_all( properties=['name', 'domain', 'industry'] ) print(f"Total companies: {len(all_companies)}") except ApiException as e: print(f"Company operation error: {e}") ``` -------------------------------- ### HubSpot CMS Blog Posts: Manage Blog Content in Python Source: https://context7.com/hubspot/hubspot-api-python/llms.txt Fetches a list of blog posts, retrieves a specific blog post by its ID, and lists blog authors using the HubSpot Python client. Requires a HubSpot access token and a valid blog post ID for individual retrieval. ```python from hubspot import HubSpot from hubspot.cms.blogs.blog_posts.exceptions import ApiException client = HubSpot(access_token='your_token') try: # Get all blog posts posts = client.cms.blogs.blog_posts.basic_api.get_page( limit=20, archived=False ) print(f"Found {len(posts.results)} blog posts") for post in posts.results: print(f"- {post.name} (ID: {post.id})") print(f" State: {post.state}") print(f" Created: {post.created}") # Get specific blog post post = client.cms.blogs.blog_posts.basic_api.get_by_id('post_id_123') print(f"\nPost title: {post.name}") print(f"URL: {post.url}") print(f"Author: {post.blog_author_id}") # Get blog authors authors = client.cms.blogs.authors.blog_authors_api.get_page() for author in authors.results: print(f"Author: {author.full_name} ({author.email})") except ApiException as e: print(f"Blog posts error: {e}") ``` -------------------------------- ### HubSpot Marketing Events: Track and Search Events in Python Source: https://context7.com/hubspot/hubspot-api-python/llms.txt Retrieves a list of marketing events and searches for specific events (e.g., webinars) using the HubSpot Python client. Requires a HubSpot access token and constructs search requests based on specified filters. ```python from hubspot import HubSpot from hubspot.marketing.events.exceptions import ApiException client = HubSpot(access_token='your_token') try: # Get marketing events events = client.marketing.events.basic_api.get_page(limit=50) print(f"Found {len(events.results)} marketing events") for event in events.results: print(f"Event: {event.event_name}") print(f"Type: {event.event_type}") print(f"Start: {event.start_date_time}") print(f"Organizer: {event.event_organizer}") print("---") # Search for events from hubspot.marketing.events import PublicObjectSearchRequest search_request = PublicObjectSearchRequest( filter_groups=[ { "filters": [ { "propertyName": "event_type", "operator": "EQ", "value": "WEBINAR" } ] } ] ) webinars = client.marketing.events.search_api.do_search(search_request) print(f"\nFound {len(webinars.results)} webinars") except ApiException as e: print(f"Marketing events error: {e}") ``` -------------------------------- ### POST /oauth/v1/token Source: https://context7.com/hubspot/hubspot-api-python/llms.txt Manages OAuth tokens including creating access tokens from authorization codes and refreshing expired tokens. ```APIDOC ## POST /oauth/v1/token ### Description Creates access tokens from authorization codes and refreshes expired tokens. ### Method POST ### Endpoint /oauth/v1/token #### Request Body - **grant_type** (string) - Required - Either 'authorization_code' or 'refresh_token' - **client_id** (string) - Required - Your application's client ID - **client_secret** (string) - Required - Your application's client secret - **redirect_uri** (string) - Required for authorization_code - Must match the redirect URI used in the authorization request - **code** (string) - Required for authorization_code - The authorization code received from the authorization server - **refresh_token** (string) - Required for refresh_token - The refresh token to use for obtaining a new access token ### Request Example (Authorization Code) { "grant_type": "authorization_code", "client_id": "your_client_id", "client_secret": "your_client_secret", "redirect_uri": "http://localhost:8080/oauth-callback", "code": "authorization_code_from_callback" } ### Request Example (Refresh Token) { "grant_type": "refresh_token", "client_id": "your_client_id", "client_secret": "your_client_secret", "refresh_token": "refresh_token_value" } ### Response #### Success Response (200) - **access_token** (string) - The access token for API requests - **refresh_token** (string) - The refresh token for obtaining new access tokens - **expires_in** (integer) - Number of seconds until the access token expires #### Response Example { "access_token": "access_token_value", "refresh_token": "refresh_token_value", "expires_in": 21600 } ``` -------------------------------- ### Retrieve HubSpot CRM contacts with pagination (Python) Source: https://context7.com/hubspot/hubspot-api-python/llms.txt Shows two approaches to retrieving HubSpot contacts with pagination: automatic pagination using get_all() and manual pagination using get_page() for more control. Includes property selection and error handling. ```python from hubspot import HubSpot from hubspot.crm.contacts.exceptions import ApiException client = HubSpot(access_token='your_token') try: # Automatic pagination - fetches all contacts all_contacts = client.crm.contacts.get_all( properties=['email', 'firstname', 'lastname', 'createdate'], limit=500 # Optional: stop after 500 contacts ) print(f"Total contacts retrieved: {len(all_contacts)}") for contact in all_contacts: email = contact.properties.get('email') name = f"{contact.properties.get('firstname', '')} {contact.properties.get('lastname', '')}" print(f"{email}: {name}") # Manual pagination for more control after = None all_results = [] while True: page = client.crm.contacts.basic_api.get_page( limit=100, after=after, properties=['email', 'firstname'] ) all_results.extend(page.results) print(f"Fetched {len(page.results)} contacts") if page.paging is None or page.paging.next is None: break after = page.paging.next.after print(f"Total contacts: {len(all_results)}") except ApiException as e: print(f"Exception when getting contacts: {e}") ``` -------------------------------- ### CRM Contacts Batch Operations in Python Source: https://context7.com/hubspot/hubspot-api-python/llms.txt Demonstrates batch create (up to 100), batch read, batch update, and batch archive (soft delete) for HubSpot CRM contacts using the hubspot-api-python client. Uses BatchInput/BatchRead DTOs and includes try/except error handling. ```python from hubspot import HubSpot from hubspot.crm.contacts import ( BatchInputSimplePublicObjectBatchInputForCreate, BatchInputSimplePublicObjectBatchInput, BatchReadInputSimplePublicObjectId, BatchInputSimplePublicObjectId ) from hubspot.crm.contacts.exceptions import ApiException client = HubSpot(access_token='your_token') try: # Batch create (up to 100 at a time) batch_create = BatchInputSimplePublicObjectBatchInputForCreate( inputs=[ { "properties": { "email": f"user{i}@example.com", "firstname": f"User{i}", "lastname": "Test", "phone": f"555-{i:04d}" } } for i in range(1, 51) ] ) create_result = client.crm.contacts.batch_api.create(batch_create) print(f"Created {len(create_result.results)} contacts") # Collect IDs for subsequent operations contact_ids = [contact.id for contact in create_result.results] # Batch read batch_read = BatchReadInputSimplePublicObjectId( inputs=[{"id": id} for id in contact_ids[:10]], properties=["email", "firstname", "lastname"] ) read_result = client.crm.contacts.batch_api.read(batch_read) print(f"Read {len(read_result.results)} contacts") # Batch update batch_update = BatchInputSimplePublicObjectBatchInput( inputs=[ { "id": contact_ids[i], "properties": {"jobtitle": "Developer"} } for i in range(5) ] ) update_result = client.crm.contacts.batch_api.update(batch_update) print(f"Updated {len(update_result.results)} contacts") # Batch archive (soft delete) batch_archive = BatchInputSimplePublicObjectId( inputs=[{"id": id} for id in contact_ids[:5]] ) client.crm.contacts.batch_api.archive(batch_archive) print("Archived 5 contacts") except ApiException as e: print(f"Batch operation error: {e}") ``` -------------------------------- ### Make Direct API Requests with HubSpot Python Source: https://github.com/hubspot/hubspot-api-python/blob/master/README.md This snippet shows how to make direct API requests with the HubSpot Python client, bypassing wrapped endpoint implementations. It allows for greater flexibility when interacting with HubSpot APIs. ```python client.api_request({ "method": "PUT", "path": "/some/api/not/wrapped/yet", "body": {"key": "value"} }) ``` -------------------------------- ### Configure HTTP Client Retries with HubSpot Python Source: https://github.com/hubspot/hubspot-api-python/blob/master/README.md This snippet demonstrates how to configure HTTP client retries using `urllib3.util.retry.Retry` and pass it to the HubSpot client. ```python 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) ``` -------------------------------- ### Create HubSpot CRM Contact Source: https://github.com/hubspot/hubspot-api-python/blob/master/README.md Creates a new contact in HubSpot CRM with specified properties, such as email. Uses SimplePublicObjectInputForCreate and handles potential API exceptions. ```python 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) ```