TypeScript SDK

Install the official TypeScript SDK, make your first call, and handle results and errors without try/catch.

The TypeScript SDK is a typed client for the Social Fetch API. For example, client.tiktok.getProfile() calls GET /v1/tiktok/profiles/{handle}, and the parameters and response come with their types. Calls cost the same credits as the raw API.

Before you start

You need:

  • Node.js 18 or later. The SDK uses the built-in fetch.
  • A project that uses ES modules. The package is ESM only, so use import, not require(). In Node, that means "type": "module" in your package.json or .mts/.mjs files.
  • An API key from the Social Fetch app.

Create an API key

  1. Open API Keys in the app.
  2. Under Name, type something that says where the key will be used, such as local dev.
  3. Leave Expires on No expiry, or pick a date, then click Create key.
The API Keys page with local dev (docs-sdk) typed in the Name box, and the Name box, Expires and Create key highlighted, labelled Name the key, then Create key
Give the key a name you'll recognise later, then click Create key.
  1. Copy the key from Save your API key and click Done. This is the only time the app shows the whole key.
The Save your API key window with the secret covered and the copy button beside it highlighted, labelled Copy it now: it's only shown once
Copy the key before you close this window. If you lose it, revoke it and create another.

Keep the key in an environment variable called SOCIALFETCH_API_KEY. Every example on this page reads it from there:

export SOCIALFETCH_API_KEY=sfk_...

In Windows PowerShell, use $env:SOCIALFETCH_API_KEY = "sfk_..." instead. Either way, the variable lasts until you close the terminal.

Keep the key on your server. Don't put it in code that runs in a browser or a mobile app, where anyone can read it.

Install

Published on npm as

@socialfetch/sdk

$npm install @socialfetch/sdk

Make your first call

Save this as index.mts. It looks up a TikTok profile and prints the follower count. The .mts ending tells Node the file is an ES module, which lets you use await outside a function:

index.mts
import { SocialFetchClient } from "@socialfetch/sdk";

const client = new SocialFetchClient({
  apiKey: process.env.SOCIALFETCH_API_KEY!,
});

const result = await client.tiktok.getProfile({ handle: "charlidamelio" });

if (!result.ok) {
  console.error(result.error.code, result.error.message, result.error.requestId);
} else {
  const { lookupStatus, profile, metrics } = result.value.data;
  if (lookupStatus === "found" && profile && metrics) {
    console.log(`${profile.handle} has ${metrics.followers} followers`);
  } else {
    console.log(`Lookup status: ${lookupStatus}`);
  }
  console.log(`Request ID: ${result.value.meta.requestId}`);
  console.log(`Credits charged: ${result.value.meta.creditsCharged}`);
}

Run it with tsx, which runs TypeScript files directly:

npx tsx index.mts

You'll see something like this:

charlidamelio has 160357094 followers
Request ID: req_8b9caaf0-6a43-4fca-b662-95b457de053b
Credits charged: 1

A successful call gives you { data, meta }, the same envelope the API returns. For a TikTok profile, data holds lookupStatus (found, private or not_found), profile (handle, display name, bio, avatar, verification) and metrics (followers, following, likes, posts). meta holds the requestId and the creditsCharged for the call. Other endpoints use the same envelope; each one's page in the API reference lists its fields.

Find the method for any endpoint

Methods are grouped by platform (client.tiktok, client.instagram, client.youtube, client.twitter and so on) and named after what they fetch. To find the one you need, open the endpoint in the Playground, fill in its parameters and choose the TypeScript SDK tab. It shows the call with your parameters filled in, ready to copy. The same tab is on every endpoint's page in the API reference.

The Playground with Get TikTok profile open and charlidamelio in the handle field. The TypeScript SDK tab is boxed, and the client.tiktok.getProfile call with handle charlidamelio is labelled The method and its parameters
The TypeScript SDK tab shows the call for the endpoint you have open, with your parameters filled in.

In your editor, typing client. lists the platforms, and client.tiktok. lists every TikTok method with its parameters.

Check a call in the request log

Calls made with your API keys appear in the app's Request history (open Usage, then Request history), with their status, how long they took and the credits they cost. To find one call, paste its request ID into the Request ID filter, then click the call.

Request history filtered by one request ID, with the Request ID filter labelled Paste the request ID and the GET /v1/tiktok/profiles/charlidamelio row labelled Click the call to open it
The Request ID filter finds one call among all of them.

The call opens with what it cost, its request ID and the full response the API sent back.

The details of the TikTok profile call: Credits 1 and the request ID boxed and labelled What it cost, and its request ID, and the response's lookupStatus value found labelled Check lookupStatus first
The same response your code received, so you can see what came back.

This is the quickest way to see what happened when a call didn't do what you expected. If you need help, contact support and include the request ID.

Results instead of exceptions

SDK methods don't throw when the API returns an error. They return a Result, which is either a success or an error:

type Result<T, E> =
  | { ok: true; value: T }
  | { ok: false; error: E };

Check result.ok first. TypeScript then knows which side you have: result.value after a success, result.error after a failure.

const result = await client.tiktok.getProfile({ handle: "charlidamelio" });

if (!result.ok) {
  console.error(result.error.code, result.error.requestId);
} else {
  console.log(result.value.data.profile);
}

Prefer try/catch? Use unwrap()

unwrap() returns result.value on success and throws a SocialFetchUnwrapError on failure. The error's detail holds the same error object a Result would:

import { SocialFetchClient, SocialFetchUnwrapError, unwrap } from "@socialfetch/sdk";

const client = new SocialFetchClient({
  apiKey: process.env.SOCIALFETCH_API_KEY!,
});

try {
  const tweets = unwrap(
    await client.twitter.getProfileTweets({ handle: "nasa" }),
  );
  console.log(tweets.data.tweets);
} catch (error) {
  if (error instanceof SocialFetchUnwrapError) {
    console.error(error.detail.code, error.detail.requestId);
  } else {
    throw error;
  }
}

Handle errors

Every error has a kind, a code, a message, a requestId and the httpStatus. For network errors, requestId is empty and httpStatus is 0:

  • kind: "api" means the API answered with an error, such as unauthorized (a missing or wrong key), insufficient_credits or temporarily_unavailable. The Errors page lists every code. On insufficient_credits, the error usually has a checkoutUrl, a link to buy more credits.
  • kind: "client" means the call didn't complete: network_error (the SDK could not send the request or read its response), parse_error or invalid_response (the reply wasn't what the SDK expected).
const result = await client.tiktok.getProfile({ handle: "charlidamelio" });

if (!result.ok) {
  const error = result.error;
  if (error.kind === "api" && error.code === "insufficient_credits") {
    console.error("Out of credits.", error.checkoutUrl ?? "");
  } else if (error.kind === "client") {
    console.error(`The request didn't complete: ${error.code}`);
  } else {
    console.error(error.code, error.message, error.requestId);
  }
}

The package also exports PUBLIC_API_ERROR_CODES, the list of every API error code, and isSocialFetchSdkError(), which checks whether an unknown value is an SDK error.

A successful call can still find nothing

result.ok means the API returned a successful response. A profile that doesn't exist or is private still comes back with ok: true, with lookupStatus set to not_found or private. Check lookupStatus before you use the profile.

const result = await client.instagram.getProfileV2({ profile: "instagram" });

if (!result.ok) {
  // 401, 402, 503, network errors and so on
  console.error(result.error.code, result.error.requestId);
} else {
  const data = result.value.data;
  switch (data.lookupStatus) {
    case "found":
      console.log(data.profile?.handle);
      break;
    case "private":
    case "not_found":
      // A normal answer, not an SDK error
      console.log(`No public profile: ${data.lookupStatus}`);
      break;
  }
}

Some list endpoints don't have a lookupStatus and return an empty list instead. Errors explains how to tell an empty result from a missing account.

Client options

Most projects only need apiKey. The other options are for retries, tests and unusual runtimes:

OptionWhat it does
apiKeyYour API key, sent as the x-api-key header. Required.
retryOnRetryAfterSet to true to wait and retry when the API answers 503 or 429 with a Retry-After header. Off by default. Pass { maxRetries, maxWaitMs } to change the limits (3 retries and a maximum accepted wait of 120 seconds per retry by default). Missing, invalid or longer Retry-After values are not retried. Useful for bulk jobs; leave it off where someone is waiting for the answer.
fetchYour own fetch function, for tests or runtimes without a global fetch.
baseUrlA different API address, for tests.
warnOnSdkUpdateLogs one warning per process when the API recommends an SDK update. On by default; set false to turn it off.
warnOnDeprecatedEndpointsLogs one warning per process for each deprecated endpoint you call, with its replacement when the API supplies one. On by default; set false to turn it off.
const client = new SocialFetchClient({
  apiKey: process.env.SOCIALFETCH_API_KEY!,
  retryOnRetryAfter: true,
});

Use the SDK's types

The package exports the parameter and response types for each method, so you don't need to write your own:

import type {
  GetInstagramProfileV2Params,
  InstagramProfileV2Response,
} from "@socialfetch/sdk";

const params: GetInstagramProfileV2Params = { profile: "instagram" };

function profileHandle(response: InstagramProfileV2Response) {
  return response.data.profile?.handle;
}

To verify webhooks from Monitors, import from @socialfetch/sdk/webhooks. See Webhooks.

On this page