Files
sdk/sdks/javascript/README.md
T

276 lines
9.5 KiB
Markdown
Raw Normal View History

2026-05-29 12:46:42 -05:00
# @socialhose/api
2026-05-29 14:41:43 -05:00
Official TypeScript SDK for the Socialhose Public API.
2026-05-29 12:46:42 -05:00
2026-05-29 14:41:43 -05:00
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.
2026-05-29 13:35:09 -05:00
2026-05-29 14:47:41 -05:00
## Getting an API key
2026-05-29 14:57:34 -05:00
See the repository [API access notes](../../README.md#api-access) for subscription and 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.
2026-05-29 14:47:41 -05:00
To use the SDK:
2026-05-29 14:57:34 -05:00
1. Get a Socialhose API key with access to the campaigns you need to query.
2. Store it as a server-side environment variable:
2026-05-29 14:47:41 -05:00
```bash
export SOCIALHOSE_API_KEY="sh_your_key_here"
```
2026-05-29 14:57:34 -05:00
3. Pass it to the client:
2026-05-29 14:47:41 -05:00
```ts
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.
2026-05-29 12:46:42 -05:00
## Install
```bash
npm install @socialhose/api
```
2026-05-29 13:35:09 -05:00
Node 18+ is required because the SDK uses built-in `fetch`, `Response`, and `AbortSignal.timeout`. You can pass a custom `fetch` implementation if needed.
2026-05-29 12:46:42 -05:00
## Quickstart
```ts
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);
```
2026-05-29 14:41:43 -05:00
## Core capabilities
2026-05-29 13:35:09 -05:00
2026-05-29 14:41:43 -05:00
### 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.
```ts
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.
```ts
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.
### Mention search
Mentions are the underlying public posts/articles/items Socialhose has collected and classified. Search them by campaign, date, platform, sentiment, content, page, and ordering.
```ts
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.
```ts
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.
```ts
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:
```ts
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.
2026-05-29 13:35:09 -05:00
2026-05-29 12:46:42 -05:00
## Configuration
```ts
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,
});
```
2026-05-29 14:41:43 -05:00
Important options:
2026-05-29 12:46:42 -05:00
2026-05-29 14:41:43 -05:00
- `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.
2026-05-29 14:41:43 -05:00
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.
2026-05-29 14:41:43 -05:00
## Caching, retries, and failure behavior
2026-05-29 14:41:43 -05:00
- 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.
2026-05-29 12:46:42 -05:00
```ts
2026-05-29 14:41:43 -05:00
await socialhose.getMentions(
{ content_search: 'sudan' },
{ revalidateSeconds: 900 },
);
2026-05-29 12:46:42 -05:00
```
2026-05-29 14:41:43 -05:00
For multi-process, serverless, or high-traffic dashboards, inject a shared cache instead of relying on the default in-memory cache.
2026-05-29 12:46:42 -05:00
## Errors
2026-05-29 13:35:09 -05:00
Failed requests throw `SocialhoseError` with `status`, `path`, `body`, and `cause` when available.
2026-05-29 12:46:42 -05:00
```ts
import { SocialhoseError } from '@socialhose/api';
try {
await socialhose.getCampaign('missing');
} catch (error) {
if (error instanceof SocialhoseError) {
console.error(error.status, error.path, error.body);
}
}
```
2026-05-29 14:41:43 -05:00
## Documentation
- [Usage guide](./docs/GUIDE.md) — setup, workflows, filtering, pagination, caching, and operational guidance.
- [API reference](./docs/API.md) — every public class, function, method, option, and exported type.
- [Entity analytics](./docs/ENTITY_ANALYTICS.md) — how term-level analytics are built, accuracy safeguards, and rate-limit guidance.
- [Caching and retries](./docs/CACHING_AND_RETRIES.md) — cache contract, retry policy, request lifecycle, and failure semantics.
- [Examples](./examples) — runnable TypeScript examples.
2026-05-29 13:35:09 -05:00
## Development
2026-05-29 12:46:42 -05:00
```bash
2026-05-29 13:35:09 -05:00
pnpm install
2026-05-29 12:46:42 -05:00
pnpm test
pnpm typecheck
pnpm build
```
2026-05-29 13:35:09 -05:00
Publishing:
Preferred publish path is the release workflow, which runs with npm provenance from CI. Before publishing, verify npm authentication and `@socialhose` scope access:
2026-05-29 13:35:09 -05:00
```bash
npm whoami
npm publish --dry-run --access public --provenance
2026-05-29 13:35:09 -05:00
```
For the actual release, publish from CI with provenance enabled. If you must publish locally, first confirm whether npm provenance is supported in that environment.