Tracking Twitter (X) Account Views via API — A Developer Guide
Most articles about Twitter (X) account views are written for consumers — 'can I see who viewed my profile?' The honest answer is no, and the technical reason is straightforward (privacy design). But the related developer question — how do I programmatically track account-level view metrics for analytics, brand monitoring, or competitive intelligence? — has a real answer with real engineering trade-offs, and almost no one writes about it.
This guide is the developer version. It covers what the X API actually exposes for account-level view tracking (aggregate impressions, profile visits as a top-line number, tweet-level analytics), what it does NOT expose (per-viewer identity, real-time view streams, historical view density by hour), and the runnable Python pipeline that combines what's available into a usable analytics dataset. Plus the cost economics — track 1 account, 10 accounts, 100 accounts, and what each path costs.
If you're building analytics tooling, brand monitoring, or competitive intelligence around X data, this guide gives you the integration shape and the realistic latency/cost numbers you need before committing to architecture.
What 'account views' actually means in the X API surface
Before designing a tracker, get the vocabulary right. The X API exposes three different metric families that get casually called 'views', and they're not interchangeable.
1. Tweet impressions. Per-tweet count of how many users saw the tweet in their timeline (regardless of engagement). Available via the X API analytics endpoints for tweets posted by accounts you own; available via third-party APIs (including TwitterAPI.io) for tweets you can access programmatically. This is the most actionable 'view' signal — per-tweet, time-series, normalizable to followers.
2. Profile visits aggregate. The number of times a profile page was loaded in a given window (visible in the X Analytics dashboard as 'profile visits this week'). This is account-level, aggregate-only, and not exposed via a stable public API — it's an analytics-dashboard signal, not a developer-API signal. Some third-party tools scrape it from the analytics dashboard; that's a separate compliance question.
3. Engagement metrics (likes, retweets, replies, quotes). Per-tweet engagement counts available for all public tweets via both the official X API and third-party APIs. These are correlated with views but are not views themselves — a tweet can be viewed without engagement.
The practical implication: if your product needs 'profile views' specifically, the X API doesn't reliably give you that at the per-account level. If your product needs 'how visible is this account' as a metric, you build it by combining tweet impressions + engagement-velocity + mention-volume + follower-growth derivatives — all of which the API DOES expose.
Why per-viewer identity isn't (and won't be) exposed
Several articles in this space implicitly promise 'you can see who viewed your profile.' That's wrong, and the wrong-ness is not a technical bug — it's a deliberate platform choice. Understanding why it's a permanent decision saves you weeks chasing a feature that won't ship.
The platform design. X intentionally does not expose per-viewer identity in any API surface. This applies to profile visits, tweet impressions, search-result visibility — every 'view'-shaped signal. Public-data access works by allowing anyone to read public posts; the corollary is that no one tracks who reads them. The few platforms that do track per-viewer identity (LinkedIn for example) are explicit social-graph products where the trade-off is different.
The legal design. Several jurisdictions (EU GDPR, California CPRA) require explicit consent for personally-identifiable tracking of behavior. Exposing per-viewer identity at scale would create compliance obligations X Corp deliberately avoids by simply not tracking that data.
The implication for builders. Any product that markets 'see who viewed your X profile' is either (a) scraping data X doesn't legitimately expose (compliance + ToS risk + frequent breakage when X changes), (b) inferring identity from indirect signals (low accuracy, generally illegal in regulated jurisdictions), or (c) lying to its users. Don't build that product.
What you CAN build — the realistic dev surface
Set aside per-viewer identity. The realistic developer surface for account-views tracking has three patterns, all of which the API supports cleanly.
Pattern A — Aggregate tweet impressions (your own account). If you own the account, the X API's analytics endpoints expose per-tweet impressions, profile visits aggregate, and engagement metrics with ~24h delay. Useful for your own analytics dashboard, growth tracking, and content-experiment measurement.
Pattern B — Per-tweet engagement tracking (any public account). Fetch a target account's recent tweets via API, capture engagement (likes/retweets/replies/quotes) at multiple time points, derive engagement-velocity. This is the strongest available proxy for 'visibility' of public tweets — it's what their content's reach actually looks like.
Pattern C — Mention volume + follower growth as visibility proxies. Track the rate at which an account gets mentioned in public tweets (via filtered stream or periodic search) and the rate at which its follower count grows. Both are indirect proxies for visibility but they're real signal — and they're available via the same public API surface that all third-party tools use.
Combining the three. Building an account-visibility analytics product means combining all three: pattern A for owned-account ground truth, pattern B for engagement-velocity per-tweet, pattern C for trend-line visibility. The runnable Python in the next section starts with pattern B + C — pattern A requires owned-account auth, which is per-customer onboarding.
Runnable Python — track an account's engagement-velocity over time
Below is a working pipeline that targets a specific account, captures all recent tweets, schedules engagement re-fetch at T+15m / T+1h / T+6h / T+24h, computes engagement-velocity (likes per minute in the first 15 minutes is a leading indicator of total reach), and outputs JSONL for downstream analytics.
Cost: roughly $1/month per account at the recommended cadence (60-second timeline poll + 4 re-fetches per new tweet on TwitterAPI.io at $0.00015 per read). At 100 tracked accounts, total cost is roughly $100/month — about 33× cheaper than the same workload on the official X API at $0.005/read.
Implementation notes embedded in the script:
- We resolve the handle once to a user_id and cache locally.
- The poll loop captures new tweets to JSONL + schedules re-fetches into a queue.
- The re-fetch loop runs at every poll tick; checks the queue for due checkpoints.
- Each re-fetch event has a kind field (new_tweet vs velocity_checkpoint) so downstream code can join cleanly.
- The headline metric: likes/minute in the first 15 minutes. Engagement velocity in the first 15-30 minutes is widely cited as a leading indicator of viral reach; the exact correlation depends on the account category and time window, and you should verify against your own data before relying on a specific threshold.
What the data unlocks — analytics applications
Once an account's engagement-velocity data is in your pipeline, several downstream applications compose naturally:
- Content benchmarking — Compare engagement-velocity across different tweet types (original / reply / quote / image / video). Different content categories tend to have meaningfully different velocity baselines on the same account; normalize before drawing conclusions.
- Best-time-to-post predictor — Build a hour-of-week × engagement-velocity heatmap from the account's history; recommend posting windows when expected velocity is highest. This is one of the few 'best time to post' tools that uses real data instead of category averages.
- Competitive monitoring — Track the engagement-velocity of competitor accounts and yourself; chart the share of voice over time. The relative velocity (their velocity / your velocity) is more useful than absolute numbers because it controls for industry-wide attention shifts.
- Anomaly detection (spikes, drops, sudden silence) — A tracked account that posts 3 tweets per day at velocity X suddenly going silent for 36 hours is signal — either operational (account locked, person on vacation) or strategic (waiting to release a high-stakes post). Either is useful in monitoring or PR contexts.
Cost economics — what tracking N accounts actually costs
Scaling cost is linear per-account at the recommended cadence. Realistic monthly cost on TwitterAPI.io vs the official X API at three account counts:
At 100 tracked accounts (a realistic mid-size monitoring product), the cost gap is roughly 33× — $750/month on TwitterAPI.io vs $25,000/month on the official path. At 1,000 accounts (a full enterprise monitoring product) the gap is $7.5K/month vs $250K/month annual.
Why the gap is so large. TwitterAPI.io operates as a managed gateway with a flat per-call rate. Official X API charges $0.005 per post read. Both return identical data shapes for the standard X API surface. For tracking workloads that compound calls heavily (hourly polls + multiple velocity checkpoints per tweet), the per-call gap compounds linearly. See [our X API cost breakdown for the per-endpoint math](/blog/x-api-cost-breakdown-2026).
Operational notes — rate limits, suspensions, ToS
Three operational notes for a production tracker:
- Rate limits and burst behavior. Official X API enforces per-endpoint 15-minute caps (75-900 req/15min depending on endpoint). At high account counts, you'll hit them and need to shard across multiple OAuth contexts. TwitterAPI.io uses spending-limit control instead — you set a monthly max and the API throttles you when you approach it. The TwitterAPI.io model is easier to reason about at high N.
- Suspension handling. Some accounts get suspended; the API will 404 the handle. Treat this as state, not error — log a account_suspended event, back off polling, and resume when the handle resolves again. The runnable Python in the section above handles this branch.
- ToS compliance for downstream products. Public-tweet data via API (official or third-party) is governed by the platform's API ToS, not by per-account consent. For commercial products built on this data (brand-safety platforms, analytics SaaS, competitive intelligence), consult your jurisdiction's data-protection regulations on top of the API ToS — especially around the inference of personal data from public posts.
# pip install requests
import json
import time
import pathlib
import requests
API_KEY = "YOUR_TWITTERAPI_IO_KEY"
BASE = "https://api.twitterapi.io"
HANDLE = "elonmusk" # change to whoever you're tracking
POLL_INTERVAL = 60 # seconds
VELOCITY_CHECKPOINTS = [15, 60, 360, 1440] # minutes after first-seen
STATE_DIR = pathlib.Path(".state")
STATE_DIR.mkdir(exist_ok=True)
IDS_FILE = STATE_DIR / f"{HANDLE}_seen.json"
VEL_FILE = STATE_DIR / f"{HANDLE}_velocity_queue.json"
OUT_FILE = STATE_DIR / f"{HANDLE}_events.jsonl"
headers = {"X-API-Key": API_KEY}
def load_json(p, default):
return json.loads(p.read_text()) if p.exists() else default
def save_json(p, obj):
p.write_text(json.dumps(obj))
def emit(d):
with OUT_FILE.open("a") as f:
f.write(json.dumps(d) + "\n")
def resolve_uid(handle):
r = requests.get(f"{BASE}/twitter/user/info",
params={"userName": handle}, headers=headers, timeout=10)
if r.status_code == 404:
return None # suspended
r.raise_for_status()
return str(r.json()["data"]["id"])
def poll_once(uid):
r = requests.get(f"{BASE}/twitter/user/last_tweets",
params={"userId": uid}, headers=headers, timeout=10)
r.raise_for_status()
tweets = r.json().get("data", {}).get("tweets", [])
seen = set(load_json(IDS_FILE, []))
queue = load_json(VEL_FILE, [])
now = time.time()
for t in tweets:
if t["id"] in seen:
continue
e = (t.get("likeCount", 0) + t.get("retweetCount", 0) +
t.get("replyCount", 0) + t.get("quoteCount", 0))
emit({"kind": "new_tweet", "id": t["id"],
"created_at": t.get("createdAt"), "first_seen_at": now,
"likes": t.get("likeCount", 0),
"retweets": t.get("retweetCount", 0),
"replies": t.get("replyCount", 0),
"engagement": e})
for m in VELOCITY_CHECKPOINTS:
queue.append({"tid": t["id"], "at": now + m * 60})
seen.add(t["id"])
save_json(IDS_FILE, sorted(seen)[-300:])
save_json(VEL_FILE, queue)
def velocity_pass():
q = load_json(VEL_FILE, [])
due = [c for c in q if c["at"] <= time.time()]
save_json(VEL_FILE, [c for c in q if c["at"] > time.time()])
for c in due:
r = requests.get(f"{BASE}/twitter/tweet/info",
params={"tweetId": c["tid"]}, headers=headers, timeout=10)
present = r.status_code != 404
if present:
r.raise_for_status()
d = r.json().get("data", {})
emit({"kind": "velocity_checkpoint", "id": c["tid"], "at": c["at"],
"present": True, "likes": d.get("likeCount"),
"retweets": d.get("retweetCount"),
"replies": d.get("replyCount")})
else:
emit({"kind": "velocity_checkpoint", "id": c["tid"], "at": c["at"],
"present": False})
if __name__ == "__main__":
while True:
uid = resolve_uid(HANDLE)
if uid is None:
emit({"kind": "account_suspended", "at": time.time()})
time.sleep(3600)
continue
try:
poll_once(uid); velocity_pass()
except Exception as e:
print("err:", e)
time.sleep(POLL_INTERVAL)
Questions readers ask
Can I see who viewed my Twitter (X) account via the API?
No. X does not expose per-viewer identity in any API surface — this is a deliberate platform design choice, not a missing feature. Any third-party tool that promises 'see who viewed your profile' is either scraping data X doesn't legitimately expose, inferring identity from indirect signals, or misrepresenting their product. Don't build on that promise.
What account-view metrics CAN I track via the X API?
Three families: (1) per-tweet impressions for tweets posted by accounts you own (via X API analytics, ~24h delay); (2) per-tweet engagement metrics (likes/retweets/replies/quotes) for any public account, via the public X API surface; (3) derived visibility proxies — mention volume, follower growth rate, engagement-velocity over time. Combine these for an account-visibility analytics product.
How much does tracking 10 accounts cost?
On TwitterAPI.io at $0.00015 per read, tracking 10 accounts at 60-second poll + 4 velocity re-fetches per new tweet costs roughly $75/month. On the official X API at $0.005 per read, the same workload costs about $2,500/month — a 33× gap that compounds as you scale. The cost is linear per account; tracking 100 accounts is roughly $750 vs $25,000.
Is engagement velocity a better metric than total engagement count?
For predicting reach and detecting viral content, yes. Engagement velocity (likes/minute in the first 15-30 minutes after a tweet posts) is a leading indicator of viral reach; the exact strength of correlation depends on account category and is best calibrated against your own observed data. For final-reach reporting (after 24h+), total engagement count is what you'd quote; for real-time monitoring and alerting, engagement-velocity is the metric to optimize for.
What happens when a tracked account gets suspended?
user/info returns 404. Treat this as state, not error — log an account_suspended event in your pipeline, back off polling (e.g., once-per-hour heartbeat check), and resume the normal poll cadence when the handle resolves again. The runnable Python in this guide handles this branch.
Can I get historical account-view data for accounts I don't own?
Only as engagement metrics on tweets (via advanced_search with from:handle since:YYYY-MM-DD until:YYYY-MM-DD). Per-tweet impressions for non-owned accounts are not exposed in the public API; only X's own analytics dashboard shows that for the account owner. For 'how visible was this account historically', you reconstruct from engagement-velocity + mention-volume over time, not from a single 'views' field.
Is account-view tracking compliant with X's Terms of Service?
Tracking engagement metrics on public tweets via the public X API (official or third-party) is governed by the API's Terms of Service. Public-data access for public posts is allowed. What's NOT allowed: scraping logged-out analytics dashboards, inferring per-viewer identity from indirect signals, or reverse-engineering private platform endpoints. The pipeline in this guide stays within the public-API surface; downstream commercial products should consult counsel on their jurisdiction's data-protection regulations.
Continue
- X API — TwitterAPI.io coverage hub
- Monitoring Twitter via API — the broader real-time tracking patterns
- Twitter monitoring — architecture patterns beyond single-account tracking
- X API cost breakdown — per-call rate math at scale
- Twitter analytics API guide — broader analytics integration
- TwitterAPI.io pricing — per-call rates
Stop reading. Start building.
Starter credits cover real testing on real data. Google sign-in, no card, no application queue.
Get an API key