### Complete Example: Get published blog posts Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/cms-api.md Example demonstrating how to retrieve a list of published blog posts. ```APIDOC ## Get published blog posts ```typescript const posts = await client.cms.blogs.blogPostsApi.getPage( 10, undefined, 'blog-post', 'PUBLISHED' ); ``` ``` -------------------------------- ### Complete Example: Create redirect Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/cms-api.md Example demonstrating how to create a URL redirect. ```APIDOC ## Create redirect ```typescript const redirect = await client.cms.urlRedirects.redirectsApi.create({ routePrefix: '/old-product', destination: '/new-product', redirectStyle: 301 }); ``` ``` -------------------------------- ### Complete Example: Create new page Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/cms-api.md Example demonstrating how to create a new CMS page. ```APIDOC ## Create new page ```typescript const newPage = await client.cms.pages.pagesApi.create({ name: 'New Landing Page', contentType: 'WEBSITE_PAGE', state: 'DRAFT' }); ``` ``` -------------------------------- ### Install HubSpot API Client Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/README.md Install the HubSpot API Node.js client using npm. ```shell npm install @hubspot/api-client ``` -------------------------------- ### Complete CMS API Example Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/cms-api.md A comprehensive example demonstrating initialization of the client and performing various CMS operations including fetching blog posts, creating pages and redirects, and retrieving HubDB table data. ```typescript import { Client } from '@hubspot/api-client'; const client = new Client({ accessToken: 'your-token' }); // Get published blog posts const posts = await client.cms.blogs.blogPostsApi.getPage( 10, undefined, 'blog-post', 'PUBLISHED' ); // Create new page const newPage = await client.cms.pages.pagesApi.create({ name: 'New Landing Page', contentType: 'WEBSITE_PAGE', state: 'DRAFT' }); // Create redirect const redirect = await client.cms.urlRedirects.redirectsApi.create({ routePrefix: '/old-product', destination: '/new-product', redirectStyle: 301 }); // Get HubDB table data const tableRows = await client.cms.hubdb.rowsApi.getTableRows('table-123'); ``` -------------------------------- ### Complete Example: Get HubDB table data Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/cms-api.md Example demonstrating how to retrieve rows from a HubDB table. ```APIDOC ## Get HubDB table data ```typescript const tableRows = await client.cms.hubdb.rowsApi.getTableRows('table-123'); ``` ``` -------------------------------- ### Complete HubSpot API Client Configuration Example Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/configuration.md A comprehensive example demonstrating various configuration options for the HubSpot API client, including authentication, network settings, custom headers, rate limiting, retry logic, and middleware. ```typescript import { Client } from '@hubspot/api-client'; import * as https from 'https'; const client = new Client({ // Authentication accessToken: 'your-oauth-token', developerApiKey: 'your-developer-key', // Network basePath: 'https://api.hubapi.com', httpAgent: new https.Agent({ keepAlive: true }), // Headers defaultHeaders: { 'X-Custom-Header': 'value' }, // Rate limiting limiterOptions: { minTime: 111, maxConcurrent: 6, id: 'hubspot-client-limiter' }, // Retry logic numberOfApiCallRetries: 3, // Custom middleware middleware: [ { pre(ctx) { console.log('Sending request'); return ctx; }, post(ctx) { console.log('Received response'); return ctx; } } ] }); ``` -------------------------------- ### Example: Get All Contacts Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/services-and-utilities.md Demonstrates how to use the `getAll` utility to retrieve all contacts, specifying the number of items per page and the desired properties. ```typescript // Get all contacts without manual pagination const allContacts = await getAll( client.crm.contacts.basicApi, 100, // 100 per page undefined, // start from beginning ['firstname', 'lastname', 'email'] ); console.log(`Retrieved ${allContacts.length} contacts`); ``` -------------------------------- ### Get All Webhook Subscriptions Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/oauth-files-webhooks.md Retrieve a list of all existing webhook subscriptions. No specific setup is required beyond initializing the client. ```typescript // Get all webhook subscriptions const subscriptions = await client.webhooks.subscriptionsApi.getAll(); ``` -------------------------------- ### Get and Create Invoices Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/crm-api.md Demonstrates how to retrieve an existing invoice by its ID and how to create a new invoice with basic properties. ```typescript // Get invoice const invoice = await client.crm.commerce.invoices.basicApi.getById('invoice-id'); // Create invoice const newInvoice = await client.crm.commerce.invoices.basicApi.create({ externalId: 'inv-123', properties: { total: 500.00 } }); ``` -------------------------------- ### Example: Creating a Configured API Client (TypeScript) Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/services-and-utilities.md Demonstrates how to create a configured API client instance. It initializes the client with authentication, retrieves parameters using `ApiClientConfigurator.getParams`, and applies decorators via `ApiDecoratorService`. ```typescript const config = new Client({ accessToken: 'token' }); const params = ApiClientConfigurator.getParams( config, ServerConfiguration, Observable, Observable ); const basicApi = new BasicApi(params); const decorated = ApiDecoratorService.getInstance().apply(basicApi); ``` -------------------------------- ### Example 401 Unauthorized Error Response (Invalid Credentials) Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/errors-and-exceptions.md A JSON example of a 401 Unauthorized error, indicating invalid authentication credentials. ```json { "status": 401, "message": "Invalid authentication credentials", "category": "AUTHENTICATION_ERROR" } ``` -------------------------------- ### Complete OAuth 2.0 Flow Example Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/oauth-files-webhooks.md This TypeScript example demonstrates the full OAuth 2.0 authorization code grant flow, including generating the authorization URL, handling the callback, exchanging the code for tokens, and refreshing tokens. It requires environment variables for CLIENT_ID and CLIENT_SECRET, and uses session storage for tokens and state. ```typescript import { Client } from '@hubspot/api-client'; // 1. Redirect user to authorization URL const getAuthUrl = (req, res) => { const authUrl = new Client().oauth.getAuthorizationUrl( process.env.CLIENT_ID, 'https://myapp.com/oauth-callback', 'crm.objects.contacts.read crm.objects.deals.read', undefined, req.session.state // CSRF token ); res.redirect(authUrl); }; // 2. Handle OAuth callback const handleCallback = async (req, res) => { const code = req.query.code; const state = req.query.state; // Verify state for CSRF protection if (state !== req.session.state) { return res.status(400).send('Invalid state parameter'); } try { const client = new Client(); const token = await client.oauth.tokensApi.create( 'authorization_code', code, 'https://myapp.com/oauth-callback', process.env.CLIENT_ID, process.env.CLIENT_SECRET ); // Store refresh token securely req.session.refreshToken = token.refreshToken; req.session.expiresAt = Date.now() + token.expiresIn * 1000; // Redirect to authenticated area res.redirect('/dashboard'); } catch (error) { console.error('OAuth error:', error); res.status(500).send('Authentication failed'); } }; // 3. Token refresh middleware const refreshTokenIfNeeded = async (req, res, next) => { if (!req.session.refreshToken) { return next(); } if (Date.now() > req.session.expiresAt) { const client = new Client(); const newToken = await client.oauth.tokensApi.create( 'refresh_token', undefined, undefined, process.env.CLIENT_ID, process.env.CLIENT_SECRET, req.session.refreshToken ); req.session.accessToken = newToken.accessToken; req.session.expiresAt = Date.now() + newToken.expiresIn * 1000; } // Create client with current token req.hubspotClient = new Client({ accessToken: req.session.accessToken }); next(); }; ``` -------------------------------- ### Get and Batch Get Owners Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/crm-api.md Shows how to retrieve a list of all owners or perform a batch read of owners by their IDs. ```typescript // Get all owners const owners = await client.crm.owners.basicApi.getPage(); // Batch get owners const ownerIds = await client.crm.owners.batchApi.read({ inputs: [{ id: 'owner-1' }, { id: 'owner-2' }] }); ``` -------------------------------- ### getUrl Method Example Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/services-and-utilities.md Shows how to obtain the fully constructed URL object using the getUrl method. This is useful for inspecting the final API endpoint. ```typescript const url = request.getUrl(); console.log(url.toString()); // https://api.hubapi.com/crm/v3/objects/contacts?hapikey=... ``` -------------------------------- ### Making an API Call (Contacts) Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/README.md Provides an example of how to make an API call to retrieve a list of contacts using the `getPage` method. ```APIDOC ## Making an API Call (Contacts) ### Description An example demonstrating how to use the HubSpot client to fetch a paginated list of contacts. All methods return a Promise. ### Method ```javascript hubspotClient.crm.contacts.basicApi .getPage(limit, after, properties, propertiesWithHistory, associations, archived) .then((results) => { console.log(results) }) .catch((err) => { console.error(err) }) ``` ### Parameters * **limit** (number) - Optional - The maximum number of contacts to return. * **after** (string) - Optional - The paging cursor for the next page of results. * **properties** (array) - Optional - An array of contact properties to include in the response. * **propertiesWithHistory** (array) - Optional - An array of contact properties to include with history. * **associations** (array) - Optional - An array of association types to include. * **archived** (boolean) - Optional - Whether to include archived contacts. ``` -------------------------------- ### Get Blog Tags Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/cms-api.md Retrieve a list of blog tags. This operation typically fetches a paginated page of tags. ```typescript const tags = await client.cms.blogs.tagsApi.getPage(); ``` -------------------------------- ### Initialize Chat Widget with Identification Token Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/marketing-events-conversations.md Example of how to use the generated identification token when initializing the HubSpot chat widget in a browser. ```javascript // In your chat widget initialization hbspt.conversations.widget.load({ identificationToken: identificationToken, loadImmediately: true }); ``` -------------------------------- ### RetryDecorator Console Output Example Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/services-and-utilities.md Illustrates the console output when the RetryDecorator handles request failures and retries. Logs indicate the status code, retry count, and delay. ```logs Request failed with status code [502], will retry [1] time in [200] ms Request failed with status code [502], will retry [2] time in [400] ms ``` -------------------------------- ### Handle Authentication Errors (401) Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/errors-and-exceptions.md Detect and log authentication failures due to invalid or missing access tokens. This example redirects the user to a login page. ```typescript try { const contacts = await client.crm.contacts.basicApi.getPage(); } catch (error) { if (error.status === 401) { console.error('Authentication failed:', error.message); // Redirect to re-authentication flow window.location.href = '/login'; } } ``` -------------------------------- ### Example Rate Limit Error Response Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/errors-and-exceptions.md A sample JSON object for a 429 rate limit error, indicating that the user has reached their secondly limit. ```json { "status": 429, "message": "You have reached your secondly limit.", "policyName": "TEN_SECONDLY_ROLLING", "correlationId": "abc123" } ``` -------------------------------- ### Initialize Client with Access Token Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/client.md Demonstrates how to create a new Client instance and update its access token. Use this when your OAuth 2.0 token changes. ```typescript const hubspotClient = new Client({ accessToken: 'old-token' }); hubspotClient.setAccessToken('new-token'); ``` -------------------------------- ### Direct API Request - Get contacts Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/README.md Makes a direct GET request to the contacts endpoint to retrieve contact data. ```APIDOC ## Direct API Request - Get contacts ### Description Retrieves contacts using a direct API request to the `/crm/v3/objects/contacts` endpoint. This method demonstrates fetching data when a specific SDK method is not available or preferred. ### Method ```javascript await hubspotClient.apiRequest({ path: '/crm/v3/objects/contacts' }) ``` ### Endpoint `/crm/v3/objects/contacts` ### Request Example ```javascript const response = await hubspotClient.apiRequest({ path: '/crm/v3/objects/contacts', }) const json = await response.json() console.log(json) ``` ``` -------------------------------- ### Initialize Settings Module Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/marketing-events-conversations.md Instantiate the HubSpot client and access the settings module for account and user settings. ```typescript const client = new Client({ accessToken: 'token' }); const settings = client.settings; ``` -------------------------------- ### Example 403 Forbidden Error Response Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/errors-and-exceptions.md A JSON example of a 403 Forbidden error, indicating insufficient permissions for the requested action. ```json { "status": 403, "message": "Insufficient permissions for action", "category": "AUTHORIZATION_ERROR" } ``` -------------------------------- ### Create Contact, Company, and Associate Them Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/README.md Demonstrates creating a contact and a company, then associating them. Ensure AssociationTypes are correctly imported. ```javascript const contactObj = { properties: { firstname: yourValue, lastname: yourValue, }, } const companyObj = { properties: { domain: yourValue, name: yourValue, }, } 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 // AssociationTypes contains the most popular HubSpot defined association types } ] ) ``` -------------------------------- ### Make API Call and Handle Response Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/README.md Example of making an API call using the HubSpot client and handling the response or errors using Promises. This demonstrates fetching a page of contacts. ```javascript hubspotClient.crm.contacts.basicApi .getPage(limit, after, properties, propertiesWithHistory, associations, archived) .then((results) => { console.log(results) }) .catch((err) => { console.error(err) }) ``` -------------------------------- ### Initialize Client with Developer API Key Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/client.md Authenticate using a developer API key. This is an alternative to using an access token. ```typescript const hubspotClient = new Client({ developerApiKey: 'your-developer-api-key' }); ``` -------------------------------- ### Instantiate Client with Custom Base Path Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/README.md Explains how to configure the client to use a custom base path, which is useful for testing or specific deployment scenarios. ```APIDOC ## Instantiate Client with Custom Base Path ### Description Configure the HubSpot client to use a custom base path for API requests. ### Method ```javascript new hubspot.Client({ accessToken: YOUR_ACCESS_TOKEN, basePath: 'https://some-url' }) ``` ### Parameters * **accessToken** (string) - Required - Your HubSpot API access token. * **basePath** (string) - Optional - The custom base URL for API requests. ``` -------------------------------- ### Example 401 Unauthorized Error Response (Missing Scopes) Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/errors-and-exceptions.md A JSON example of a 401 Unauthorized error, specifying missing OAuth scopes required for an action. ```json { "status": 401, "message": "Missing OAuth scopes: [crm.objects.contacts.write]", "category": "AUTHENTICATION_ERROR" } ``` -------------------------------- ### Example Standard API Error Response Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/errors-and-exceptions.md An example JSON object illustrating a standard API error, specifically a validation error with details about an unknown field. ```json { "status": 400, "message": "Invalid input JSON on line 2, column 5: unknown field \"email_invalid\"", "correlationId": "f77e0e45-a2cf-45d3-a4c5-18b6e8edddee", "errors": [ { "message": "unknown field", "code": "INVALID_PROPERTY", "context": { "propertyName": ["email_invalid"] } } ], "category": "VALIDATION_ERROR" } ``` -------------------------------- ### Client Initialization and API Call with Decorators Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/services-and-utilities.md Demonstrates initializing the HubSpot API client with custom options and making a basic API call. Shows the execution flow through RetryDecorator and LimiterDecorator, including error handling for 429 and 5xx errors. ```typescript // 1. Client initialization const client = new Client({ accessToken: 'token', numberOfApiCallRetries: 3, limiterOptions: { minTime: 111, maxConcurrent: 6 } }); // 2. Init sets up decorators // - RetryDecorator (3 retries) // - LimiterDecorator (rate limiting) // 3. API call const contacts = await client.crm.contacts.basicApi.getPage(); // 4. Execution flow // Request → LimiterDecorator → RetryDecorator → HTTP send → Response // 5. If 429 error occurs // - RetryDecorator catches it // - Waits 10 seconds (for TEN_SECONDLY_ROLLING) // - Retries request // - Retries handled by LimiterDecorator // 6. If server error (5xx) occurs // - RetryDecorator catches it // - Waits 200ms × retryNumber // - Retries up to 3 times // - Final error thrown if all retries fail ``` -------------------------------- ### Filter Operator Examples Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/enums-and-constants.md Illustrates how to use different filter operators with various property types. Examples cover numeric comparisons, date ranges, list membership, and text searches. ```typescript // Numeric comparison { propertyName: 'hs_analytics_num_visits', operator: 'GT', value: '5' } ``` ```typescript // Date range { propertyName: 'createdate', operator: 'BETWEEN', value: '2024-01-01', highValue: '2024-12-31' } ``` ```typescript // List membership { propertyName: 'hs_lead_status', operator: 'IN', value: 'new_lead|qualified_lead' // Pipe-separated } ``` ```typescript // Text search { propertyName: 'email', operator: 'CONTAINS', value: 'example.com' } ``` -------------------------------- ### Access Marketing Module Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/marketing-events-conversations.md Instantiate the client and access the marketing module. ```typescript const client = new Client({ accessToken: 'token' }); const marketing = client.marketing; ``` -------------------------------- ### Instantiate Client with Rate Limiter Options Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/README.md Configures the client with custom rate limiting options using the Bottleneck library. ```APIDOC ## Instantiate Client with Rate Limiter Options ### Description Configure rate limiting for API requests using Bottleneck options. This helps manage request frequency to comply with HubSpot's API limits. ### Method ```javascript const DEFAULT_LIMITER_OPTIONS = { minTime: 1000 / 9, maxConcurrent: 6, id: 'hubspot-client-limiter', } const hubspotClient = new hubspot.Client({ accessToken: YOUR_ACCESS_TOKEN, limiterOptions: DEFAULT_LIMITER_OPTIONS, }) ``` ### Parameters * **accessToken** (string) - Required - Your HubSpot API access token. * **limiterOptions** (object) - Optional - Bottleneck options for rate limiting. Example: `DEFAULT_LIMITER_OPTIONS`. ``` -------------------------------- ### Initialize Client with Multiple Authentication Methods Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/client.md Configure the client to use both an access token and a developer API key simultaneously. ```typescript const hubspotClient = new Client({ accessToken: 'your-access-token', developerApiKey: 'your-developer-api-key' }); ``` -------------------------------- ### Get Invoice Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/crm-api.md Retrieves a specific invoice by its ID. ```APIDOC ## GET /crm/v3/objects/invoices/{invoiceId} ### Description Retrieves a specific invoice by its ID. ### Method GET ### Endpoint /crm/v3/objects/invoices/{invoiceId} ### Parameters #### Path Parameters - **invoiceId** (string) - Required - The ID of the invoice. ### Response #### Success Response (200) - **id** (string) - The ID of the invoice. - **externalId** (string) - The external ID of the invoice. - **properties** (object) - Properties of the invoice. - **total** (number) - The total amount of the invoice. #### Response Example ```json { "id": "invoice-id", "externalId": "inv-123", "properties": { "total": 500.00 } } ``` ``` -------------------------------- ### Batch Get Owners Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/crm-api.md Retrieves a batch of owners by their IDs. ```APIDOC ## POST /crm/v3/owners/batch/read ### Description Retrieves a batch of owners by their IDs. ### Method POST ### Endpoint /crm/v3/owners/batch/read ### Parameters #### Request Body - **inputs** (array) - Required - A list of owner IDs to retrieve. - **id** (string) - Required - The ID of the owner. ### Request Example ```json { "inputs": [ { "id": "owner-1" }, { "id": "owner-2" } ] } ``` ### Response #### Success Response (200) - **results** (array) - A list of owner objects corresponding to the input IDs. - **id** (string) - The unique identifier for the owner. - **name** (string) - The name of the owner. #### Response Example ```json { "results": [ { "id": "owner-1", "name": "John Doe" }, { "id": "owner-2", "name": "Jane Smith" } ] } ``` ``` -------------------------------- ### Client Initialization Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/README.md Shows how to initialize the HubSpot API client with an access token. This is the first step before making any API calls. ```APIDOC ## Client Initialization ### Description Shows how to initialize the HubSpot API client with an access token. This is the first step before making any API calls. ### Code Examples ```typescript const client = new Client({ accessToken: 'your-token' }); ``` ``` -------------------------------- ### Get All Owners Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/crm-api.md Retrieves a paginated list of all owners within the HubSpot account. ```APIDOC ## GET /crm/v3/owners ### Description Retrieves a paginated list of all owners within the HubSpot account. ### Method GET ### Endpoint /crm/v3/owners ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of owners to return per page. - **after** (string) - Optional - The paging cursor for the next page. ### Response #### Success Response (200) - **results** (array) - A list of owner objects. - **id** (string) - The unique identifier for the owner. - **name** (string) - The name of the owner. #### Response Example ```json { "results": [ { "id": "owner-1", "name": "John Doe" } ] } ``` ``` -------------------------------- ### Instantiate Client with Custom Headers Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/README.md Demonstrates how to add custom headers to all outgoing requests made by the client. ```APIDOC ## Instantiate Client with Custom Headers ### Description Add custom headers that will be included in all requests made by the HubSpot client. ### Method ```javascript new hubspot.Client({ accessToken: YOUR_ACCESS_TOKEN, defaultHeaders: { 'My-header': 'test-example' }, }) ``` ### Parameters * **accessToken** (string) - Required - Your HubSpot API access token. * **defaultHeaders** (object) - Optional - An object containing custom headers to be sent with every request. ``` -------------------------------- ### Get specific subscription Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/oauth-files-webhooks.md Retrieves details for a specific webhook subscription by its ID. ```APIDOC ## GET /webhooks/v1/subscriptions/{subscriptionId} ### Description Retrieves a specific webhook subscription by its ID. ### Method GET ### Endpoint /webhooks/v1/subscriptions/{subscriptionId} ### Parameters #### Path Parameters - **subscriptionId** (string) - Required - The ID of the subscription to retrieve. ### Response #### Success Response (200) - **id** (string) - The ID of the subscription. - **targetUrl** (string) - The URL to send webhook events to. - **eventTypes** (array) - A list of event types the subscription listens for. - **active** (boolean) - Whether the subscription is currently active. - **createdAt** (string) - The timestamp when the subscription was created. - **updatedAt** (string) - The timestamp when the subscription was last updated. #### Response Example { "id": "sub-123", "targetUrl": "https://myapp.com/webhooks", "eventTypes": [ "contact.creation" ], "active": true, "createdAt": "2023-01-01T12:00:00Z", "updatedAt": "2023-01-01T12:00:00Z" } ``` -------------------------------- ### Get all webhook subscriptions Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/oauth-files-webhooks.md Retrieves a list of all currently active webhook subscriptions. ```APIDOC ## GET /webhooks/v1/subscriptions ### Description Retrieves a list of all webhook subscriptions. ### Method GET ### Endpoint /webhooks/v1/subscriptions ### Parameters None ### Response #### Success Response (200) - **results** (array) - An array of webhook subscription objects. - **paging** (object) - Pagination details. #### Response Example { "results": [ { "id": "sub-123", "targetUrl": "https://myapp.com/webhooks", "eventTypes": [ "contact.creation" ], "active": true, "createdAt": "2023-01-01T12:00:00Z", "updatedAt": "2023-01-01T12:00:00Z" } ], "paging": { "next": { "hasMore": false, "portalId": 123, "requestedAt": "2023-01-01T12:00:00Z", "pageSize": 100, "pageType": "PAGINATION_COMPLIANT" } } } ``` -------------------------------- ### Create Contact, Company and associate created objects Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/README.md Demonstrates how to create a contact and a company, and then associate them using the HubSpot API. ```APIDOC ## Create Contact, Company and associate created objects ### Description This example shows how to create a new contact and a new company, and then establish an association between them. ### Method POST (implied by `create` calls) ### Endpoint `/crm/v3/objects/contacts` (for contact creation) `/crm/v3/objects/companies` (for company creation) `/crm/v4/associations/companies/contacts/batch/create` (for association) ### Request Example ```javascript const contactObj = { properties: { firstname: 'Jane', 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 } ] ) ``` ### Response Success responses will vary based on the created objects and associations. ``` -------------------------------- ### Get Users Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/marketing-events-conversations.md Retrieve a paginated list of users or a specific user by their ID. ```typescript // Get all users const usersList = await client.settings.users.usersApi.getPage( limit, // Optional: items per page after // Optional: pagination cursor ); // Get specific user const user = await client.settings.users.usersApi.getById(userId); ``` -------------------------------- ### Get Specific Domain Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/cms-api.md Retrieve a single website domain by its object ID. ```typescript const domain = await client.cms.domains.domainsApi.getById(objectId); ``` -------------------------------- ### Upload a file (via the SDK) Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/README.md Demonstrates how to upload a file using the HubSpot SDK, specifying file details and upload options. ```APIDOC ## Upload a file (via the SDK) ### Description Uploads a file to HubSpot using the SDK. This method allows specifying file metadata, access level, and overwrite behavior. ### Method ```javascript await hubspotClient.files.filesApi.upload(...) ``` ### Parameters - `data`: File data, typically a readable stream. - `name`: The name of the file. - `folderPath`: The path to the folder where the file should be uploaded. - `options`: An object containing upload options such as `access`, `overwrite`, `duplicateValidationStrategy`, and `duplicateValidationScope`. ### Request Example ```javascript const response = await hubspotClient.files.filesApi.upload( { data: fs.createReadStream('./photo.jpg'), name: 'photo.jpg' }, undefined, '/folder', 'photo.jpg', undefined, JSON.stringify({ access: 'PRIVATE', overwrite: false, duplicateValidationStrategy: 'NONE', duplicateValidationScope: 'ENTIRE_PORTAL', }) ) console.log(response) ``` ``` -------------------------------- ### Get all Contacts Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/README.md Retrieves all contacts from the CRM. This method handles pagination internally. ```APIDOC ## Get all Contacts ### Description This example demonstrates how to retrieve all contacts from the HubSpot CRM. The `getAll` method abstracts away the complexity of pagination. ### Method GET (implied by `getAll`) ### Endpoint `/crm/v3/objects/contacts` ### Notes Pagination is handled automatically by the client library. ``` -------------------------------- ### Initialize Client with Rate Limiting Options Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/client.md Configure rate limiting to control request frequency and concurrency. Set 'minTime' for delay between requests and 'maxConcurrent' for simultaneous requests. ```typescript const hubspotClient = new Client({ accessToken: 'your-access-token', limiterOptions: { minTime: 1000 / 9, // ~111ms between requests maxConcurrent: 6, // Max 6 concurrent requests id: 'hubspot-client-limiter' } }); ``` -------------------------------- ### Create, Check, and Download Exports Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/crm-api.md Demonstrates how to create a new export, check its status, and download the results using the Exports API. ```typescript // Create export const exportRequest = { name: 'Export Contacts', exportFormat: 'CSV', state: 'DRAFT' }; const exportTask = await client.crm.exports.basicApi.create( 'contacts', exportRequest ); // Check export status const status = await client.crm.exports.basicApi.getById('contacts', exportTask.id); // Download export const download = await client.crm.exports.basicApi.downloadById( 'contacts', exportTask.id ); ``` -------------------------------- ### Get Timeline Events Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/crm-api.md Retrieves a paginated list of timeline events for a specific object. ```APIDOC ## GET /crm/v3/objects/{objectType}/{objectId}/timeline/events ### Description Retrieves a paginated list of timeline events for a specific object. ### Method GET ### Endpoint /crm/v3/objects/{objectType}/{objectId}/timeline/events ### Parameters #### Path Parameters - **objectType** (string) - Required - The type of the object (e.g., 'contacts'). - **objectId** (string) - Required - The ID of the object. #### Query Parameters - **limit** (integer) - Optional - The maximum number of events to return per page. - **after** (string) - Optional - The paging cursor for the next page. ### Response #### Success Response (200) - **results** (array) - A list of timeline event objects. #### Response Example ```json { "results": [ { "eventId": "event-123", "timestamp": "2023-10-27T10:00:00Z", "eventTypeId": "note" } ] } ``` ``` -------------------------------- ### Configure Client with Access Token Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/configuration.md Use an OAuth 2.0 access token for authentication. This is the recommended method for most applications. ```typescript const client = new Client({ accessToken: 'your-oauth-access-token' }); ``` -------------------------------- ### Get Export Status Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/crm-api.md Retrieves the status of a previously created export task by its ID. ```APIDOC ## GET /crm/v3/exports/{objectType}/{exportId} ### Description Retrieves the status of a previously created export task by its ID. ### Method GET ### Endpoint /crm/v3/exports/{objectType}/{exportId} ### Parameters #### Path Parameters - **objectType** (string) - Required - The type of object that was exported (e.g., 'contacts'). - **exportId** (string) - Required - The ID of the export task. ### Response #### Success Response (200) - **state** (string) - The current state of the export task (e.g., 'COMPLETE', 'FAILED'). #### Response Example ```json { "state": "COMPLETE" } ``` ``` -------------------------------- ### Instantiate Client with Both Access Token and Developer API Key Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/README.md Illustrates how to instantiate the HubSpot client when both an access token and a developer API key are available. ```APIDOC ## Instantiate Client with Both Access Token and Developer API Key ### Description Instantiate the HubSpot client providing both an access token and a developer API key. ### Method ```javascript new hubspot.Client({ accessToken: YOUR_ACCESS_TOKEN, developerApiKey: YOUR_DEVELOPER_API_KEY }) ``` ### Parameters * **accessToken** (string) - Required - Your HubSpot API access token. * **developerApiKey** (string) - Required - Your HubSpot developer API key. ``` -------------------------------- ### Get Specific Blog Tag Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/cms-api.md Retrieve a single blog tag by its unique ID. ```typescript const tag = await client.cms.blogs.tagsApi.getById(tagId); ``` -------------------------------- ### Get Specific Blog Author Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/cms-api.md Retrieve a single blog author by their unique ID. ```typescript const author = await client.cms.blogs.authorsApi.getById(authorId); ``` -------------------------------- ### Initialize Automation Module Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/marketing-events-conversations.md Instantiate the HubSpot client and access the automation module for workflows and actions. ```typescript const client = new Client({ accessToken: 'token' }); const automation = client.automation; ``` -------------------------------- ### CMS - Get audit logs Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/README.md Retrieves a paginated list of audit logs from the CMS. ```APIDOC ## CMS - Get audit logs ### Description Fetches a page of audit logs for the Content Management System (CMS). This is useful for tracking changes and activities within the CMS. ### Method ```javascript await hubspotClient.cms.auditLogs.auditLogsApi.getPage() ``` ### Request Example ```javascript const response = await hubspotClient.cms.auditLogs.auditLogsApi.getPage() ``` ``` -------------------------------- ### Get associated Companies by Contact Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/README.md Retrieves a list of companies associated with a given contact. ```APIDOC ## Get associated Companies by Contact ### Description This example demonstrates how to fetch all companies associated with a specific contact ID. ### Method GET (implied by `getPage`) ### Endpoint `/crm/v4/associations/contact/{contactId}/company` ### Parameters #### Path Parameters - **contactId** (string) - Required - The ID of the contact. #### Query Parameters - **after** (string) - Optional - The paging cursor for the next page of results. - **pageSize** (integer) - Optional - The number of results to return per page. ``` -------------------------------- ### Instantiate Client with Developer API Key Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/README.md Shows how to instantiate the HubSpot client using a developer API key. This method is suitable for certain API endpoints that support developer API keys. ```APIDOC ## Instantiate Client with Developer API Key ### Description Instantiate the HubSpot client using a developer API key. This can be used alongside or instead of an access token. ### Method ```javascript new hubspot.Client({ developerApiKey: YOUR_DEVELOPER_API_KEY }) ``` ### Parameters * **developerApiKey** (string) - Required - Your HubSpot developer API key. ``` -------------------------------- ### Get Business Units Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/marketing-events-conversations.md Retrieve a paginated list of business units or a specific business unit by its ID. ```typescript // Get all business units const units = await client.settings.businessUnits.businessUnitsApi.getPage( limit, // Optional: items per page after // Optional: pagination cursor ); // Get specific business unit const unit = await client.settings.businessUnits.businessUnitsApi.getById(businessUnitId); ``` -------------------------------- ### Import HubSpot API Client Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/README.md Demonstrates how to import the Client class from the @hubspot/api-client package using ES module syntax or CommonJS. ```typescript import { Client } from '@hubspot/api-client'; // or const hubspot = require('@hubspot/api-client'); const { Client } = hubspot; ``` -------------------------------- ### Client Class Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/00-CONTENTS.txt Documentation for the Client class, including its constructor, configuration options, authentication methods, and module getters for lazy loading of API modules. ```APIDOC ## Client Class ### Description Provides the main entry point for interacting with the HubSpot API. It handles client initialization, authentication, and provides access to various API modules. ### Constructor `new Client(config)` - **config** (IConfiguration) - Required - The configuration object for the client. ### Authentication Methods Supports various authentication methods including OAuth, API key, and Developer key, configured via the `IConfiguration` object. ### Module Getters Provides lazy-loaded getters for accessing different API modules (e.g., `client.crm`, `client.cms`). ### Usage Example ```javascript const HubSpotClient = require('@hubspot/api-client'); const client = new HubSpotClient({ accessToken: 'YOUR_ACCESS_TOKEN' }); // Accessing CRM API const contacts = await client.crm.contacts.basicApi.getPage(); ``` ``` -------------------------------- ### Get subscription status for contact Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/marketing-events-conversations.md Retrieves the subscription status for a specific contact identified by their portal ID. ```APIDOC ## GET /hubspot/communication-preferences/v3/status/{portalId} ### Description Retrieves the subscription status for a specific contact. ### Method GET ### Endpoint /hubspot/communication-preferences/v3/status/{portalId} ### Parameters #### Path Parameters - **portalId** (string) - Required - The ID of the portal to retrieve status for. ``` -------------------------------- ### Type Guards Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/types-and-interfaces.md Provides examples of common TypeScript type guard patterns for checking response and error structures. ```APIDOC ## Type Guards Common TypeScript patterns for checking types: ```typescript // Check if response has paging if (response.paging?.next?.after) { const nextAfter = response.paging.next.after; } // Check if error has details if (error.body?.message) { console.log(error.body.message); } // Check association type if (response.associations?.['companies']?.results) { const companies = response.associations.companies.results; } ``` ``` -------------------------------- ### Initialize Client with Access Token Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/client.md Use this method for authenticating with an access token. Ensure the 'Client' is imported from '@hubspot/api-client'. ```typescript import { Client } from '@hubspot/api-client'; const hubspotClient = new Client({ accessToken: 'your-access-token' }); // Access CRM APIs const contacts = await hubspotClient.crm.contacts.basicApi.getPage(); ``` -------------------------------- ### Create Domain Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/cms-api.md Create a new website domain. Requires the domain name as a parameter. ```typescript const newDomain = await client.cms.domains.domainsApi.create({ domain: 'example.com' }); ``` -------------------------------- ### Instantiate Client with Access Token Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/README.md Demonstrates how to instantiate the HubSpot client using an access token. This is the primary method for authenticating with the HubSpot API. ```APIDOC ## Instantiate Client with Access Token ### Description Instantiate the HubSpot client using an access token obtained from a private app or OAuth 2.0. ### Method ```javascript new hubspot.Client({ accessToken: YOUR_ACCESS_TOKEN }) ``` ### Parameters * **accessToken** (string) - Required - Your HubSpot API access token. ``` -------------------------------- ### Get Communication Subscription Status for a Contact Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/marketing-events-conversations.md Retrieve the subscription status for a specific contact using their portal ID. ```typescript // Get subscription status for contact const contactStatus = await client.communicationPreferences.statusApi.getById(portalId); ``` -------------------------------- ### Client Initialization Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/client.md Initialize the HubSpot API client with optional configuration. The client provides access to all API modules through lazy-loaded getters. ```APIDOC ## Client Class ### Description The `Client` class is the main entry point for the HubSpot API SDK. It allows access to all API modules via lazy-loaded getters and supports multiple authentication methods. ### Constructor ```typescript constructor(config: IConfiguration = {}) ``` #### Parameters - **config** (IConfiguration) - Optional - Configuration object for the client. ``` -------------------------------- ### Get Blog Authors Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/cms-api.md Retrieve a list of blog authors. This operation typically fetches a paginated page of authors. ```typescript const authors = await client.cms.blogs.authorsApi.getPage(); ``` -------------------------------- ### Prepare API Client Parameters (TypeScript) Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/services-and-utilities.md Prepares configuration parameters for API clients, including authentication methods, middleware with custom headers, and base server configurations. This method is generic and requires context types for requests and responses. ```typescript public static getParams( config: IConfiguration, serverConfigurationClass, observableRequestContextParam, observableResponseContextParam ) ``` -------------------------------- ### Get ApiDecoratorService Instance Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/services-and-utilities.md Retrieves the singleton instance of the ApiDecoratorService. This service manages the application of decorators to API methods. ```typescript public static getInstance(): ApiDecoratorService ``` -------------------------------- ### Import Pattern Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/README.md Demonstrates the two common ways to import the Client class from the HubSpot API client library: using ES module syntax or CommonJS. ```APIDOC ## Import Pattern ### Description Demonstrates the two common ways to import the Client class from the HubSpot API client library: using ES module syntax or CommonJS. ### Code Examples ```typescript import { Client } from '@hubspot/api-client'; // or const hubspot = require('@hubspot/api-client'); const { Client } = hubspot; ``` ``` -------------------------------- ### Get All Contacts Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/README.md Retrieves all contacts from HubSpot CRM. This method handles pagination internally to ensure all records are fetched. ```javascript const allContacts = await hubspotClient.crm.contacts.getAll() ``` -------------------------------- ### Initialize HubSpot client in TypeScript Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/README.md Import and initialize the HubSpot client in a TypeScript project. Provide your access token and developer API key during instantiation. ```typescript import * as hubspot from '@hubspot/api-client' const hubspotClient = new hubspot.Client({ accessToken: YOUR_ACCESS_TOKEN , developerApiKey: YOUR_DEVELOPER_API_KEY }) ``` -------------------------------- ### Configure Client with API Key Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/configuration.md Use a legacy API key for authentication. This method is less secure than OAuth 2.0. ```typescript const client = new Client({ apiKey: 'your-api-key' }); ``` -------------------------------- ### Get Specific Webhook Subscription Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/oauth-files-webhooks.md Retrieve details for a single webhook subscription by its ID. Ensure the subscription ID is valid. ```typescript // Get specific subscription const subscription = await client.webhooks.subscriptionsApi.getById(subscriptionId); ``` -------------------------------- ### Instantiate Client with Rate Limiter Options Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/README.md Instantiate the HubSpot client with custom rate limiter options. This allows you to configure the 'Bottleneck' library for managing API request rates. Replace DEFAULT_LIMITER_OPTIONS with your desired Bottleneck configuration. ```javascript const hubspotClient = new hubspot.Client({ accessToken: YOUR_ACCESS_TOKEN, limiterOptions: DEFAULT_LIMITER_OPTIONS, }) ``` -------------------------------- ### Manage Files Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/oauth-files-webhooks.md Perform file management operations including getting information, updating, archiving, purging, and paginating files. ```typescript // Get file information const fileInfo = await client.files.filesApi.getById(fileId); ``` ```typescript // Update file await client.files.filesApi.update(fileId, { name: 'new-name.jpg' }); ``` ```typescript // Archive file await client.files.filesApi.archive(fileId); ``` ```typescript // Delete file await client.files.filesApi.purge(fileId); ``` ```typescript // Get page of files const page = await client.files.filesApi.getPage( limit, // Optional: items per page after, // Optional: pagination cursor folderPath // Optional: filter by folder ); ``` -------------------------------- ### Get Page of Domains Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/cms-api.md Retrieve a paginated list of website domains. Supports optional parameters for limit and pagination cursor. ```typescript const page = await client.cms.domains.domainsApi.getPage( limit, // Optional: items per page after // Optional: pagination cursor ); ``` -------------------------------- ### Instantiate Client with Access Token (ES Modules) Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/README.md Instantiate the HubSpot client using a personal access token with ES module syntax. This is suitable for modern JavaScript environments. Replace YOUR_ACCESS_TOKEN with your actual token. ```javascript import { Client } from "@hubspot/api-client"; const hubspotClient = new Client({ accessToken: YOUR_ACCESS_TOKEN }); ``` -------------------------------- ### Create Contact-Company Association Source: https://github.com/hubspot/hubspot-api-nodejs/blob/master/_autodocs/enums-and-constants.md Example of creating an association between a contact and a company using the HubSpot API client. Ensure the `AssociationTypes` are imported. ```typescript import { AssociationTypes } from '@hubspot/api-client'; await client.crm.associations.v4.basicApi.create( 'contacts', contactId, 'companies', companyId, [ { associationCategory: 'HUBSPOT_DEFINED', associationTypeId: AssociationTypes.contactToCompany } ] ); ```