LINKEDIN PROFILE API

Python Workflow for Enriching LinkedIn Profiles at Scale

A resumable Python workflow for enriching LinkedIn profiles at scale: batches of 100, polling, a checkpoint file, retries, and the cost math for 100,000 URLs.

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

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

Python Workflow for Enriching LinkedIn Profiles at Scale

A Python workflow for enriching LinkedIn profiles at scale has five parts: dedupe the URLs, split them into batches of 100, submit each batch once and record its id in a checkpoint file, poll until the batch is completed, and write every result to disk before moving on. With that checkpoint, a crash at profile 60,000 resumes at 60,000, nothing is submitted twice, and the cost of 100,000 profiles stays at or under $50.

This post is about scale and recovery. For the concepts behind the API, see what a LinkedIn profile API is; for a single call, the Python enrichment example.

Key takeaways

  • Batches, not loops. One batch request carries 100 URLs and counts as one request against the 60-per-minute limit. Polling isn't counted.
  • Checkpoint the batch id the moment you get it. Resubmitting a batch after a crash pays for the same profiles again.
  • Write results before marking a batch done. The worst a crash can then do is write a duplicate line, which a dedupe on read removes.
  • Retry only unavailable and failed. gone means there is no public profile, and a retry won't change that.
  • 100,000 profiles cost at most $50. Only found profiles use a credit; the rest are refunded.

The workflow at a glance

StageWhat happensFile
LoadRead the CSV, strip and dedupe URLs, keep orderleads.csv
ChunkSplit into lists of 100in memory
SubmitPOST /v1/profile/batches, save the id right awaystate.json
PollGET /v1/profile/batches/<id> every 5 seconds until completed—
StoreAppend one line per result, then mark the chunk doneresults.jsonl
RetryCollect unavailable and failed URLs into a new runretry.csv

The batch API guide explains the endpoint itself. Here the job is to run it a thousand times without losing work.

Build the pipeline

The script needs Python 3.9 or later and requests. It reads a CSV with a linkedin_url column.

Step 1: Load, dedupe and chunk the URLs

import csv, json, os, time
from pathlib import Path
import requests

API = "https://api.profilehunt.dev/v1/profile/batches"
HEADERS = {"Authorization": f"Bearer {os.environ['PROFILEHUNT_KEY']}"}
STATE = Path("state.json")       # chunk number -> {"id": batch id, "done": bool}
RESULTS = Path("results.jsonl")  # one line per URL

def load_urls(path):
    seen, urls = set(), []
    with open(path, newline="") as f:
        for row in csv.DictReader(f):
            url = row["linkedin_url"].strip()
            if url and url not in seen:
                seen.add(url)
                urls.append(url)
    return urls

urls = load_urls("leads.csv")
chunks = [urls[i:i + 100] for i in range(0, len(urls), 100)]

The order of urls must be the same on every run, because a chunk's number is its identity in the checkpoint. Reading the same CSV in the same way keeps it stable. Don't edit the input file while a run is in progress.

Step 2: Wrap every call in retries

def call(method, url, **kwargs):
    for attempt in range(6):
        res = requests.request(method, url, headers=HEADERS, timeout=30, **kwargs)
        if res.status_code in (429, 503):
            time.sleep(int(res.headers.get("Retry-After", 5)))
        elif res.status_code in (500, 502, 504):
            time.sleep(2 ** attempt)
        else:
            res.raise_for_status()   # 401, 402, 404, 422 stop the run
            return res.json()
    raise RuntimeError(f"{method} {url} kept failing")

429 and 503 say how long to wait in Retry-After. 500, 502 and 504 get exponential back-off. Everything else that isn't a success stops the run, on purpose: a 401 means a bad key and a 402 means the workspace can't cover the next batch, and retrying neither helps.

Step 3: Submit, poll and checkpoint

state = json.loads(STATE.read_text()) if STATE.exists() else {}

def save():
    STATE.write_text(json.dumps(state))

for i, chunk in enumerate(chunks):
    key = str(i)
    if state.get(key, {}).get("done"):
        continue                                   # finished on an earlier run
    if key not in state:
        batch = call("POST", API, json={"urls": chunk})
        state[key] = {"id": batch["id"], "done": False}
        save()                                     # before anything else can fail

    batch = call("GET", f"{API}/{state[key]['id']}")
    while batch["status"] == "processing":
        time.sleep(5)
        batch = call("GET", f"{API}/{state[key]['id']}")

    with RESULTS.open("a") as out:
        for r in batch["results"]:
            out.write(json.dumps({"chunk": i, **r}) + "\n")
    state[key]["done"] = True
    save()
    print(f"chunk {i + 1}/{len(chunks)}: {batch['counts']}")

If the script stops anywhere, run it again. Finished chunks are skipped, and a chunk that was submitted but not finished is polled by its saved id instead of being created again.

A checkpoint flag beside a conveyor: work before it is stored, work after it is still waiting

Step 4: Read the results and queue retries

latest = {}
with RESULTS.open() as f:
    for line in f:
        r = json.loads(line)
        latest[r["url"]] = r                       # a repeated line keeps the last copy

retry = [u for u, r in latest.items() if r["status"] in ("unavailable", "failed")]
with open("retry.csv", "w", newline="") as f:
    w = csv.writer(f)
    w.writerow(["linkedin_url"])
    w.writerows([u] for u in retry)

Run the retry file later, as its own input, with a fresh state.json and results.jsonl. unavailable means LinkedIn didn't serve the profile at that moment, so an hour or a day later is a better time than a second later; what an unavailable response means suggests a schedule. gone, invalid_url and duplicate don't go in the retry file. To turn the profile objects into tables, see how to parse structured LinkedIn profile JSON with Python.

Throughput and cost math for 100,000 profiles

Requests. 100,000 URLs make 1,000 batches. Creating a batch counts as one request, and the limit is 60 requests a minute per key, so submitting alone takes about 17 minutes (1,000 ÷ 60). Polling is not counted.

Processing time. Each profile is read live in the background. How long 1,000 batches take depends on load, so measure it: time your first ten batches and multiply. The print in Step 3 gives you the numbers.

Credits. One credit is held for every URL that will be fetched when a batch is created: up to 100 per batch. As results arrive, found profiles keep their credit and everything else is refunded. With one batch in flight, you need at least 100 free credits at any moment; with ten in flight, 1,000.

Cost. At $0.50 per 1,000 profiles found, the ceiling for 100,000 URLs is $50, and you only reach it if every profile is found. As an illustration, a list where 90,000 profiles are found costs 90,000 credits, which is $45. Duplicates, invalid URLs, gone and unavailable are never charged.

URLsBatchesMin. time to submitMax. cost
1,00010under a minute$0.50
10,000100about 2 minutes$5
100,0001,000about 17 minutes$50

The credits docs cover holds and refunds in full.

What Most Guides Get Wrong About Enriching at Scale

They loop single calls with time.sleep(1). At 60 requests a minute, 100,000 single calls need about 28 hours of request budget on one key. The same list in batches needs 1,000 counted requests; processing many profile URLs at once compares the concurrency models in full.

They retry the batch, not the item. When a batch has a few unavailable results, resubmitting the whole batch pays again for every profile that was already found. Retry only the URLs that need it.

They keep results in memory until the end. A script that holds 100,000 profiles in a list and writes once loses everything when it crashes at 99,000. Append each batch to disk as it finishes.

They treat a 402 as a transient error. A 402 means the workspace can't cover the whole batch, and the batch was refused with nothing held. Retrying in a loop just repeats the refusal. Stop, top up, and rerun: the checkpoint picks up where it stopped.

Myth vs Reality

MythReality
More threads means faster enrichment.Batch creation is capped at 60 a minute per key. Parallelism helps with waiting, not with the limit.
A crash means starting over.With the batch id saved on submit, a rerun resumes and pays for nothing twice.
Failed lookups waste credits.Only found profiles use a credit. Holds for everything else are refunded automatically.
A finished batch can be fetched forever.A batch can be read for 30 days after it was created; after that GET returns 404. Store the results.
Every unavailable needs an instant retry.It means LinkedIn didn't serve the profile just then. Retrying later works better than retrying at once.

A balance between many small lookups and one large batch request

Advanced: Several Batches in Flight

The script above runs one batch at a time, which is simple and easy to resume. Once it works, the next step is a window of batches in flight.

Submit ahead, poll in order. Keep up to N batches submitted but unfinished. When the oldest completes and is written, submit the next chunk. The checkpoint logic doesn't change: every submitted id is saved before it is polled, and every chunk is marked done only after its results are on disk.

Size the window by credits, not by threads. Each batch in flight holds up to 100 credits until its results settle. A window of 10 needs 1,000 credits free at all times; if the balance runs low, the next create gets 402 while the earlier batches keep running. Check the balance against N × 100 before you start.

Stay under the create limit. A window of 10 rarely gets near 60 creates a minute, because batches take longer than a second to finish. If you run several workers on one key, they share the 60, so give each its own key and its own state.json.

Write the checkpoint atomically. STATE.write_text can leave a half-written file if the machine dies mid-write. Write to state.json.tmp and call os.replace to swap it in; the swap is atomic on the same filesystem.

Finish within 30 days. A saved batch id stops working 30 days after the batch was created. A run that pauses longer than that should start a fresh state.json for the chunks that aren't done.

Know the one gap a checkpoint can't close. If a create request times out on your side after the server accepted it, you can't tell whether the batch exists. The request body has only urls, so the safe choice is to accept a rare double submission for that one chunk, or check the Usage page before rerunning it. A 30-second timeout on a call that answers 202 at once makes this rare.

Where ProfileHunt Fits

ProfileHunt is a LinkedIn Profile API built for this kind of job: up to 100 URLs per batch request, results in the order you sent them, and the same JSON keys on every profile. Batch items run after single /v1/profile calls, so a 100,000-profile backfill never slows down the lookups your app makes at the same time.

It reads the public view live, without a LinkedIn login, cookie or seat. Pricing is $0.50 per 1,000 profiles found, with no subscription, and credits never expire, so a large backfill can be bought once and spent over weeks.

Getting Started

Sign up with a work email for 100 free credits, and run the script on a CSV of ten URLs first to check the columns and the checkpoint. The batch endpoint docs list every status and error, and the rate limit docs explain how the minute is counted. For how profile APIs work end to end, see what a LinkedIn profile API is.

Frequently asked questions

How do I enrich 100,000 LinkedIn profiles with Python?

Split the URLs into 1,000 batches of 100, submit each to POST /v1/profile/batches, poll each batch until it is completed, and append the results to a file. Save every batch id as soon as you get it so the run can resume.

How long does it take to enrich 100k LinkedIn profiles?

Submitting 1,000 batches takes about 17 minutes at 60 creates a minute. Processing time depends on load, so time your first ten batches and extrapolate.

How much does it cost to enrich 100,000 LinkedIn profiles?

At most $50 with ProfileHunt, at $0.50 per 1,000 profiles found. Profiles that are gone, unavailable, invalid or duplicated cost nothing.

What happens if my enrichment script crashes halfway?

With the checkpoint in this post, nothing is lost: finished batches are skipped, submitted batches are polled by their saved id, and no batch is paid for twice.

Should I retry unavailable LinkedIn profiles right away?

No. unavailable means LinkedIn didn't serve the profile at that moment and it wasn't charged. Collect those URLs and run them again later as a separate input.

Get API key 100 free credits with a work email