![Maven Central Adds Sigstore Signature Validation](https://cdn.sanity.io/images/cgdhsj6q/production/7da3bc8a946cfb5df15d7fcf49767faedc72b483-1024x1024.webp?w=400&fit=max&auto=format)
Security News
Maven Central Adds Sigstore Signature Validation
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.
@hubspot/api-client
Advanced tools
NodeJS v3 [HubSpot API](https://developers.hubspot.com/docs/api/overview) SDK(Client) files
The @hubspot/api-client npm package is a comprehensive client library for interacting with HubSpot's APIs. It allows developers to easily integrate HubSpot's CRM, marketing, sales, and service functionalities into their applications.
CRM
This feature allows you to manage CRM functionalities such as creating, reading, updating, and deleting contacts. The code sample demonstrates how to create a new contact in HubSpot.
const hubspot = require('@hubspot/api-client');
const hubspotClient = new hubspot.Client({ apiKey: 'your-api-key' });
async function createContact() {
const contactObj = { properties: { firstname: 'John', lastname: 'Doe', email: 'john.doe@example.com' } };
const createResponse = await hubspotClient.crm.contacts.basicApi.create(contactObj);
console.log(createResponse);
}
createContact();
Marketing
This feature allows you to manage marketing functionalities such as creating and managing email campaigns. The code sample demonstrates how to create a new email campaign in HubSpot.
const hubspot = require('@hubspot/api-client');
const hubspotClient = new hubspot.Client({ apiKey: 'your-api-key' });
async function createEmailCampaign() {
const emailCampaignObj = { name: 'New Campaign', subject: 'Hello World', fromName: 'Your Company', fromEmail: 'info@yourcompany.com' };
const createResponse = await hubspotClient.marketing.emailCampaigns.create(emailCampaignObj);
console.log(createResponse);
}
createEmailCampaign();
Sales
This feature allows you to manage sales functionalities such as creating, reading, updating, and deleting deals. The code sample demonstrates how to create a new deal in HubSpot.
const hubspot = require('@hubspot/api-client');
const hubspotClient = new hubspot.Client({ apiKey: 'your-api-key' });
async function createDeal() {
const dealObj = { properties: { dealname: 'New Deal', amount: '1000', dealstage: 'qualifiedtobuy' } };
const createResponse = await hubspotClient.crm.deals.basicApi.create(dealObj);
console.log(createResponse);
}
createDeal();
Service
This feature allows you to manage service functionalities such as creating, reading, updating, and deleting tickets. The code sample demonstrates how to create a new support ticket in HubSpot.
const hubspot = require('@hubspot/api-client');
const hubspotClient = new hubspot.Client({ apiKey: 'your-api-key' });
async function createTicket() {
const ticketObj = { properties: { subject: 'Support Request', content: 'Need help with product', hs_pipeline: '0', hs_pipeline_stage: '1' } };
const createResponse = await hubspotClient.crm.tickets.basicApi.create(ticketObj);
console.log(createResponse);
}
createTicket();
The node-hubspot package is another client library for interacting with HubSpot's APIs. It offers similar functionalities to @hubspot/api-client but may have a different API design and feature set.
The hubspot-api package provides a simplified interface for accessing HubSpot's APIs. It is designed to be easy to use and may be a good alternative for developers looking for a more lightweight solution.
NodeJS v3 HubSpot API SDK(Client) files
Please, take a look at our Sample apps
npm install @hubspot/api-client
const hubspot = require('@hubspot/api-client')
const hubspotClient = new hubspot.Client({ accessToken: YOUR_ACCESS_TOKEN })
For ES modules
import { Client } from "@hubspot/api-client";
const hubspotClient = new Client({ accessToken: YOUR_ACCESS_TOKEN });
You'll need to create a private app to get your access token or you can obtain OAuth2 access token.
You can provide developer API key. There is no need to create separate client instances for using endpoints with API key and Developer API key support.
const hubspotClient = new hubspot.Client({ developerApiKey: YOUR_DEVELOPER_API_KEY })
const hubspotClient = new hubspot.Client({ accessToken: YOUR_ACCESS_TOKEN, developerApiKey: YOUR_DEVELOPER_API_KEY })
To change the base path:
const hubspotClient = new hubspot.Client({ accessToken: YOUR_ACCESS_TOKEN, basePath: 'https://some-url' })
To add custom headers to all request:
const hubspotClient = new hubspot.Client({
accessToken: YOUR_ACCESS_TOKEN,
defaultHeaders: { 'My-header': 'test-example' },
})
If you're an app developer, you can also instantiate a client and obtain a new accessToken with your app details and a refresh_token:
hubspotClient.oauth.tokensApi
.createToken('refresh_token', undefined, undefined, YOUR_CLIENT_ID, YOUR_CLIENT_SECRET, YOUR_REFRESH_TOKEN)
.then((results) => {
console.log(results)
// this assigns the accessToken to the client, so your client is ready
// to use
hubspotClient.setAccessToken(results.accessToken)
return hubspotClient.crm.companies.basicApi.getPage()
})
It's possible to turn on retry for failed requests with statuses 429 or 5xx. To turn on/off configurable retries use numberOfApiCallRetries
option on Client instance creation. numberOfApiCallRetries
can be set to a number from 0 - 6. If numberOfApiCallRetries
is set to a number greater than 0 it means that if any API Call receives ISE5xx this call will be retried after a delay 200 * retryNumber ms and if 429 (Rate limit is exceeded) is returned for "TEN_SECONDLY_ROLLING" the call will be retried after a delay 10 sec. Number of retries will not exceed numberOfApiCallRetries
value.
const hubspotClient = new hubspot.Client({
accessToken: YOUR_ACCESS_TOKEN,
numberOfApiCallRetries: 3,
})
All methods return a promise. The success includes the serialized to JSON body and response objects. Use the API method via:
hubspotClient.crm.contacts.basicApi
.getPage(limit, after, properties, propertiesWithHistory, associations, archived)
.then((results) => {
console.log(results)
})
.catch((err) => {
console.error(err)
})
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.companies.associationsApi.create(
createCompanyResponse.id,
'contacts',
createContactResponse.id,
[
{
"associationCategory": "HUBSPOT_DEFINED",
"associationTypeId": AssociationTypes.companyToContact
// AssociationTypes contains the most popular HubSpot defined association types
}
]
)
const dealObj = {
id: yourId,
properties: {
amount: yourValue,
},
}
const dealObj2 = {
id: yourId,
properties: {
amount: yourValue,
},
}
await hubspotClient.crm.deals.batchApi.update({ inputs: [dealObj, dealObj2] })
const fs = require('fs')
const fileName = 'test.csv'
const file = {
data: fs.createReadStream(fileName),
name: fileName,
};
const importRequest = {
name: 'import(' + fileName + ')',
files: [
{
fileName: fileName,
fileImportPage: {
hasHeader: true,
columnMappings: [
{
columnName: 'First Name',
propertyName: 'firstname',
columnObjectType: 'CONTACT',
},
{
columnName: 'Email',
propertyName: 'email',
columnObjectType: 'CONTACT',
},
],
},
},
],
}
const response = await hubspotClient.crm.imports.coreApi.create(file, JSON.stringify(importRequest));
console.log(response)
Only 3 FilterGroups with max 3 Filters are supported.
Despite 'sorts' is an array, however, currently, only one sort parameter is supported.
In JS 'sort' it's possible to set as:
In TS works only the first two options.
after
for initial search should be set as 0
const filter = { propertyName: 'createdate', operator: 'GTE', value: `${Date.now() - 30 * 60000}` }
const filterGroup = { filters: [filter] }
const sort = JSON.stringify({ propertyName: 'createdate', direction: 'DESCENDING' })
const query = 'test'
const properties = ['createdate', 'firstname', 'lastname']
const limit = 100
const after = 0
const publicObjectSearchRequest = {
filterGroups: [filterGroup],
sorts: [sort],
query,
properties,
limit,
after,
}
const result = await hubspotClient.crm.contacts.searchApi.doSearch(publicObjectSearchRequest)
console.log(JSON.stringify(result))
getAll method is available for all major objects (Companies, Contacts, Deals, LineItems, Products, Quotes & Tickets) and works like
const allContacts = await hubspotClient.crm.contacts.getAll()
Please note that pagination is used under the hood to get all results.
const clientId = 'your_client_id'
const redirectUri = 'take_me_to_the_ballpark'
const scope = 'some scopes'
const uri = hubspotClient.oauth.getAuthorizationUrl(clientId, redirectUri, scope)
return hubspotClient.oauth.tokensApi.createToken(
'authorization_code',
code, // the code you received from the oauth flow
YOUR_REDIRECT_URI,
YOUR_CLIENT_ID,
YOUR_CLIENT_SECRET,
).then(...)
const auditLogsResponse = await hubspotClient.cms.auditLogs.defaultApi.getPage()
It is possible to access the hubspot request method directly, it could be handy if client doesn't have implementation for some endpoint yet. Exposed request method benefits by having all configured client params.
hubspotClient.apiRequest({
method: 'PUT',
path: '/some/api/not/wrapped/yet',
body: { key: 'value' },
})
const response = await hubspotClient.apiRequest({
method: 'get',
path: '/crm/v3/objects/contacts',
})
const json = await response.json()
console.log(json)
const formData = new FormData();
const options = {
// some options
};
formData.append("folderPath", '/');
formData.append("options", JSON.stringify(options));
formData.append("file", fs.createReadStream('file path'));
const response = await hubspotClient.apiRequest({
method: 'POST',
path: '/filemanager/api/v3/files/upload',
body: formData,
defaultJson: false
});
console.log(response);
The SDK has reserved words(e.g. from
). Full list of reserved words.
When you face with a reserved word you have to add _
before the word(e.g. _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
);
You may use this library in your Typescript project via:
import * as hubspot from '@hubspot/api-client'
const hubspotClient = new hubspot.Client({ accessToken: YOUR_ACCESS_TOKEN , developerApiKey: YOUR_DEVELOPER_API_KEY })
Apache 2.0
Install project dependencies with
npm install
You can run the tests by executing:
npm run test
You can check the TypeScript code by running:
npm run lint
If there is a linting error based on formatting, you can run the command below to auto-correct the formatting:
npm run prettier:write
[8.6.0] - 2023-02-20
crm.associations.v4
API clientoauth.refreshTokensApi.archiveRefreshToken()
methodFAQs
NodeJS v3 [HubSpot API](https://developers.hubspot.com/docs/api/overview) SDK(Client) files
The npm package @hubspot/api-client receives a total of 242,439 weekly downloads. As such, @hubspot/api-client popularity was classified as popular.
We found that @hubspot/api-client demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 29 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.
Security News
CISOs are racing to adopt AI for cybersecurity, but hurdles in budgets and governance may leave some falling behind in the fight against cyber threats.
Research
Security News
Socket researchers uncovered a backdoored typosquat of BoltDB in the Go ecosystem, exploiting Go Module Proxy caching to persist undetected for years.