LINKEDIN PROFILE API

Node.js Workflow for Enriching Public LinkedIn Profiles

A complete Node.js script that reads a CSV of LinkedIn profile URLs, enriches them in batches of 100, writes CSV and JSONL, retries misses and runs on cron.

By Surender Kumar, GTM Engineer, ProfileHunt · Published · 9 min read

Also in: Español · Português (Brasil) · Deutsch · Français · 简体中文 · हिन्दी · العربية · বাংলা · Русский · Bahasa Indonesia · اردو · 日本語 · मराठी · Tiếng Việt · తెలుగు · Hausa · Türkçe · தமிழ் · 한국어

Node.js Workflow for Enriching Public LinkedIn Profiles

A Node.js workflow for enriching public LinkedIn profiles reads a list of profile URLs, sends them to a batch API 100 at a time, polls each batch until it completes, writes the profiles to a file, and keeps the temporary misses for the next run. This post gives that workflow as one script with no dependencies beyond Node.js, built on the ProfileHunt batch API, plus a cron line to run it every night.

New to the topic? What a LinkedIn profile API is covers the basics; the batch API guide covers the endpoint itself.

Key takeaways

  • Batches of 100, not one call per row. Creating a batch counts as one request against the 60-per-minute limit, and polling doesn't count at all.
  • Write as you go. Results are appended after every batch, so a stopped run keeps everything it finished.
  • Sort results by status. ok is saved, gone is final, unavailable and failed go to a retry file. None of the misses costs a credit.
  • Cron needs the key and a full path. node --env-file=.env and an absolute path to node avoid the two most common cron failures.

Build the script in five steps

The workflow is one file, enrich.mjs. Put the five pieces below into it in order. It needs Node.js 20.6 or later for --env-file, and nothing from npm.

The input is a CSV with a linkedin_url column:

name,linkedin_url
Bill Gates,https://www.linkedin.com/in/williamhgates
Satya Nadella,https://www.linkedin.com/in/satyanadella

Step 1: Set up the API helper

The helper is the Node.js sample from the ProfileHunt batch docs, with one addition: on 429 or 503 it waits the Retry-After seconds and tries again. Every other error stops the script, including 402 when the workspace runs out of credits.

import { appendFile, readFile, writeFile } from "node:fs/promises";

const API = "https://api.profilehunt.dev";
const sleep = ms => new Promise(r => setTimeout(r, ms));

async function api(path, init = {}) {
  for (;;) {
    const res = await fetch(`${API}${path}`, {
      ...init,
      headers: {
        Authorization: `Bearer ${process.env.PROFILEHUNT_KEY}`,
        "Content-Type": "application/json",
      },
    });
    if (res.status === 429 || res.status === 503) {
      await sleep(Number(res.headers.get("retry-after") ?? 5) * 1000);
      continue;
    }
    if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);
    return res.json();
  }
}

Step 2: Read the CSV and the retry file

Read the linkedin_url column, add the URLs left over from the last run, and drop duplicates.

const input = process.argv[2] ?? "input.csv";
const [header, ...rows] = (await readFile(input, "utf8")).split(/\r?\n/).filter(Boolean);
const col = header.split(",").indexOf("linkedin_url");
const fromCsv = rows.map(r => r.split(",")[col]?.trim());
const retry = (await readFile("retry.txt", "utf8").catch(() => "")).split("\n");
const urls = [...new Set([...fromCsv, ...retry].filter(Boolean))];
console.log(`${urls.length} URLs to enrich`);

This split works for simple exports. If your CSV has quoted fields with commas inside them, swap these lines for a CSV parser such as csv-parse.

Step 3: Create a batch and poll it

Each batch takes up to 100 URLs and answers 202 at once with an id. Poll every five seconds until status is completed.

async function runBatch(chunk) {
  let batch = await api("/v1/profile/batches", {
    method: "POST",
    body: JSON.stringify({ urls: chunk }),
  });
  while (batch.status === "processing") {
    await sleep(5000);
    batch = await api(`/v1/profile/batches/${batch.id}`);
  }
  return batch;
}

Crates on a conveyor: most reach the shelf, a few loop back for another pass

Step 4: Write the results

Every result goes to results.jsonl with its full profile, and a flat row goes to results.csv. results come back in the order you sent the URLs, one per URL.

const cell = v => {
  const s = v == null ? "" : String(v);
  return /[",\n]/.test(s) ? `"${s.replaceAll('"', '""')}"` : s;
};
const toCsv = r => {
  const p = r.profile;
  const now = p?.experience.find(e => e.end_date === null);
  return [r.url, r.status, p?.full_name, p?.headline, now?.company, now?.title,
    p?.location, p?.followers, p?.last_post_at, p?.scraped_at].map(cell).join(",");
};

const hasCsv = await readFile("results.csv").then(() => true, () => false);
if (!hasCsv)
  await writeFile("results.csv", "url,status,full_name,headline,company,title,location,followers,last_post_at,scraped_at\n");

const retryLater = [];
for (let i = 0; i < urls.length; i += 100) {
  const batch = await runBatch(urls.slice(i, i + 100));
  console.log(`${batch.id}: ${batch.credits_used} credits`, batch.counts);
  for (const r of batch.results) {
    if (r.status === "unavailable" || r.status === "failed") retryLater.push(r.url);
    await appendFile("results.jsonl", JSON.stringify(r) + "\n");
    await appendFile("results.csv", toCsv(r) + "\n");
  }
}

The flat columns are a starting point. The JavaScript parsing guide covers multiple current roles, year-only dates and the connections cap if you add more.

Step 5: Save the misses for the next run

await writeFile("retry.txt", retryLater.join("\n"));
console.log(`done, ${retryLater.length} URLs saved for retry`);

Here is how the script treats each batch result status. Only ok uses a credit; everything else is refunded automatically.

statusMeaningWhat the script does
okProfile foundSaves it (1 credit)
goneNo public profile at this URLSaves the status; never retries
unavailableLinkedIn didn't serve it just thenAdds it to retry.txt
failedCouldn't be read after several triesAdds it to retry.txt
invalid_urlNot a linkedin.com/in/ URLSaves the status; fix the source data
duplicateSame profile earlier in the batchSaves the status; the first copy has the data

Run it with node --env-file=.env enrich.mjs input.csv, where .env holds PROFILEHUNT_KEY=.... Both sample profiles are public, so expect one batch with ok: 2 and 2 credits used, and two rows in results.csv: Bill Gates at the Gates Foundation and Satya Nadella at Microsoft.

Schedule it with cron

Cron runs commands with a minimal environment: no shell profile, a short PATH, and a different working directory. Spell everything out:

0 3 * * * cd /srv/enrich && /usr/local/bin/node --env-file=.env enrich.mjs input.csv >> enrich.log 2>&1

That line runs every day at 03:00 server time. Find your node path with which node. Because Step 2 reads retry.txt, last night's unavailable URLs are tried again the next night, which is the "later, not straight away" retry the errors docs recommend.

A dial above an idle conveyor with crates lined up for the next run

A scheduled run should only include URLs that need refreshing. Every ok uses a credit, so re-enriching an unchanged list every night costs the same each night. Filter the input to rows whose last scraped_at is older than your refresh window, say 30 days, or to new rows only.

What Most Guides Get Wrong

They loop over single calls. One POST /v1/profile per row hits 60 requests a minute and stops there. One batch request carries 100 URLs, so 60 batch creations a minute covers far more than any nightly list needs.

They write results at the end. A script that holds everything in memory and writes once loses the whole run to one crash. Appending after each batch makes every finished batch permanent.

They retry gone. A profile that isn't public today is unlikely to be public in five minutes. Retrying gone wastes requests; retrying unavailable the next day is what works, as what an unavailable response means explains.

Myth vs Reality

MythReality
"Bulk enrichment needs a queue system like Redis or SQS."For a nightly list, one short script and cron are enough. Add a queue when enrichment is triggered by live events.
"A failed batch item costs a credit."gone, unavailable, failed, invalid_url and duplicate are all free.
"Polling burns your rate limit."GET /v1/profile/batches/<id> isn't counted. Only creating the batch is.
"Results come back in whatever order they finish."results keep the order you sent. results[i] belongs to urls[i].

Advanced: Credits, Overlap and Resuming

Three details matter once the input grows to thousands of rows.

Credits are held per batch. When a batch is created, one credit is held for each URL that will be fetched. If the workspace can't cover the whole batch, it's refused with 402 and nothing is held. The script stops there with every earlier batch already written. Check the balance against urls.length before a large run, and set up a top-up before the nightly job hits the wall. The credits docs cover packs and refunds.

Overlapping runs. If a run takes longer than the gap between cron runs, two copies append to the same files. Guard against it with flock on Linux (flock -n /tmp/enrich.lock node ...) or by writing a lock file at start.

Resuming a stopped run. The JSONL file already lists every URL that finished. On restart, read results.jsonl, collect the URLs with status ok or gone, and remove them from urls before Step 3. A batch can be read for 30 days after it was created, so if the script died mid-poll, logging each batch id as it's created lets you fetch its results instead of paying for them again.

For splitting very large lists and mapping results back to the original rows, see submitting LinkedIn profile URLs in bulk.

Where ProfileHunt Fits

ProfileHunt is a LinkedIn Profile API: public LinkedIn profile URL in, JSON out. The batch endpoint takes up to 100 URLs per request, keeps their order, and charges only for profiles found, which is what keeps this script short.

At $0.50 per 1,000 profiles, a nightly refresh of 2,000 profiles costs at most $1, and less when some URLs come back gone. There's no subscription and credits never expire. The data is the public view: no emails or phone numbers, no titles for past roles, and connections capped at 500.

Getting Started

  1. Sign in at profilehunt.dev/login for 100 free credits with a work email (10 with a personal one).
  2. Put your key in .env, two or three URLs in input.csv, and run the script.
  3. Read the batch API docs for every status and error code, then add the cron line.

For the concepts behind the data, go back to the LinkedIn profile API overview.

Frequently asked questions

How do I enrich a CSV of LinkedIn URLs with Node.js?

Read the URL column, split it into chunks of 100, send each chunk to a batch API such as POST /v1/profile/batches, poll until each batch completes, and append the results to a new file. The script in this post does exactly that.

How many LinkedIn profiles can I enrich per minute with the API?

Each API key can make 60 requests a minute, and one batch request carries up to 100 URLs. Polling isn't counted. How fast the batches finish depends on the list and current load, since every profile is read live.

Should I retry LinkedIn profiles that return unavailable?

Yes, but later rather than straight away. unavailable means LinkedIn didn't serve the profile just then; it's not charged. Saving these URLs for the next scheduled run is a simple, reliable schedule.

How do I run a Node.js enrichment script every night?

Use cron with an absolute path to node, a cd into the script's folder, --env-file=.env for the API key, and output redirected to a log file. Hosted schedulers such as GitHub Actions or a cloud cron service work the same way.

What happens if I run out of credits in the middle of a batch job?

The next batch is refused with 402 insufficient_credits and nothing is held for it. Batches that already finished are saved, so after topping up you can rerun with the remaining URLs.

Get API key 100 free credits with a work email