HubSpot NodeJS API SDK

repository·master·Indexed 19 days ago

https://github.com/hubspot/hubspot-api-nodejs

A NodeJS SDK for the HubSpot API (v3), providing typed and structured access to HubSpot's CRM, CMS, and other service endpoints. The library includes specialized API interfaces such as BasicApi, BatchApi, and MultiLanguageApi, and supports both Promise-based and Observable-based middleware for intercepting requests and responses.

Tokens
15.4K
Snippets
68
Records
115
Agent score
61%

What's inside @hubspot/api-client

  1. Search CRM Objects

    master

    Use the searchApi.doSearch method to query objects with filters and sorting.

    Constraints:

    • Supports a maximum of 3 FilterGroups, each with a maximum of 3 Filters.
    • Only one sort parameter is supported at a time.
    • For the initial search, after should be set to 0.

    Sorting in JavaScript:

    1. propertyName: Sorts by property in ASCENDING order (e.g., 'hs_object_id').
    2. { propertyName, direction }: Explicit direction (e.g., { propertyName: 'hs_object_id', direction: 'DESCENDING' }).

    Sorting in TypeScript:

    1. ['propertyName']: Sorts in ASCENDING order.
    2. ['-propertyName']: Sorts in DESCENDING order.
    // JS Search Example
    const publicObjectSearchRequest = {
        filterGroups: [{
            filters: [{
                propertyName: 'createdate',
                operator: 'GTE',
                value: `${Date.now() - 30 * 60000}`
            }]
        }],
        sorts: [{ propertyName: 'createdate', direction: 'DESCENDING' }],
        properties: ['createdate', 'firstname', 'lastname'],
        limit: 100,
        after: 0,
    };
    
    const response = await hubspotClient.crm.contacts.searchApi.doSearch(publicObjectSearchRequest);
  2. Handle reserved words in the HubSpot SDK

    master

    The SDK uses generated code that may encounter JavaScript reserved words (e.g., from, in, delete). When an API property name is a reserved word, you must prefix it with an underscore (_) to access it. For example, use _from instead of from.

    const BatchInputPublicAssociation = {
        inputs: [
            {
                _from: {
                    id : 'contactID'
                },
                to: {
                    id: 'companyID'
                },
                type: 'contact_to_company'
            }
        ]
    };
    
    const response = await hubspotClient.crm.associations.batchApi.create(
        'contacts',
        'companies',
        BatchInputPublicAssociation
    );
  3. Instantiate the HubSpot Client

    master

    To use the SDK, create a new instance of the Client class. You can authenticate using an accessToken (from a Private App or OAuth2) or a developerApiKey.

    Common configuration options include:

    • accessToken: Your HubSpot access token.
    • developerApiKey: Your developer API key.
    • basePath: A custom base URL for requests.
    • defaultHeaders: An object of custom headers to include in every request.
    • limiterOptions: Configuration for rate limiting via Bottleneck.
    • numberOfApiCallRetries: Number of retries (0-6) for failed 429 or 5xx requests.
    // CommonJS
    const hubspot = require('@hubspot/api-client');
    const hubspotClient = new hubspot.Client({ accessToken: 'YOUR_ACCESS_TOKEN' });
    
    // ES Modules
    import { Client } from "@hubspot/api-client";
    const hubspotClient = new Client({ accessToken: 'YOUR_ACCESS_TOKEN' });
    
    // With custom headers and base path
    const hubspotClient = new hubspot.Client({
        accessToken: 'YOUR_ACCESS_TOKEN',
        basePath: 'https://some-url',
        defaultHeaders: { 'My-header': 'test-example' }
    });
  4. Create, Associate, and Batch Update CRM Objects

    master

    The SDK provides high-level wrappers for CRM operations. All methods return a Promise.

    Create and Associate Objects: To create a Contact and a Company and then link them using Association v4:

    const contactObj = { properties: { firstname: 'John', lastname: 'Doe' } };
    const companyObj = { properties: { domain: 'example.com', name: 'Example Corp' } };
    
    const createContactResponse = await hubspotClient.crm.contacts.basicApi.create(contactObj);
    const createCompanyResponse = await hubspotClient.crm.companies.basicApi.create(companyObj);
    
    await hubspotClient.crm.associations.v4.basicApi.create(
        'companies',
        createCompanyResponse.id,
        'contacts',
        createContactResponse.id,
        [{ "associationCategory": "HUBSPOT_DEFINED", "associationTypeId": AssociationTypes.companyToContact }]
    );

    Batch Update: Use batchApi.update to update multiple objects of the same type in a single call.

    const dealObj = { id: '123', properties: { amount: 100 } };
    const dealObj2 = { id: '456', properties: { amount: 200 } };
    
    await hubspotClient.crm.deals.batchApi.update({ inputs: [dealObj, dealObj2] });
    // Example: Batch Update
    const dealObj = { id: 'yourId', properties: { amount: 'yourValue' } };
    const dealObj2 = { id: 'yourId2', properties: { amount: 'yourValue2' } };
    await hubspotClient.crm.deals.batchApi.update({ inputs: [dealObj, dealObj2] });
  5. Use the HubSpot SDK in TypeScript

    master

    To use the HubSpot SDK in a TypeScript project, import the client package and instantiate the Client class using your credentials.

    import * as hubspot from '@hubspot/api-client'
    const hubspotClient = new hubspot.Client({ 
        accessToken: YOUR_ACCESS_TOKEN, 
        developerApiKey: YOUR_DEVELOPER_API_KEY 
    })
  6. Use Middleware with the CMS Audit Logs API

    master

    The API supports middleware for intercepting requests and responses. Depending on your implementation, you can use:

    • Middleware (aliased from PromiseMiddleware): For Promise-based interception.
    • ObservableMiddleware (aliased from Middleware): For RxJS-style observable interception.
    import type { Middleware, ObservableMiddleware } from './middleware';
  7. Use different API operation modes (Basic, Batch, Search)

    master

    The Tasks API provides three distinct interface types depending on your use case:

    • BasicApi: For standard single-resource operations (e.g., creating or retrieving a single task).
    • BatchApi: For performing operations on multiple objects in a single request to improve efficiency.
    • SearchApi: For performing complex queries against the Tasks collection using search parameters.
  8. Use different API styles: BasicApi, BatchApi, and SearchApi

    master

    The SDK provides different API interfaces depending on the interaction pattern required:

    • BasicApi: For standard single-resource operations.
    • BatchApi: For performing operations on multiple objects at once (batch mode).
    • SearchApi: For performing search queries against CRM objects.

    These are exported via the PromiseBasicApi, PromiseBatchApi, and PromiseSearchApi types.

  9. Implement Middleware for API requests

    master

    The SDK supports middleware to intercept and modify requests or responses. You can use two types of middleware depending on your implementation preference:

    • Middleware (aliased from PromiseMiddleware): For standard Promise-based interception.
    • ObservableMiddleware (aliased from Middleware): For implementations using Observables.
  10. Configure Rate Limiting and Retries

    master

    The SDK uses Bottleneck for rate limiting. You can control this via limiterOptions during instantiation.

    Default Limiter Options:

    {
        minTime: 1000 / 9,
        maxConcurrent: 6,
        id: 'hubspot-client-limiter'
    }

    Search Limiter Options:

    {
        minTime: 550,
        maxConcurrent: 3,
        id: 'search-hubspot-client-limiter'
    }

    Retry Mechanism: Set numberOfApiCallRetries (0-6) to automatically retry failed requests:

    • 5xx errors: Retried after a delay of 200 * retryNumber ms.
    • 429 (Rate limit exceeded): Retried after a 10-second delay.
    const hubspotClient = new hubspot.Client({
        accessToken: 'YOUR_ACCESS_TOKEN',
        limiterOptions: { minTime: 1000 / 9, maxConcurrent: 6, id: 'hubspot-client-limiter' },
        numberOfApiCallRetries: 3
    });