Get an Instagram profile with the API
Profile by username or id. Complete code for GET /v1/instagram/users/{user} in six languages and both official SDKs, each tested against the documented response.
Short answer. One call returns a public profile: id, username, full_name, biography, external_url, category, verified and business flags, and counts for followers, following and posts. Three routes return the same object: by username, by numeric id, or {user} for either.
Facts checked 2 December 2026. Prices change: follow the links before you decide.
Why call it
- Show follower, following and post counts on creator cards in an influencer-marketing or analytics tool.
- Turn a handle into its numeric
idonce and store the id: it stays the same when the account renames itself. - Check
is_verified,is_businessandcategorybefore you add an account to a campaign list or report.
The request
GET https://api.handlehaul.com/v1/instagram/users/{user} with your key in the X-Api-Key header. Profile by username or id. Same as the two routes above; accepts either. 1 credit.
| Parameter | In | Description |
|---|---|---|
user required | path | Numeric user id (skips the lookup credit) or Instagram username. All digits = an id; write "@12345" for an all-digit username. On list and user endpoints, a username we have to look up costs 1 extra credit (meta.lookup_credits). |
by | query | Optional: says whether user is a username or an id, instead of guessing from the digits. One of: username, id. |
fresh | query | true skips the cache (full price). |
Code in 6 languages
Each sample is a complete program: it reads the key from HANDLEHAUL_API_KEY, waits and retries when the API answers 429 (using Retry-After), stops with the error code on anything else. The SDK versions do the retries for you.
instagram-profile.sh
# Profile by username or id. --retry waits out a 429 using its Retry-After header;
# --fail exits with code 22 on any other error (drop it to read the error JSON).
curl -sS --fail --retry 3 "https://api.handlehaul.com/v1/instagram/users/natgeo" \
-H "X-Api-Key: $HANDLEHAUL_API_KEY"
instagram_profile.pyInstall: pip install requestsRun: python instagram_profile.py
# Profile by username or id: GET /v1/instagram/users/{user}
# pip install requests
import os
import time
import requests
API = "https://api.handlehaul.com/v1"
HEADERS = {"X-Api-Key": os.environ["HANDLEHAUL_API_KEY"]}
def get(path, params=None):
"""GET one endpoint. Waits and retries on 429 (Retry-After); stops on any other error."""
for attempt in range(5):
r = requests.get(API + path, headers=HEADERS, params=params, timeout=60)
if r.status_code == 429:
time.sleep(float(r.headers.get("Retry-After") or 2 ** attempt))
continue
body = r.json()
if not r.ok:
err = body.get("error", {})
raise SystemExit(f"{r.status_code} {err.get('code')}: {err.get('message')}")
return body
raise SystemExit("Still rate limited after 5 tries")
body = get("/instagram/users/natgeo")
data = body["data"]
print(data["username"], data["full_name"], data["counts"]["followers"], data["counts"]["posts"])
print("credits used:", body["meta"]["credits_charged"])
instagram_profile_sdk.pyInstall: pip install handlehaulRun: python instagram_profile_sdk.py
# Profile by username or id: GET /v1/instagram/users/{user}
# pip install handlehaul
from handlehaul import HandleHaul, HandleHaulError
hh = HandleHaul() # reads HANDLEHAUL_API_KEY; retries 429 using Retry-After
try:
res = hh.instagram.profile("natgeo")
data = res.data
print(data["username"], data["full_name"], data["counts"]["followers"], data["counts"]["posts"])
print("credits used:", res.meta["credits_charged"])
except HandleHaulError as e:
raise SystemExit(f"{e.status} {e.code}: {e.message}")
instagram-profile.mjsRun: node instagram-profile.mjs
// Profile by username or id: GET /v1/instagram/users/{user}
// Node.js 18+ (built-in fetch, no packages). Save as instagram-profile.mjs: top-level await needs .mjs.
const API = "https://api.handlehaul.com/v1";
const KEY = process.env.HANDLEHAUL_API_KEY;
// GET one endpoint. Waits and retries on 429 (Retry-After); throws on any other error.
async function get(path, params = {}) {
const url = new URL(API + path);
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
for (let attempt = 0; attempt < 5; attempt++) {
const res = await fetch(url, { headers: { "X-Api-Key": KEY } });
if (res.status === 429) {
const wait = Number(res.headers.get("retry-after")) || 2 ** attempt;
await new Promise((resolve) => setTimeout(resolve, wait * 1000));
continue;
}
const body = await res.json();
if (!res.ok) throw new Error(`${res.status} ${body.error?.code}: ${body.error?.message}`);
return body;
}
throw new Error("Still rate limited after 5 tries");
}
const { data, meta } = await get("/instagram/users/natgeo");
console.log(data.username, data.full_name, data.counts.followers, data.counts.posts);
console.log("credits used:", meta.credits_charged);
instagram-profile-sdk.mjsInstall: npm install handlehaulRun: node instagram-profile-sdk.mjs
// Profile by username or id: GET /v1/instagram/users/{user}
// npm install handlehaul (save as instagram-profile-sdk.mjs)
import { HandleHaul, HandleHaulError } from "handlehaul";
const hh = new HandleHaul(); // reads HANDLEHAUL_API_KEY; retries 429 using Retry-After
try {
const { data, meta } = await hh.instagram.profile("natgeo");
console.log(data.username, data.full_name, data.counts.followers, data.counts.posts);
console.log("credits used:", meta.credits_charged);
} catch (e) {
if (!(e instanceof HandleHaulError)) throw e;
console.error(`${e.status} ${e.code}: ${e.message}`);
process.exit(1);
}
instagram-profile.phpRun: php instagram-profile.php
<?php
// Profile by username or id: GET /v1/instagram/users/{user}
// PHP 8 with the curl extension. Run: php instagram-profile.php
const API = "https://api.handlehaul.com/v1";
// GET one endpoint. Waits and retries on 429 (Retry-After); throws on any other error.
function get(string $path, array $params = []): array
{
$url = API . $path . ($params ? "?" . http_build_query($params) : "");
for ($attempt = 0; $attempt < 5; $attempt++) {
$retryAfter = 0;
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_HTTPHEADER => ["X-Api-Key: " . getenv("HANDLEHAUL_API_KEY")],
CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$retryAfter) {
if (stripos($line, "retry-after:") === 0) {
$retryAfter = (float) trim(substr($line, 12));
}
return strlen($line);
},
]);
$raw = curl_exec($ch);
if ($raw === false) {
throw new RuntimeException(curl_error($ch));
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($status === 429) {
usleep((int) (($retryAfter ?: 2 ** $attempt) * 1000000));
continue;
}
$body = json_decode($raw, true);
if ($status >= 400) {
throw new RuntimeException("$status {$body["error"]["code"]}: {$body["error"]["message"]}");
}
return $body;
}
throw new RuntimeException("Still rate limited after 5 tries");
}
// Print values on one line (strings as they are, everything else as JSON).
function show(...$values): void
{
echo implode(" ", array_map(fn($v) => is_string($v) ? $v : json_encode($v), $values)), "\n";
}
$body = get("/instagram/users/natgeo");
$data = $body["data"];
show($data["username"], $data["full_name"], $data["counts"]["followers"], $data["counts"]["posts"]);
show("credits used:", $body["meta"]["credits_charged"]);
instagram_profile.goRun: go run instagram_profile.go
// Profile by username or id: GET /v1/instagram/users/{user}
// Go 1.18+, standard library only. Run: go run instagram_profile.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"strconv"
"time"
)
const api = "https://api.handlehaul.com/v1"
var client = &http.Client{Timeout: 60 * time.Second}
type objectResponse struct {
Data map[string]any `json:"data"`
Meta struct {
CreditsCharged float64 `json:"credits_charged"`
} `json:"meta"`
}
type apiError struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
// get calls one endpoint and decodes the answer into out. It waits and retries on 429
// (Retry-After) and returns an error for any other failure.
func get(path string, params url.Values, out any) error {
u := api + path
if len(params) > 0 {
u += "?" + params.Encode()
}
for attempt := 0; attempt < 5; attempt++ {
req, err := http.NewRequest(http.MethodGet, u, nil)
if err != nil {
return err
}
req.Header.Set("X-Api-Key", os.Getenv("HANDLEHAUL_API_KEY"))
res, err := client.Do(req)
if err != nil {
return err
}
raw, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
return err
}
if res.StatusCode == http.StatusTooManyRequests {
wait, _ := strconv.ParseFloat(res.Header.Get("Retry-After"), 64)
if wait <= 0 {
wait = float64(int(1) << attempt)
}
time.Sleep(time.Duration(wait * float64(time.Second)))
continue
}
if res.StatusCode >= 400 {
var e apiError
_ = json.Unmarshal(raw, &e)
return fmt.Errorf("%d %s: %s", res.StatusCode, e.Error.Code, e.Error.Message)
}
dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber() // keeps big ids and counts exact
return dec.Decode(out)
}
return fmt.Errorf("still rate limited after 5 tries")
}
// field reads a nested value, e.g. field(row, "counts", "views"); nil when it is missing.
func field(m map[string]any, keys ...string) any {
var v any = m
for _, k := range keys {
obj, ok := v.(map[string]any)
if !ok {
return nil
}
v = obj[k]
}
return v
}
func main() {
params := url.Values{}
var body objectResponse
if err := get("/instagram/users/natgeo", params, &body); err != nil {
log.Fatal(err)
}
fmt.Println(field(body.Data, "username"), field(body.Data, "full_name"), field(body.Data, "counts", "followers"), field(body.Data, "counts", "posts"))
fmt.Println("credits used:", body.Meta.CreditsCharged)
}
instagram-profile.rbRun: ruby instagram-profile.rb
# Profile by username or id: GET /v1/instagram/users/{user}
# Ruby 3, standard library only. Run: ruby instagram-profile.rb
require "json"
require "net/http"
require "uri"
API = "https://api.handlehaul.com/v1"
# GET one endpoint. Waits and retries on 429 (Retry-After); stops on any other error.
def get(path, params = {})
uri = URI(API + path)
uri.query = URI.encode_www_form(params) unless params.empty?
5.times do |attempt|
req = Net::HTTP::Get.new(uri)
req["X-Api-Key"] = ENV.fetch("HANDLEHAUL_API_KEY")
res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", read_timeout: 60) do |http|
http.request(req)
end
if res.code == "429"
sleep((res["Retry-After"] || 2**attempt).to_f)
next
end
body = JSON.parse(res.body)
abort "#{res.code} #{body.dig("error", "code")}: #{body.dig("error", "message")}" unless res.is_a?(Net::HTTPSuccess)
return body
end
abort "Still rate limited after 5 tries"
end
body = get("/instagram/users/natgeo")
data = body["data"]
puts [data["username"], data["full_name"], data.dig("counts", "followers"), data.dig("counts", "posts")].join(" ")
puts "credits used: #{body["meta"]["credits_charged"]}"
Response
One object in data and meta with what the call cost. Example values, from the API docs. Lists are cut to two rows here.
{
"data": {
"id": "787132",
"username": "natgeo",
"full_name": "National Geographic",
"is_private": false,
"is_verified": true,
"profile_pic_url": "https://scontent.cdninstagram.com/…",
"biography": "Experience the world through the eyes of our photographers.",
"external_url": "https://www.nationalgeographic.com",
"category": "Media/news company",
"is_business": true,
"profile_pic_url_hd": "https://scontent.cdninstagram.com/…",
"counts": {
"followers": 280000000,
"following": 160,
"posts": 30500
}
},
"meta": {
"request_id": "req_Zt0q…",
"cached": true,
"cache_age_seconds": 141,
"credits_charged": 0.5,
"credits_remaining": 26948.5
}
}
Cost, cache and limits
- 1 credit per call. At $1.40 to $0.80 per 1,000 calls. Cache hits, failed calls and
429answers are free;meta.credits_chargedsays what each call cost. - No lookup credit. The profile call is the lookup. Store the
idit returns for the other endpoints. - Cache. Answers are cached for 60 seconds, so polling once a minute or less often always gets a live answer. Add
fresh=trueto force a live call (billed). - Speed. Over your plan's requests-per-second limit the API answers
429 rate_limitedwithRetry-After; the samples wait that long and retry. - Private accounts. The profile still comes back, with
is_private: true; their lists and posts answer403 private_account(free). - Testing. A
kd_test_key returns sample data in this exact shape at no cost, so you can run the code before you spend anything.
Things to know
- No lookup credit on the profile routes: the profile call is the lookup itself.
- On the
{user}route an all-digit value is read as an id. Write@12345or addby=usernamefor an all-digit username. The by-username route always reads a username. idis a string because Instagram ids can be larger than 2^53. Store it as text, not as a number.- A private account still returns its public profile fields, with
is_private: true. Its lists and posts are not available.
Same answer, other routes
These routes return the same object as GET /v1/instagram/users/{user}, so they share this page. Pick the one that matches the input you have.
| Route | Use it when | SDK |
|---|---|---|
GET /v1/instagram/users/by-username/{username} | Profile by username | instagram.profileByUsername() (Node), instagram.profile_by_username() (Python) |
GET /v1/instagram/users/by-id/{id} | Profile by user id | instagram.profileById() (Node), instagram.profile_by_id() (Python) |
curl -sS --fail --retry 3 "https://api.handlehaul.com/v1/instagram/users/by-username/natgeo" \
-H "X-Api-Key: $HANDLEHAUL_API_KEY"
curl -sS --fail --retry 3 "https://api.handlehaul.com/v1/instagram/users/by-id/787132" \
-H "X-Api-Key: $HANDLEHAUL_API_KEY"
Next steps
- Instagram account details API: when the account joined, its country and username changes.
- Instagram followers API: followers, newest first.
- Instagram posts API: recent posts.
- Full script for a real job: Instagram API in Python: bulk profiles to CSV or Bulk Instagram profiles to CSV with Node.js.
- Instagram profile API overview: what it returns and how it compares.
- The TikTok version: the same job on the other platform.
- API reference: every field and error code.
- All Instagram API tutorials, or no code at all with n8n, Make, Zapier and Google Sheets.
Instagram profile API: questions
How do I get an Instagram follower count with an API?
data.counts.followers, next to following and posts.Should I look up Instagram profiles by username or by id?
{user} when your input can be either.Run it on real data
One key for Instagram and TikTok. $1.40 to $0.80 per 1,000 calls; failed calls and cache hits are free.
Want to test first? Sandbox keys are free and unlimited, with sample data in the live schema.