X/Twitter Public Data API | SandBase
Read one X/Twitter profile by handle or exact ID, validate notfound and identity, and distinguish two routes, prices and historical examples.

An account lookup should start with the identifier you selected, not a chain of searches, tweets and follower requests. If you know a handle, Web User Profile is one option. If you have an exact numeric account ID as a string, User Detail is a separately priced option with a different request key. They share authentication, but their input types and reference examples are not interchangeable.
This 2026-11-08 repair focuses on those two first requests. It uses free inspect and public reference material without making a new business call. The wider X/Twitter catalog remains navigation below, not a fresh verification of every search, timeline or social-graph endpoint. Existing keyword research and monitoring articles are separate tasks.
Key takeaway
- Web User Profile accepts screen_name as a string or rest_id as an integer. Choose one; an ID overrides the handle when both are supplied.
- User Detail instead requires camel-case restId as a decimal string. Do not copy the other route’s spelling or type.
- A completed SandBase envelope can contain a notfound business result. Missing identity is not a successful empty profile.
- Keep raw counters and flags. A snapshot does not measure growth, and a badge does not independently verify identity or partnership.
The retained cover is conceptual artwork. Its fictional SandBase account, badge, 128.7K followers and trend figures are not account evidence or measured results. The visual claims of real-time reliability are not verified by this repair.
Select the identifier and price deliberately
| What you have | Current endpoint | First request |
|---|---|---|
| A selected handle such as NASA | Web User Profile | screen_name string |
| A selected exact integer ID for the web route | Web User Profile | rest_id integer, no screen_name |
| An exact numeric account ID retained as text | User Detail | restId string, with a capital I |
The web schema marks both properties individually optional, but an empty body does not select an account. Its description explicitly gives rest_id precedence over screen_name. Sending a handle next to an unrelated saved ID can therefore look like a lookup of one account while selecting another. The new helper rejects that combination locally.
For User Detail, the exact ID string is required. A handle, URL, float or already rounded JavaScript Number is not a substitute. Python integers retain arbitrary precision, but a JavaScript client should reject unsafe integer input before serialization. Converting an already rounded Number to a string cannot restore the original ID. Returned IDs should stay strings in your records even when the web request uses an integer.
Historical X/Twitter catalog screenshot. Its displayed endpoint count, price labels and GET catalog paths are navigation context, not a new execution check for these POST requests. Its old user-post-tweet reading label is not a safe read-only calling instruction.
Reuse your setup and stop after one response
Already have SANDBASE_API_KEY? Reuse its environment or secret-manager configuration. An already connected agent needs the identifier, selected route and desired result, not your key pasted into chat or another signup. For a new project, provide the setup Skill, Markdown quickstart and the chosen API link. The human quickstart explains account setup.
A concrete instruction is: “Read one public profile for this selected handle through Web User Profile. Validate the business identity, retain optional values unchanged, and stop after one response. If it is notfound, report that outcome without switching to another endpoint.” Selecting User Detail should be a separate decision because its price differs.
Install requests in your Python environment. The example uses local guards for a bare ASCII handle of one to fifteen characters and positive decimal IDs. Those are explicit first-request restrictions; the registry defines the handle as a string and the web ID as an integer rather than this exact regular expression. The code does not scrape a profile URL or guess an ID from a name.
import os
import re
import requests
API = "https://api.sandbase.ai/v1/api/twitter"
ID_PATTERN = r"[1-9][0-9]*"
def first_request(task, *, screen_name=None, rest_id=None, restId=None):
expected_id = None
if task == "web":
if restId is not None or (screen_name is None) == (rest_id is None):
raise ValueError("Choose exactly one web screen_name or integer rest_id")
if screen_name is not None:
if not isinstance(screen_name, str) or not re.fullmatch(r"[A-Za-z0-9_]{1,15}", screen_name):
raise ValueError("Provide a bare selected handle, not a URL or @handle")
payload = {"screen_name": screen_name}
else:
if type(rest_id) is not int or rest_id <= 0:
raise ValueError("Web rest_id must be a positive integer")
expected_id = str(rest_id)
payload = {"rest_id": rest_id}
route = "web/user-profile"
elif task == "detail":
if screen_name is not None or rest_id is not None:
raise ValueError("User Detail accepts only camel-case restId")
if not isinstance(restId, str) or not re.fullmatch(ID_PATTERN, restId):
raise ValueError("User Detail restId must be an exact positive decimal string")
expected_id = restId
payload, route = {"restId": restId}, "user-detail"
else:
raise ValueError("Choose web or detail")
key = os.environ.get("SANDBASE_API_KEY", "").strip()
if not key:
raise ValueError("Set SANDBASE_API_KEY in your environment")
try:
response = requests.post(
f"{API}/{route}",
headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
json=payload, timeout=(10, 90), allow_redirects=False,
)
if not 200 <= response.status_code < 300:
raise RuntimeError(f"SandBase HTTP {response.status_code}; request stopped")
body = response.json()
except requests.RequestException:
raise RuntimeError("Network request failed; inspect locally before another call") from None
except ValueError:
raise RuntimeError("SandBase returned invalid JSON") from None
if not isinstance(body, dict) or body.get("status") != "completed":
raise RuntimeError("SandBase request did not complete")
outputs = body.get("outputs")
if not isinstance(outputs, list) or not outputs or not isinstance(outputs[0], dict):
raise RuntimeError("Missing documented outputs[0]")
data = outputs[0].get("data")
if not isinstance(data, dict):
raise RuntimeError("Missing documented outputs[0].data object")
if data.get("status") == "notfound":
raise RuntimeError("Profile not found; no fallback request made")
identities = [data[k] for k in ("rest_id", "id") if data.get(k) is not None]
if (not identities or any(not isinstance(v, str) or not re.fullmatch(ID_PATTERN, v) for v in identities)
or len(set(identities)) != 1):
raise RuntimeError("Missing, malformed or conflicting returned profile identity")
if expected_id is not None and identities[0] != expected_id:
raise RuntimeError("Returned profile ID does not match the selected ID")
if not isinstance(data.get("name"), str) or not data["name"].strip():
raise RuntimeError("Missing profile display name in the reference shape")
return data
if __name__ == "__main__":
result = first_request("web", screen_name="NASA")
print("Received fields:", sorted(result))To choose an integer web ID, replace the main assignment with result = first_request("web", rest_id=11348282). For User Detail, use result = first_request("detail", restId="44196397"). Replace the line rather than appending calls. The helper does not retry, follow redirects, silently change routes, open media links or retrieve pinned posts.
The response checks use the flat reference fields directly under outputs[0].data. There is no additional user object or data.data layer. The helper accepts a usable string id or rest_id, rejects conflicting returned IDs and compares an ID-based request against the returned identity. It also requires the display-name shape seen in the available references. These conservative checks stop on a changed structure instead of turning it into a successful empty record.
A handle-based request has a different limitation: the shortened reference does not expose a separate guaranteed echoed screen_name. Keep the requested handle alongside the returned exact ID, rather than treating matching display names as independent proof of account identity. The optional profile field is described differently across the two references, so do not use one shared assumption about it to join unrelated accounts.
The saved web example is a real negative result
The public saved Web User Profile example has ID dab93362-96dc-4d35-a50a-9036130ee4ba, created_at 2026-08-20T07:25:01.103Z. Its input snapshot is an empty object. The business response reports status notfound with null identity and counter fields. This trimmed projection preserves that outcome:
{
"status": "notfound",
"id": null,
"rest_id": null,
"name": null,
"sub_count": null,
"statuses_count": null
}It is negative evidence, not a successful NASA lookup. Changing the teaching request to screen_name NASA does not retroactively change what the saved empty-input request did. A completed SandBase status only says the wrapper completed; it cannot turn notfound into a usable account record. The offline test deliberately feeds this saved business result into the parser and expects rejection, without another network call.
The shortened NASA-shaped README response is a separate, undated reference. It shows flat id and name fields, an affiliates array and a business_account object. That supports the selected field paths, not a newly executed successful handle lookup. In particular, it is not the complete saved response above with null values replaced by assumed defaults.
Historical Web User Profile parameter reference. It shows screen_name and integer rest_id; its old model-only request, empty data response and illustrative IDs are not the current runnable example or a measured NASA response.
User Detail has a reference shape, not a full saved example
The inspected User Detail page has no full saved example. Its README labels a shortened response as real, with an id string, display name and other flat profile fields, but gives no execution timestamp. Treat it as a reference fragment rather than a new account read. Its request uses restId, preserving the capital I and string type.
That reference shows an affiliates object with an organization label, while the web reference shows an array; its business_account is null, while the web example shows an object. Do not force both into one invented nested schema. Preserve optional structures and document the route if your application later maps them. A successful parser check against a fragment is not evidence of a successful live request or a complete response.
The response descriptions distinguish sub_count as followers and friends as accounts followed. Keep the field names, raw values and observation time. statuses_count and media_count describe different totals, not campaign results or reach. A single profile snapshot cannot show growth. Missing counters stay unknown rather than zero, and null flags do not become false merely to simplify a dashboard.
created_at describes account creation, not the time you observed it. Location is free text rather than verified geography. desc can contain a shortened link instead of a complete bio; the helper does not open it automatically. A verification flag or organization label is a displayed signal, not independent proof of payment, identity or a partnership. Protected-state metadata does not grant access to protected posts or direct messages.
Preserve the old illustration without calling it a test
The original article used the following illustrative envelope with ID 13a394de-55e6-4c72-b0b1-604007a3757d. Its NASA values were presented as example structure, not a verified run. This JSON is preserved unchanged; it is not a current counter measurement or evidence that the empty saved web request succeeded:
{
"id": "13a394de-55e6-4c72-b0b1-604007a3757d",
"status": "completed",
"model": "twitter/web/user-profile",
"outputs": [
{
"data": {
"name": "NASA",
"rest_id": "11348282",
"blue_verified": true,
"location": "Pale Blue Dot",
"friends": 115,
"statuses_count": 74334,
"created_at": "Wed Dec 19 20:20:32 +0000 2007"
}
}
]
}The old Python and curl blocks are preserved verbatim in the historical code archive. They did not perform the new explicit business-result and identity checks. The bounded helper above is the current first-request example; the illustration remains a record of the previous article.
Wider catalog: separate tasks
The following map is retained navigation from the original hub. Only the two profile routes are checked in this repair. Search, tweet detail, followers and trends require their own current input, response and cost review; a common envelope does not make their business schemas interchangeable.
| Capability | Historical navigation | Reader task |
|---|---|---|
| Search | twitter/web/search-timeline | Find candidate posts for a query |
| Tweet detail | twitter/web/tweet-detail | Read a selected post |
| Replies | twitter/web/post-comments | Inspect a selected discussion |
| Social graph | twitter/web/user-followers | Plan a separately scoped follower read |
| Trends | twitter/web/trending | Inspect a selected trend source |
Historical search-timeline parameter reference, not an endpoint-list screenshot. Search inputs and pagination belong to another task and were not executed in this repair.
Shared authentication gives your agent a consistent entry point, but every request still needs its own status and business validation. A profile read should not automatically become search-to-tweet-to-replies or a follower crawl. A pinned-post ID and an avatar URL are references, not content already fetched. Decide what additional evidence would answer the research question before making another call.
For account research, keep the requested identifier and exact returned ID, noting unresolved fields. For monitoring, follow the separate monitoring guide and recheck that task’s contract rather than appending it here. These selected reads do not post, send DMs, operate an account or provide private analytics. SandBase supplies an access layer and does not own X.
Price and failure outcomes
Free inspect checked on 2026-11-08 lists Web User Profile at USD 0.001 per call and User Detail at USD 0.014286. Both show eligibility for the organization’s shared 100 daily eligible-data-API calls, resetting at 00:00 UTC. Eligibility does not show remaining allowance, account balance or an actual charge, and it does not promise a free successful read. Independently choosing both is 0.015286 before quota effects; no automatic fallback is included.
Keep HTTP failure, incomplete wrapper, malformed payload and a business notfound result separate. They do not all mean the account disappeared, and none should silently become a blank successful profile. The helper stops without leaking keys or copying upstream response bodies into error text. A later retry or another route is a new decision with a reason and budget, not a hidden recovery action.
FAQ
Which ID spelling belongs to which route? Web User Profile uses integer rest_id. User Detail uses camel-case restId with a decimal string. Returned IDs remain strings; do not confuse request serialization with storage.
Can a completed wrapper still fail to provide a profile? Yes. The real saved empty-input web example is notfound with null identity. Check business fields before storing a successful record.
Does a badge verify the account for my research? It is a response signal, not an independent identity or partnership assessment. Preserve it without inferring payment history, reach or audience quality.
Should I switch routes after notfound? Not automatically. The routes have different inputs, references and prices. Report the result and separately choose any next request.
Are search and followers covered by this first request? No. The catalog map is navigation; these two selected tasks stop at one public profile response.
Start with one known account
Choose Web User Profile or User Detail using the identifier you actually have. Validate the business identity, preserve unknowns, and stop before expanding scope. The X/Twitter catalog can help identify a separately reviewed next task.
Found this useful? Share it