X AI Search API
Returns a written answer to a plain-English question about X (Twitter), the X posts cited as sources, and how many searches the model ran.
GET /v1/twitter/ai-searchLast updated November 2026Maintained by the SocialCrawl team
When to use the X AI Search API
Use it for open questions about what an account said this week. If your client stops at 30 seconds, send Prefer: respond-async. A thin answer means thin retrieval, so confirm with search/tweets.
From the API reference
Natural-language search over X (Twitter) powered by xAI's Grok 4.3 model with the built-in x_search tool. Returns a synthesised answer plus X source citations. Pin results to specific authors via from_handles (or exclude with exclude_handles), and narrow to a time window with from_date / to_date. Costs 5 credits per call regardless of how many internal x_search invocations the model performs (see tool_calls_count in the response for visibility). Auto-refunds on upstream failure. Best for freeform questions like 'what is @elonmusk saying about xAI this week' that would otherwise require multiple structured calls to /v1/twitter/profile, /v1/twitter/user/tweets, etc. **Read a thin answer as thin retrieval, never as an empty corpus.** This is a discovery surface: the model runs a handful of internal searches and answers from what they returned, so a reply such as 'limited posts appear on this topic' is a statement about that retrieval, not about X. Keyword search over the same window routinely finds substantially more. A call usually takes 10 to 30 seconds. About a quarter of calls take longer, up to about a minute on broad prompts with several keywords, so set a client timeout of at least 100 seconds. If your client or agent gives up at 30 seconds, send Prefer: respond-async (or add async=true to the query) and poll GET /v1/prism/jobs/{job_id}. As a job, the call costs the same 5 credits and keeps its 90-second budget. If you need the posts rather than a written answer, /v1/twitter/search/tweets lists them in about 2 seconds for 1 credit a page. An identical request repeated within 30 minutes is answered from cache, free, so re-sending the same question more often than that returns the same answer.
Searching 69 platforms in parallel
What can you do with the AI Search API?
The AI Search endpoint gives you structured X data with computed fields in a single request. No scraping infrastructure to build or maintain.
Example Request
# GET /v1/twitter/ai-search: 5 credits per call. Cache hits are free and failed calls are refunded.
# Check the price first for 0 credits: add dry_run=1 to the query. Nothing is fetched or charged.
# --max-time 80: this endpoint's measured p99 latency x 1.5.
# --retry 3: retries timeouts, 429 and 5xx, honoring Retry-After.
# -o response.json keeps only the final attempt's body.
# One Idempotency-Key per request, reused on every retry, so a retried call is never charged twice.
IDEMPOTENCY_KEY=$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')
curl -sS --max-time 80 --retry 3 -o response.json \
-H "x-api-key: YOUR_API_KEY" \
-H "Idempotency-Key: $IDEMPOTENCY_KEY" \
"https://www.socialcrawl.dev/v1/twitter/ai-search?query=What+is+%40elonmusk+saying+about+xAI+this+week%3F" && cat response.json# GET /v1/twitter/ai-search: 5 credits per call. Cache hits are free and failed calls are refunded.
# Check the price first for 0 credits: add dry_run=1 to the query. Nothing is fetched or charged.
import os
import random
import time
import uuid
import requests
API_KEY = os.environ.get("SOCIALCRAWL_API_KEY", "YOUR_API_KEY")
TIMEOUT_S = 80 # this endpoint's measured p99 latency x 1.5.
MAX_RETRIES = 3
URL = "https://www.socialcrawl.dev/v1/twitter/ai-search"
def backoff(attempt):
# Exponential backoff with jitter: about 1 s, 2 s, then 4 s.
return 2 ** attempt * (0.5 + random.random() / 2)
def socialcrawl(params):
# One Idempotency-Key per request, reused on every retry, so a retried call is never charged twice.
idempotency_key = str(uuid.uuid4())
for attempt in range(MAX_RETRIES + 1):
try:
res = requests.get(
URL,
params=params,
headers={"x-api-key": API_KEY, "Idempotency-Key": idempotency_key},
timeout=TIMEOUT_S,
)
body = res.json()
except (requests.RequestException, ValueError):
# A timeout, a dropped connection or a non-JSON gateway page: retry with the same key.
if attempt == MAX_RETRIES:
raise
time.sleep(backoff(attempt))
continue
if body["success"]:
return body
error = body["error"]
# Branch on error["type"], never on the message text.
if error["type"] == "RESOURCE_NOT_FOUND":
return None # refunded: nothing to read
retry_after = res.headers.get("Retry-After")
# SERVICE_UNAVAILABLE without Retry-After is a withdrawn endpoint: permanent.
permanent = error["type"] == "SERVICE_UNAVAILABLE" and retry_after is None
if not error.get("retryable") or permanent or attempt == MAX_RETRIES:
raise RuntimeError(f"{error['type']}: {error['message']} (request_id {body['request_id']})")
# Retry-After (seconds) wins; otherwise back off.
time.sleep(float(retry_after) if retry_after else backoff(attempt))
params = {
"query": "What is @elonmusk saying about xAI this week?",
}
body = socialcrawl(params)
if body is not None:
print(body["data"])// GET /v1/twitter/ai-search: 5 credits per call. Cache hits are free and failed calls are refunded.
// Check the price first for 0 credits: add dry_run=1 to the query. Nothing is fetched or charged.
const API_KEY = process.env.SOCIALCRAWL_API_KEY ?? "YOUR_API_KEY";
const TIMEOUT_MS = 80_000; // this endpoint's measured p99 latency x 1.5.
const MAX_RETRIES = 3;
type Page = { next_cursor: string | null; has_more: boolean };
type SocialCrawlResponse =
| { success: true; data: any; pagination?: Page; credits_used: number; request_id: string }
| { success: false; error: { type: string; message: string; retryable: boolean }; request_id: string };
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
// Exponential backoff with jitter: about 1 s, 2 s, then 4 s.
const backoffMs = (attempt: number) => 2 ** attempt * 1000 * (0.5 + Math.random() / 2);
async function socialcrawl(url: URL) {
// One Idempotency-Key per request, reused on every retry, so a retried call is never charged twice.
const idempotencyKey = crypto.randomUUID();
for (let attempt = 0; ; attempt++) {
let res: Response;
let body: SocialCrawlResponse;
try {
res = await fetch(url, {
headers: {
"x-api-key": API_KEY,
"Idempotency-Key": idempotencyKey,
},
signal: AbortSignal.timeout(TIMEOUT_MS),
});
body = (await res.json()) as SocialCrawlResponse;
} catch (error) {
// A timeout, a dropped connection or a non-JSON gateway page: retry with the same key.
if (attempt >= MAX_RETRIES) throw error;
await sleep(backoffMs(attempt));
continue;
}
if (body.success) return body;
// Branch on error.type, never on the message text.
if (body.error.type === "RESOURCE_NOT_FOUND") return null; // refunded: nothing to read
const retryAfter = res.headers.get("Retry-After");
// SERVICE_UNAVAILABLE without Retry-After is a withdrawn endpoint: permanent.
const permanent = body.error.type === "SERVICE_UNAVAILABLE" && retryAfter === null;
if (!body.error.retryable || permanent || attempt >= MAX_RETRIES) {
throw new Error(`${body.error.type}: ${body.error.message} (request_id ${body.request_id})`);
}
// Retry-After (seconds) wins; otherwise back off.
await sleep(retryAfter ? Number(retryAfter) * 1000 : backoffMs(attempt));
}
}
const url = new URL("https://www.socialcrawl.dev/v1/twitter/ai-search");
url.searchParams.set("query", "What is @elonmusk saying about xAI this week?");
const body = await socialcrawl(url);
if (body) console.log(body.data);Parameters
| Parameter | Required | Description |
|---|---|---|
| query | Yes | Natural-language prompt describing what you want to learn from X. The model autonomously searches X using the x_search tool with any handle / date filters you provide. |
| from_handles | No | Comma-separated X handles (max 10). Restricts the search to posts from these accounts only. Mutually exclusive with exclude_handles. |
| exclude_handles | No | Comma-separated X handles (max 10) to exclude from search results. Mutually exclusive with from_handles. |
| from_date | No | ISO 8601 start date (YYYY-MM-DD). Limits the search window to posts on or after this date. |
| to_date | No | ISO 8601 end date (YYYY-MM-DD). Limits the search window to posts on or before this date. |
What does the X AI Search API return?
This example shows the endpoint's response shape and fields. Values are illustrative; this is not a live capture.
Example response
{
"success": true,
"platform": "twitter",
"endpoint": "/v1/twitter/ai-search",
"data": {
"answer": "Elon Musk recently posted about xAI's new reasoning model, highlighting its real-time X search capability...",
"sources": [
{
"url": "https://x.com/user_58cc83/status/1234567890",
"title": "elonmusk on X"
}
],
"tool_calls_count": 1
},
"credits_used": 5,
"credits_remaining": 95,
"request_id": "req-a1b2c3d4e5f6",
"cached": false
}Illustrative fixture for the documented response shape. Values are examples, not a production capture.
How does the X AI Search API work?
Send a GET request with your API key and get back clean, structured JSON in our unified schema. Supported computed fields are populated when the source provides the required inputs.
Method
GET
Response
JSON
How do you scrape social media data in seconds?
The fastest social media scraping API for developers. Scrape profiles, posts, comments, and analytics from 69 platforms covering 10B+ monthly active users.
One schema, every platform
Query 69 platforms with identical response structures. Write your integration once.
Computed fields, not just scraped
When an endpoint supports these metrics and the source provides the required inputs, the normalized record includes engagement_rate, estimated_reach, content_category, and language. Ready to use.
See your data before you code
Visual Data Explorer. Paste any URL, get rich result cards, sortable tables, CSV export.
import requests
response = requests.get(
'https://www.socialcrawl.dev/v1/tiktok/profile',
params={'handle': 'charlidamelio'},
headers={'x-api-key': 'sc_YOUR_API_KEY'}
)
data = response.json(){
"success": true,
"platform": "tiktok",
"data": {
"author": {
"username": "charlidamelio",
"followers": 152400000
},
"engagement": {
"likes": 12400000000,
"engagement_rate": 0.087
},
"metadata": {
"language": "en",
"content_category": "lifestyle"
}
}
}Have a question? We got answers
Find answers to frequently asked questions about SocialCrawl's API, pricing, and capabilities.
Contact usWhat is the Twitter AI Search API?
How is AI search different from regular tweet search?
Can I scope the Twitter AI search to specific accounts or dates?
Which model powers Twitter AI search?
How much does the Twitter AI Search API cost?
Ask AI about SocialCrawl
Ready to scrape X AI Search data?
Get your API key and start pulling X data in under 60 seconds.
