How to resolve an Instagram username to a user id
Almost every Instagram endpoint wants the numeric user id (pk) — and almost every workflow starts with a handle. The gap between the two is where bad data enters pipelines. This is every resolution path that works, and the one that silently does not.
Path 1: search (the default)
GET /v1/search/username/{query}?count=10
Returns up to ten matches with pk, username, full_name,
is_private, is_verified. For a unique handle the first hit is the
account; for ambiguous handles (@john), rank by follower_count or
require exact username equality:
from getsocialapi import Client
ig = Client(api_key="gsa_live_...").instagram
hits = ig.search_username("natgeo", count=10)["users"]
match = next(u for u in hits if u["username"] == "natgeo")
uid = match["pk"]
Path 2: username lookup (exact)
When you already trust the handle, the username endpoint resolves it to the full profile in one call — pk plus biography, counters, category. One call instead of search + info.
The trap: shortcodes are not ids
Media shortcodes — the Deu3BoCBbDP in
instagram.com/p/Deu3BoCBbDP/ — historically encoded the media pk in
base64, and half the internet still "decodes" them client-side. Two
reasons to stop:
- The encoding changed. New shortcodes (the
D…family) decode to wrong numbers — silently, with no error. - It was never a contract.
The robust options:
- Media endpoints that accept a shortcode directly (media info, comments, likes) — pass it as the argument, no conversion needed.
- For the raw pk: Instagram's public oEmbed endpoint returns the
media_id— the number before the underscore.
import requests
from urllib.parse import quote
r = requests.get(
"https://i.instagram.com/api/v1/oembed/",
params={"url": "https://www.instagram.com/p/Deu3BoCBbDP/"},
timeout=15)
pk = r.json()["media_id"].split("_")[0] # e.g. 4012386322294878415
User id vs media id vs comment id
| Entity | Field | Looks like | Used by |
|---|---|---|---|
| Account | pk | 25025320 | profile, followers, following, media |
| Media | pk / id | 4012386322294878415_25025320 | media info, comments, likes |
| Comment | pk | 18120167255059206 | reply threads |
The suffix after the underscore in a media id is the owner pk — strip it before passing the id anywhere else.
Caching discipline
Resolution is the cheapest call you will make and the most wasteful to repeat. Cache handle → pk pairs (they are stable; handles change, ids never do), and re-resolve only on 404 from downstream endpoints.
All the endpoints above are live on getsocialapi.com — 100 free calls, no cookies required.
Build with GetSocialAPI
Explore Instagram API for capabilities, pricing and integration examples. Create an account to start with 100 free calls, or follow the quickstart.