1

Find Contacts

by
Published Feb 24, 2025

Search (and sort) contacts in HubSpot.

Script hubspot
  • Submitted by pat m.436 Bun
    Created 491 days ago
    1
    import { Client } from "@hubspot/api-client@^12.0.1";
    2
    
    
    3
    /**
    4
     * This script searches for HubSpot Contacts using filters that you specify.
    5
     * See links below for documentation/help:
    6
     *  - https://developers.hubspot.com/docs/guides/api/crm/search#filter-search-results
    7
     *  - https://github.hubspot.com/hubspot-api-nodejs/classes/crm_contacts.SearchApi.html
    8
     */
    9
    
    
    10
    type Hubspot = {
    11
      token: string;
    12
    };
    13
    
    
    14
    type Filter = {
    15
      propertyName: string; // https://developers.hubspot.com/docs/guides/api/crm/search#search-default-searchable-properties
    16
      operator: 'LT' | 'LTE' | 'GT' | 'GTE' | 'EQ' | 'NEQ' | 'BETWEEN' | 'IN' | 'NOT_IN' | 'HAS_PROPERTY' | 'NOT_HAS_PROPERTY' | 'CONTAINS_TOKEN' | 'NOT_CONTAINS_TOKEN';
    17
      value: string;
    18
    };
    19
    
    
    20
    type Sort = {
    21
      propertyName: string;
    22
      direction: 'ASCENDING' | 'DESCENDING';
    23
    };
    24
    
    
    25
    type SearchOptions = {
    26
      // properties to return outside of default properties
    27
      properties?: string[]
    28
      // you could use just `filters` too but i'm not implementing it
    29
      filterGroups?: {filters: Filter[]}[];
    30
      // only one sort allowed per search, despite it being called `sorts`? hubspot wtf
    31
      sorts?: Sort[];
    32
      // default limit is 10, max. is 200
    33
      limit?: number;
    34
      // for pagination, pass in the `after` property in `paging.next.after` of prev. response
    35
      after?: string;
    36
    }
    37
    
    
    38
    type QueryResponse = {
    39
      total: number;
    40
      results: any[];
    41
    }
    42
    
    
    43
    export async function main(auth: Hubspot, searchOptions: SearchOptions): Promise<QueryResponse> {
    44
      const client = new Client({ accessToken: auth.token });
    45
    
    
    46
      try {
    47
        return await client.crm.contacts.searchApi.doSearch(searchOptions as any);
    48
      } catch (e: any) {
    49
        throw Error(`
    50
          Error Code: ${e?.code || 'UNKNOWN'}
    51
          Message: ${e?.body?.message || e?.body || e}
    52
        `);
    53
      }
    54
    }