This article is part of in the series
Published: Thursday 26th November 2026

python api

This Python script reads LinkedIn profile URLs from a CRM export and uses EnvoAPI’s People API to add names, headlines, and locations. If two contacts share a profile, the script reuses the result and keeps both rows. To try it without an API key, save the four sample rows below as contacts.csv.

contact_id,linkedin_url
A01,https://www.linkedin.com/in/sample-one/
A02,https://www.linkedin.com/in/sample-one/?trk=demo
A03,
A04,https://www.linkedin.com/in/sample-missing/

In the offline demo, the first lookup returns a fictional profile for Casey Lane.

contact_id,linkedin_url,profile_name,profile_headline,profile_location,lookup_status
A01,https://www.linkedin.com/in/sample-one/,Casey Lane,Product Designer,Austin,ok

Contact A02 gets the same three values as A01. Its URL has a tracking tag, ?trk=demo, but both links point to /in/sample-one/. The other two rows stay in the export even though one has no URL and the other returns no match.

Your CSV needs two columns, contact_id and linkedin_url. You can leave individual URL cells blank.

Can the LinkedIn API look up a profile URL?

LinkedIn restricts its official Profile API to developers it has approved. Its /v2/me endpoint returns the profile of the member who signed in. Looking up another member requires a person ID available through certain restricted APIs. LinkedIn’s Profile API documentation

Look up one profile and read the response

For a live lookup, use a public profile you have permission to process. The script sends its URL to EnvoAPI’s People API, an independent provider that accepts the same kind of link you have in the CSV. With Requests installed and your key in the ENVO_API_KEY environment variable, you can try one profile at the Python prompt. The complete script reads the URL from the CSV instead.

import os
import requests

url = input("Public LinkedIn profile URL: ").strip()
response = requests.get(
"https://api.envoapi.com/v1/profiles/details/by-url",
params={"url": url},
headers={"Authorization": f"Bearer {os.environ['ENVO_API_KEY']}"},
timeout=20,
)
response.raise_for_status()
profile = response.json()["data"]
print(profile["headline"])

Here, url is the profile link. Passing it in params lets Requests encode it for you. The other address, ending in /details/by-url, stays the same for every contact. The key goes in the authorization header, and the 20-second timeout keeps the script from waiting indefinitely for a silent server. Profile lookup endpoint and response fields

The offline demo returns these fields for sample-one. Use data.headline for profile_headline and data.location.displayName for profile_location.

{
"data": {
"fullName": "Casey Lane",
"headline": "Product Designer",
"location": {"displayName": "Austin"}
}
}

Keep the headline as the person wrote it. “Product Designer” happens to look like a job title, but another person might write “I design tools for teachers.” Putting that text in profile_headline preserves an existing job_title column in your CRM.

A profile can also have a name and headline but no location. If location or its displayName is null, the lookup still succeeded. Here’s how the last three cells of that row would look in a CSV. The two commas leave the location cell empty.

profile_headline,profile_location,lookup_status
Product Designer,,ok

Match each profile back to the original contacts

Copy the code below into enrich_profiles.py in the same folder as contacts.csv.

"""Add public profile details to a contact CSV. Use --live to call EnvoAPI."""
import argparse
import csv
import json
import os
import random
import re
import sqlite3
import time
from pathlib import Path
from tempfile import NamedTemporaryFile
from urllib.parse import urlsplit

ENDPOINT = "https://api.envoapi.com/v1/profiles/details/by-url"
FIELDS = ("profile_name", "profile_headline", "profile_location", "lookup_status")

def profile_key(raw):
try:
parts = urlsplit(raw.strip())
except ValueError:
return None
if parts.scheme not in {"http", "https"}:
return None
if parts.netloc.lower() not in {"linkedin.com", "www.linkedin.com"}:
return None
match = re.fullmatch(r"/in/([^/\s]+)/?", parts.path)
if match:
return f"https://www.linkedin.com/in/{match[1]}/"
return None

def live_request(url):
import requests

try:
response = requests.get(
ENDPOINT,
params={"url": url},
headers={"Authorization": f"Bearer {os.environ['ENVO_API_KEY']}"},
timeout=20,
)
data = response.json()["data"] if response.status_code == 200 else None
except (requests.RequestException, KeyError, ValueError) as exc:
raise SystemExit(f"Could not read {url}. Rerun to resume. {exc}") from exc
return response.status_code, data, response.headers.get("Retry-After")

def demo_request(url):
if url == "https://www.linkedin.com/in/sample-one/":
return 200, {
"fullName": "Casey Lane",
"headline": "Product Designer",
"location": {"displayName": "Austin"},
}, None
if url == "https://www.linkedin.com/in/sample-missing/":
return 404, None, None
raise SystemExit(f"No demo response for {url}. Use the sample CSV.")

def lookup(url, request):
for attempt in range(1, 4):
status, data, retry_after = request(url)
if status == 200:
if not isinstance(data, dict) or not {"fullName", "headline", "location"} <= data.keys():
raise SystemExit(f"Incomplete response for {url}. Rerun to resume.")
location = data["location"] or {}
result = (
data["fullName"] or "",
data["headline"] or "",
location.get("displayName") or "",
"ok",
)
return result, attempt
if status == 404:
return ("", "", "", "not_found"), attempt
if status == 401:
raise SystemExit("401: Check ENVO_API_KEY, then rerun.")
if status == 402:
raise SystemExit("402: Check your EnvoAPI credit balance, then rerun.")
if status != 429:
raise SystemExit(f"HTTP {status} for {url}. Check the error and rerun.")
wait = int(retry_after) if (retry_after or "").isdigit() else 2 ** (attempt - 1)
if attempt == 3:
raise SystemExit(f"429: Wait at least {wait} seconds, then rerun.")
time.sleep(wait + random.uniform(0, 0.25))

def enrich(source, live=False):
mode = "live" if live else "demo"
request = live_request if live else demo_request
if live and not os.environ.get("ENVO_API_KEY"):
raise SystemExit("Set ENVO_API_KEY before using --live.")
output = source.with_suffix(f".{mode}.enriched.csv")
checkpoint = source.with_suffix(f".{mode}.sqlite3")
with source.open(encoding="utf-8-sig", newline="") as stream:
reader = csv.DictReader(stream)
columns = reader.fieldnames or []
if not {"contact_id", "linkedin_url"}.issubset(columns):
raise SystemExit("The CSV needs contact_id and linkedin_url columns.")
if len(columns) != len(set(columns)) or set(columns).intersection(FIELDS):
raise SystemExit("Use unique input headers and leave the four output names free.")
rows = list(reader)
if any(None in row for row in rows):
raise SystemExit("A row has extra cells. Quote values containing commas and retry.")

requests_made = 0
db = sqlite3.connect(checkpoint, timeout=60)
try:
db.execute("CREATE TABLE IF NOT EXISTS profiles (url TEXT PRIMARY KEY, result TEXT)")
for row in rows:
raw = row["linkedin_url"] or ""
key = profile_key(raw)
if key:
# Check and save under the same lock so two runs cannot claim a URL at once.
with db:
db.execute("BEGIN IMMEDIATE")
hit = db.execute("SELECT result FROM profiles WHERE url = ?", (key,)).fetchone()
if hit:
result = json.loads(hit[0])
else:
result, attempts = lookup(key, request)
requests_made += attempts
db.execute("INSERT INTO profiles VALUES (?, ?)", (key, json.dumps(result)))
else:
status = "invalid_url" if raw.strip() else "missing_url"
result = ("", "", "", status)
row.update(zip(FIELDS, result))
finally:
db.close()

stream = NamedTemporaryFile(mode="w", dir=output.parent, delete=False,
encoding="utf-8", newline="")
pending = Path(stream.name)
try:
with stream:
writer = csv.DictWriter(stream, fieldnames=[*columns, *FIELDS])
writer.writeheader()
writer.writerows(rows)
pending.replace(output)
finally:
pending.unlink(missing_ok=True)
print(f"{len(rows)} rows | {requests_made} {mode} requests | {output.name}")

if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("csv", type=Path)
parser.add_argument("--live", action="store_true", help="use your EnvoAPI key")
args = parser.parse_args()
enrich(args.csv, args.live)

From that folder, run the offline demo with Python 3.9 or later.

python enrich_profiles.py contacts.csv

Open contacts.demo.enriched.csv to see the result. After the original columns, you’ll find profile_name, profile_headline, profile_location, and lookup_status.

Look at the two versions of sample-one again. Using the raw URLs as keys would send two requests. Removing duplicate rows from the CSV would lose a contact. Instead, the script makes a separate copy of each URL for the lookup. It drops the tracking query and any fragment, uses www.linkedin.com as the host, and gives the profile path one trailing slash. Those changes turn both links into the same key.

The output CSV keeps A02’s original URL, including ?trk=demo. A blank cell gets missing_url. A company page, a shortened link, or another unsupported address gets invalid_url. The script skips the lookup in both cases. For your own data, use a full linkedin.com/in/… or www.linkedin.com/in/… address.

Where a stopped run picks up

After each completed lookup, the script saves the key, the three profile fields, and the status in a small SQLite file beside the CSV. That file is the checkpoint. When Python reaches A02, it finds the answer saved for A01. It does the same after a restart, even if you’ve moved a contact to a different row. If you fix a mistyped link on a single row, its new URL gets a lookup of its own unless another row has already supplied the answer.

A 404 goes into the checkpoint as not_found for this batch. It means the provider couldn’t return that profile at the time of the lookup. If you’re refreshing last month’s export, give the new input a new filename so it gets a fresh checkpoint. Otherwise, you’ll reuse last month’s headlines along with its missing results.

Run the script on your own CSV

If you followed PythonCentral’s CSV-cleaning guide, add contact_id to the list of columns you export.

To look up the profiles in your CSV, you’ll need an API key from EnvoAPI. Install Requests in the same Python environment you use to run the script. On macOS or Linux, set the key in your shell, then pass --live with the filename of your export.

python -m pip install requests
export ENVO_API_KEY='your-key'
python enrich_profiles.py crm.csv --live

In PowerShell, set the variable with $env:ENVO_API_KEY = 'your-key'. The live run creates crm.live.sqlite3 and, once all rows are ready, crm.live.enriched.csv. The demo uses separate filenames, so its fictional responses stay out of your live results. When you import the results into your CRM, match records on contact_id. If the importer offers to overwrite existing values with blanks, leave that option off unless you intend to clear them. An empty profile_location only tells you what this lookup returned.

If the run stops, the error tells you what to fix. A 401 means you should check the key in the shell running Python. A 402 means the account needs credits. For either one, fix the account issue and repeat the command with the same input filename. Previously saved profiles will be there when it starts again.

When the API replies with 429, it includes a Retry-After header with the number of seconds to wait. The script waits that long plus a small random delay and tries again, up to three attempts for that URL. If the third attempt is still rate-limited, the script stops and tells you how long to wait before restarting. A timeout or server error also leaves the current URL available to try again. EnvoAPI’s rate-limit guide

There’s a small window between receiving a response and saving it. If you interrupt Python in that moment, it may repeat the last request. Everything already saved in the checkpoint is ready to reuse. You can rerun the original export as it stands, without working out which row was last on screen.

Run the four-row example twice

If you ran the offline demo above, use the output you already have for this comparison. In a fresh folder, the first run looks like this. The two demo requests use built-in sample responses.

$ python enrich_profiles.py contacts.csv
4 rows | 2 demo requests | contacts.demo.enriched.csv

Open contacts.demo.enriched.csv.

contact_id,linkedin_url,profile_name,profile_headline,profile_location,lookup_status
A01,https://www.linkedin.com/in/sample-one/,Casey Lane,Product Designer,Austin,ok
A02,https://www.linkedin.com/in/sample-one/?trk=demo,Casey Lane,Product Designer,Austin,ok
A03,,,,,missing_url
A04,https://www.linkedin.com/in/sample-missing/,,,,not_found

For A03, the empty cells include the original URL. For A04, the URL is still there so you can check it later. If you filter the spreadsheet by lookup_status, you can find contacts that need a URL separately from contacts whose existing link needs a closer look.

Keep the checkpoint in place and save a copy of the first output. These commands run the example again and compare the two CSVs byte for byte on macOS or Linux.

$ cp contacts.demo.enriched.csv first-run.csv
$ python enrich_profiles.py contacts.csv
4 rows | 0 demo requests | contacts.demo.enriched.csv
$ cmp first-run.csv contacts.demo.enriched.csv && echo "Identical"
Identical

The second run writes all four contacts again. It makes zero new lookups, and cmp confirms that both files contain the same bytes.

To connect a member’s LinkedIn account to an app, see PythonCentral’s LinkedIn integration guide.