Call the xAI Grok API with live X Search
Grok's API can search X live and answer with links to the posts it read. This guide makes that call from Python, narrows it to the accounts and dates you care about, pulls out the sources, and shows the fetch counts so you know what each request costs.
- Time
- About 25 minutes
- Checked
If a button name on the screen does not match this guide, follow the action. These products rename buttons often. This is an advanced guide: it uses code, and each technical term is explained the first time it appears. Model names and prices change, so check the linked docs before you ship.
Steps
Know what X Search does
On its own, the API model only knows what was in its training data. X Search is a server-side tool: you list it in your request, and xAI's servers run the searches for you. Grok decides which searches to run (keyword, semantic, user lookup, or fetching a whole thread), reads the posts, and answers with links to them. You don't write a tool loop like you would for your own functions.
It costs money beyond tokens. When this was checked, xAI billed X Search at $5 per 1,000 posts fetched and $10 per 1,000 user profiles fetched, plus normal token costs. Step 6 shows how to see and limit that.
Install the SDK and set your key
xAI's Responses API works with the OpenAI Python library pointed at xAI's address. Create a key in the xAI Console under API keys, then:
python3 -m venv .venv && source .venv/bin/activate pip install openai export XAI_API_KEY="your-key-here"Keep the key out of your code and out of Git.
Make your first X Search call
Add
{"type": "x_search"}totools. Save this asxsearch.pyand runpython xsearch.py.import os from openai import OpenAI MODEL = "grok-4.7" client = OpenAI(api_key=os.environ["XAI_API_KEY"], base_url="https://api.x.ai/v1") response = client.responses.create( model=MODEL, input="What are people on X saying about [your topic] this week? Give 3 bullet points.", tools=[{"type": "x_search"}], ) print(response.output_text)Replace
[your topic]. The answer usually includes inline links in the form[[1]](https://x.com/...)that point to the posts Grok used.Narrow it to certain accounts and dates
Unfiltered searches can wander and fetch lots of posts. Add filters to the tool:
tools = [{ "type": "x_search", "allowed_x_handles": ["xai", "SpaceX"], # no @, up to 20 "from_date": "2026-10-01", # YYYY-MM-DD "to_date": "2026-10-17", # not included }]allowed_x_handleskeeps only posts from those accounts.excluded_x_handlesdoes the opposite. You can't use both in one request.- Dates cover 00:00 UTC on
from_dateup to, but not including,to_date. To search one day, setto_dateto the next day. Any other date format, such as a full timestamp, is ignored, so double-check it. - The handle and date filters apply to every keyword and semantic search Grok runs. They don't apply when Grok fetches a thread.
Pull out the sources
Use the cited posts to show sources in your app or to check the answer. Each text block carries annotations: structured citations with the URL and where the link sits in the text.
for item in response.output: if item.type == "message": for block in item.content: if block.type == "output_text": for a in block.annotations or []: print(f"[{a.title}] {a.url}")The response also has a full
citationslist of every source Grok looked at, including ones it decided not to use. You can see it withresponse.model_dump().get("citations").Watch and cap the cost
Each response says how much it fetched. Cap the number of search rounds with
max_turns, which the OpenAI library sends throughextra_body:response = client.responses.create( model=MODEL, input="What did xAI post about the API this month?", tools=[{"type": "x_search", "allowed_x_handles": ["xai"], "from_date": "2026-10-01", "to_date": "2026-10-18"}], extra_body={"max_turns": 2}, ) details = response.usage.model_dump()["server_side_tool_usage_details"] print("searches:", details["x_search_calls"]) print("posts fetched:", details["x_posts_fetched"]) print("profiles fetched:", details["x_users_fetched"])The counts are not de-duplicated, so a post that shows up in two searches counts twice. Log these numbers for every call, the same way you'd log tokens.
Check the answer against the posts
Open two or three of the cited links and confirm the posts say what Grok claims, and that their dates fall inside your range. If the answer has no X links at all, treat it as unsourced: Grok may have answered from memory because the filters were too narrow. Loosen the dates or handles and try again.
Tips
Keep the model name in one constant.
grok-4.7was xAI's recommended model when this was checked; their models page lists the current names.If you only need an answer and not code, the Grok app can search X for you with no API key. See the guide on researching real-time trends with Grok.
Add
{"type": "web_search"}next tox_searchwhen you want news sites as well as posts. Each tool has its own filters.Image and video understanding (
enable_image_understanding,enable_video_understanding) let Grok look at media in posts, billed as image tokens. Leave them off unless you need them.
Common questions
Do I need an X account or the X API?
No. X Search runs on xAI's side with your xAI API key. You don't need X developer access.
Why does the same question return different posts each time?
Grok writes its own search queries, so results vary from run to run. Filters on handles and dates make them more consistent.
Can I use the xAI Python SDK instead of the OpenAI library?
Yes. xAI's own xai_sdk has an x_search() tool with the same filters. One difference: inline citations are on by default in the Responses API but off by default in xAI's SDK, where you turn them on with include=["inline_citations"].
How much will this cost me?
It depends on how many posts Grok fetches, plus tokens. Run a few calls, read the fetch counts from Step 6, and multiply by the current price on xAI's pricing page. Prices change, so check before you build anything that runs on a schedule.
More guides
BeginnerGrokGetting started
Get started with Grok: ask about what's happening now
Open Grok on the web or in X, ask a first question, and use its live search to get current answers with sources you can check.
About 10 minutes using Grok
IntermediateGrokResearch
Research real-time trends on X with Grok
Use Grok's live X and web search to track a topic, compare opinions, and get a sourced summary you can verify before you act on it.
About 20 minutes using Grok
AdvancedClaudeBuilding
Call the Claude API in Python and cut costs with prompt caching
Get an API key, make your first Claude Messages API call in Python, then add prompt caching so repeated long prompts cost less and run faster.
About 30 minutes using Claude Console, Claude API docs