iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🧪

[HubSpot] Getting Started with Serverless Functions (Part 3): Displaying Company Lists via HubSpot API 🧪

に公開

[HubSpot] Your First HubSpot Serverless Function (Part 3): Displaying a Company List via the HubSpot API

2025-03-30 · Reina

📝 Introduction

In Part 1, we started by displaying "Hello World," and in Part 2, we displayed cat images using a public API (Cat API), gradually getting used to HubSpot serverless functions 🐾

And now, in this final installment, we will use the "HubSpot API" to dynamically display CRM data on our website!

Specifically, the process involves retrieving a list of "company names" from specific company records via a serverless function and displaying them on a page.

Adding or updating a "List of Client Companies," "Case Studies," or "Portfolio" manually on a page can be quite tedious, don't you think? Companies come and go, or sometimes you just forget to add them...

If you are using the HubSpot CRM, your company record information should already be registered.

🐾 This is our plan!

We will add a property to HubSpot company records to indicate "I want this company displayed," and we will use the HubSpot API's search functionality to retrieve and display only those companies where that property is set to true.

✅ We will be using the

POST /crm/v3/objects/companies/search

endpoint!

Using custom properties allows you to handle data more flexibly and in a way closer to real-world operations ✨

*In this article, I will explain the example where companies are displayed on the page if the custom property "Show on website (show_on_website)" is set to "Yes (true)" 🌏

Also, using the HubSpot API in a serverless function requires setting up authentication. In this article, I will walk you through that process as well 🛡️

Let's start with the preparation 🧪

🧩 (Preparation) Adding a Custom Property to Company Records!

In this function, we are searching HubSpot company records with the condition:

show_on_website = true

To do this, we need to prepare a custom property beforehand as follows👇

⚙️ Creation Steps

  • Go to "⚙️ Settings" in the top right corner.
  • Open "Data Management" > "Properties" from the left menu.
  • Select "Company properties" from the dropdown.
  • Click the "Create property" button.
  • Set it up as follows👇
Item Value
Label Show on website (or any label you prefer)
Internal name show_on_website
Field type Single checkbox

✅ Once the property is set...
You can now filter for this information from the function by checking "Yes✅" only for the company records you want to display on the site!

📂 File Structure

As before, we will place the function inside the .functions folder. For details on how to create it, please refer to the previous article 📝

📁 get-company-list.functions/
├── 📄 get-company-list.js ← The function file we will create this time
└── 📄 serverless.json ← A configuration file to specify secrets, etc.

Inside get-company-list.js, which we will introduce shortly, we will create a function to access the HubSpot API and retrieve a list of company names!

🔐 Before Using the HubSpot API, Prepare Authentication!

In this final part, we will use the HubSpot API to access "company records" in the CRM. To do this, you need to create a Private App in HubSpot and obtain an access token.

However, writing the token directly into your code is a no-go ✋🏻. Instead, we will use the HubSpot CLI's secrets functionality to make it usable within the function safely 🛡️

✅ Step 1: Create a Private App

  • In your HubSpot portal, go to "⚙️ Settings" > "Integrations" > "Private Apps."
  • Click the "Create private app" button.
  • Enter an app name (e.g., serverless-api-demo).
  • Add crm.objects.companies.read to the scopes.
  • After creating the app, copy the "Access token."

✅ Step 2: Register Secrets via CLI

Next, register the token you copied as a secret using the HubSpot CLI.

① Execute the hs secrets add command

hs secrets add

② Specify the secret name (e.g., SERVERLESS_API_DEMO)
③ Just follow the prompts and paste the access token you copied earlier! If you see [SUCCESS], you are done✨

For more detailed information about secrets, click here → Serverless Reference / Secrets

💡 Note: There is a rule for secret names

Secret names can only contain letters, numbers, and underscores (_). Be careful, as names with hyphens (-), like serverless-api-demo, cannot be used!

Valid examples:

HUBSPOT_ACCESS_TOKEN
crm_token
SERVERLESS_API_DEMO

Invalid example:

serverless-api-demo

✅ Step 3: Add the Secret to serverless.json

To allow the function to use this secret, add it to serverless.json in the .functions folder as shown below👇

{
  "runtime": "nodejs18.x",
  "version": "1.0",
  "secrets": ["SERVERLESS_API_DEMO"], // 👈 Specify the secret added earlier here
  "endpoints": {
    "get-company-list": {
      "method": "GET",
      "file": "get-company-list.js"
    }
  }
}

You will use it in the function as process.env.SERVERLESS_API_DEMO. Now that you are ready to safely call the API using the token, it is time to build the function and access company records🐾

🧪 Let's Retrieve the Company Name List with a Serverless Function!

In this section, we will finally create a function that uses the HubSpot API to fetch and display the "company names" of company records that match specific conditions!

✨ Our Goal (Summary)

  • Create a function called get-company-list.js.
  • Call POST /crm/v3/objects/companies/search within the function.
  • Filter company records where show_on_website = true and return a list of company names.
  • Fetch and display it as a <ul> list on the page!

📂 Folder/File Structure (Revisited)

📁 get-company-list.functions/
├── 📄 get-company-list.js
└── 📄 serverless.json

🐾 Step 1: Fetch Matching Company Records via API

In get-company-list.js, search for company records that match the condition (custom property: show_on_website is true) and retrieve the record names.

📄 Sample get-company-list.js

const hubspotToken = process.env.SERVERLESS_API_DEMO;

exports.main = async (context, sendResponse) => {
  try {
    const searchResponse = await fetch('https://api.hubapi.com/crm/v3/objects/companies/search', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${hubspotToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        filterGroups: [
          {
            filters: [
              {
                propertyName: 'show_on_website',
                operator: 'EQ',
                value: true
              }
            ]
          }
        ],
        properties: ['name'],
        limit: 20
      })
    });

    const data = await searchResponse.json();

    const companyNames = data.results
      .map(company => company.properties.name)
      .filter(Boolean);

    sendResponse({
      statusCode: 200,
      body: JSON.stringify(companyNames)
    });

  } catch (error) {
    console.error('Error:', error);
    sendResponse({
      statusCode: 500,
      body: JSON.stringify({ error: 'Failed to retrieve company names' })
    });
  }
};

💡 What get-company-list.js does:

Line Description
fetch(...) Calls the HubSpot company search API
filterGroups / show_on_website = true Condition (* show_on_website is the internal name of the custom property)
properties Information to retrieve (only the name in this case)
.map(...).filter(Boolean) Extract only company names from the array & remove nulls

Once prepared, upload it to the HubSpot Design Manager using hs upload

🔐 Supplement: How to Call Secrets
const hubspotToken = process.env.HUBSPOT_ACCESS_TOKEN;
// headers: {
//   Authorization: `Bearer ${hubspotToken}`,
//   'Content-Type': 'application/json'
// }

The code above retrieves the secret registered in the CLI and sets that value in the API request header👇

Authorization: Bearer <TOKEN>
Content-Type: application/json

This way, you can make authenticated API requests safely without writing the token directly in the code💡

🐾 Step 2: Call the Function from the Client-Side to Display Company Names!

Once the serverless function is complete, let's call it from the page to display the retrieved company names!

💡 What to do here

Step Content
1 Place a <div id="company-list"> in the page template or custom module
2 Use JavaScript to call the serverless function via fetch()
3 Add the returned array as a <ul> list to the HTML

📜 HTML/JavaScript Example for the page

<div id="company-list">Loading...</div>
<script>
fetch('/_hcms/api/get-company-list')
  .then(response => response.json())
  .then(names => {
    const list = document.createElement('ul');
    names.forEach(name => {
      const li = document.createElement('li');
      li.textContent = name;
      list.appendChild(li);
    });
    document.getElementById('company-list').textContent = '';
    document.getElementById('company-list').appendChild(list);
  })
  .catch(err => {
    console.error(err);
    document.getElementById('company-list').textContent = 'Failed to retrieve';
  });
</script>

💡 Process flow:

Line Meaning
fetch(...) Call the created serverless function
.then(response => response.json()) Read the response as JSON
document.createElement('ul') Create a list element
li.textContent = name Set each company name as a list item
.appendChild(...) / <div id="company-list"> Add the list inside #company-list
.catch(...) Display fallback text & output logs upon error

If the company record name with the custom property show_on_website set to true appears after "Loading..." as shown below, you have succeeded🎉💕

  • You can verify the operation by creating one HubSpot page template, pasting the code above, and previewing it!
  • If an error appears in the console, check the "Console" tab in your browser's DevTools👀✨

✨ Summary: Real-world Dynamic Display with HubSpot API and Serverless Functions!

Over the past three parts, we have challenged ourselves with HubSpot serverless functions:

  • 🧪 In Part 1, we experienced how functions work with "Hello World."
  • 🐱 In Part 2, we learned about external API integration and page display using the Cat API.
  • 🏢 And in this final part, we advanced to dynamically fetching and displaying HubSpot CRM company data on a page!

💡 What We Learned Today

✅ Prepared API authentication using a HubSpot Private App.
✅ Understood how to use tokens safely with the CLI's secrets functionality.
✅ Retrieved data using POST /crm/v3/objects/companies/search with a custom property as a condition.
✅ Created a function that returns company names in JSON format.
✅ Called the function with JavaScript and displayed the company list on the page!

🐾 Small Tweaks, Big Maintainability!

Even information you tend to manually update, such as "Client Lists" or "Case Studies," can be linked to the page just by updating the CRM if you use this serverless function + custom property mechanism✨

HubSpot CMS × Serverless Functions is the perfect tool for realizing "little bits of dynamic content"💡

☕ Thank You for Your Hard Work!

To everyone who read through to the end, thank you so much! I would like to close with an illustration of a girl (with a cat🐈) enjoying a coffee break after finishing the implementation☕

I hope this series has sparked even a little interest in serverless functions and HubSpot CMS development🍀

Discussion