Files

9.2 KiB

@socialhose/api

Official TypeScript SDK for the Socialhose Public API.

The SDK wraps the Socialhose REST API with typed JavaScript/TypeScript methods for campaign discovery, analytics dashboards, mention search, mailing lists, and SDK-composed entity analytics. It handles API-key auth, browser-compatible headers, retries, timeouts, GET caching, and normalized response shapes so product code can focus on the analysis instead of raw HTTP plumbing.

This package is intended for backend code only. Do not ship your Socialhose API key to browsers.

Getting an API key

API access is available with paid Socialhose subscriptions. See socialhose.net/pricing for current plans, or use a publicly provided API key if Socialhose offers one from time to time.

See the repository API access notes for more key-provisioning details. This package consumes an existing key; it does not create keys, and there is no self-service key-generation flow documented here.

To use the SDK:

  1. Get a Socialhose API key with access to the campaigns you need to query.
  2. Store it as a server-side environment variable:
export SOCIALHOSE_API_KEY="sh_your_key_here"
  1. Pass it to the client:
const socialhose = new SocialhoseClient({
  apiKey: process.env.SOCIALHOSE_API_KEY!,
});

Do not commit API keys, expose them in frontend bundles, or send them to browsers. If you are building a web app, call Socialhose from your server/API route and return only the data your frontend needs.

Install

npm install @socialhose/api

Node 18+ is required because the SDK uses built-in fetch, Response, and AbortSignal.timeout. You can pass a custom fetch implementation if needed.

Quickstart

import { SocialhoseClient } from '@socialhose/api';

const socialhose = new SocialhoseClient({
  apiKey: process.env.SOCIALHOSE_API_KEY!,
});

const mentions = await socialhose.getMentions({
  content_search: 'hospital',
  platforms: 'twitter',
  ordering: '-published_at',
});

console.log(mentions.count, mentions.results[0]?.content);

Core capabilities

Campaign discovery

Campaigns are the API's top-level monitoring containers. Use them to discover what this API key can access, resolve IDs, and scope analytics or mention search.

const campaigns = await socialhose.getCampaigns();
const campaign = await socialhose.getCampaign(campaigns[0].id);

Related methods:

  • getCampaigns() — fetches the first page of accessible campaigns.
  • getCampaign(id) — fetches one campaign by ID.
  • getCampaignIdByMatch(match) — convenience helper that finds a campaign ID by case-insensitive name substring.

Analytics dashboards

Analytics methods summarize campaign performance and conversation health.

const filters = {
  campaign_ids: 'campaign-id',
  date_from: '2026-05-01',
  date_to: '2026-05-29',
};

const [overview, timeline, sentiment, platforms] = await Promise.all([
  socialhose.getOverview(filters),
  socialhose.getTimeline({ ...filters, interval: 'day' }),
  socialhose.getSentiment(filters),
  socialhose.getPlatforms(filters),
]);

Analytics methods include:

  • getOverview() — total mentions, authors, estimated reach, sentiment distribution, platform breakdown, engagement, and growth.
  • getTimeline() — time-series mention volume with sentiment and engagement buckets.
  • getSentiment() — aggregate and platform-specific sentiment splits.
  • getShareOfVoice() — compares campaigns by mention share, engagement, and sentiment.
  • getPlatforms() — mention and engagement totals grouped by platform.
  • getTopKeywords() — most frequent keywords with sentiment split.
  • getTrending() — keywords whose volume changed against the previous period.
  • getTopMentions() — high-impact mentions with reach, engagement, author, URL, and content preview.

Mentions are the underlying public posts/articles/items Socialhose has collected and classified. Search them by campaign, date, platform, sentiment, content, page, and ordering.

const page = await socialhose.getMentions({
  campaign_ids: 'campaign-id',
  content_search: 'ozempic',
  platforms: 'twitter,reddit',
  sentiments: 'negative',
  ordering: '-engagement_count',
});

console.log(page.count);
for (const mention of page.results) {
  console.log(mention.platform, mention.sentiment, mention.url);
}

Use this for feeds, search results, moderation queues, source inspection, custom reports, or downstream enrichment.

Entity analytics

Entity helpers build analytics around one search term even when native analytics endpoints are campaign-scoped. They use /mentions/ facets to produce compact profiles for people, organizations, brands, products, places, hashtags, or arbitrary terms.

const stats = await socialhose.getEntityStats('RSF', 'campaign-id', {
  revalidateSeconds: 900,
});

console.log({
  total: stats.total,
  sentiment: stats.sentiment,
  platformMix: stats.platformMix,
  momentumPct: stats.momentumPct,
  topUrls: stats.sample.slice(0, 3).map((m) => m.url),
});

Entity methods:

  • getEntityBrief(term, campaignId?) — one request for count plus a top-engagement sample; derives sentiment and platform mix from the sample.
  • getEntityStats(term, campaignId?) — richer entity profile with exact facet reconciliation, newest mentions, daily sparkline, and momentum.
  • getEntityBriefs(terms, campaignId?, concurrency?) — batch entity cards with bounded concurrency.

Entity analytics can fan out many requests. Use caching and conservative concurrency for production dashboards.

Mailing lists

Mailing-list helpers support Socialhose alert/recipient workflows.

const lists = await socialhose.getMailingLists();

const result = await socialhose.inviteMailingListMember(lists[0].id, {
  email: 'analyst@example.com',
  first_name: 'Ada',
  last_name: 'Lovelace',
});

Methods:

  • getMailingLists() — fetches first-page mailing-list metadata.
  • inviteMailingListMember() — invites a recipient and normalizes 201 and 409 outcomes into invited or already.

Low-level access

If the SDK does not yet expose a typed helper for an endpoint, use authenticated low-level methods:

const raw = await socialhose.get('/mentions/', {
  page: 1,
  content_search: 'cholera',
});

const created = await socialhose.post('/some-endpoint/', { value: true });
  • get<T>(path, params?, options?) — authenticated cached GET with query serialization.
  • post<T>(path, body, options?) — authenticated JSON POST, never cached.

Configuration

const socialhose = new SocialhoseClient({
  apiKey: process.env.SOCIALHOSE_API_KEY!,
  baseUrl: 'https://socialhose.net/api/public/v1',
  timeoutMs: 8_000,
  retries: 3,
  cacheTtlMs: 60_000,
});

Important options:

  • apiKey — required Socialhose API key. Missing keys fail on the first request.
  • baseUrl — defaults to https://socialhose.net/api/public/v1.
  • timeoutMs — per-attempt timeout. Default: 8000.
  • retries — retry count for network failures, timeouts, 429, and 5xx. Default: 3.
  • cacheTtlMs — default GET cache TTL in milliseconds. Default: 60000; set 0 to disable built-in memory caching.
  • cache — custom cache implementation, e.g. Redis or a platform cache.
  • fetch — custom fetch for tests, instrumentation, or non-standard runtimes.
  • defaultHeaders — extra headers sent with every request.

The SDK sends Authorization: Api-Key <key> and a browser-like User-Agent by default. The user-agent is intentional: the current Socialhose API edge rejects some non-browser requests.

Caching, retries, and failure behavior

  • GET requests are cached by full URL.
  • POST requests are never cached.
  • Default cache is process-local MemoryCache.
  • NoopCache disables storage.
  • Custom caches implement Cache#get, Cache#set, and Cache#delete.
  • revalidateSeconds overrides TTL per request.
  • Non-positive TTL means “do not cache”.
  • Transient failures are retried: network errors, timeouts, 429, and 5xx.
  • Client errors such as 400, 401, 403, and 404 are not retried.
await socialhose.getMentions(
  { content_search: 'sudan' },
  { revalidateSeconds: 900 },
);

For multi-process, serverless, or high-traffic dashboards, inject a shared cache instead of relying on the default in-memory cache.

Errors

Failed requests throw SocialhoseError with status, path, body, and cause when available.

import { SocialhoseError } from '@socialhose/api';

try {
  await socialhose.getCampaign('missing');
} catch (error) {
  if (error instanceof SocialhoseError) {
    console.error(error.status, error.path, error.body);
  }
}

Documentation

  • Usage guide — setup, workflows, filtering, pagination, caching, and operational guidance.
  • API reference — every public class, function, method, option, and exported type.
  • Entity analytics — how term-level analytics are built, accuracy safeguards, and rate-limit guidance.
  • Caching and retries — cache contract, retry policy, request lifecycle, and failure semantics.
  • Examples — runnable TypeScript examples.

Development

pnpm install
pnpm test
pnpm typecheck
pnpm build