Add web search to a Grok API request
Add web search to a Grok API request
Pass web_search on POST https://api.x.ai/v1/responses. xAI runs the search on its servers and returns the answer plus source URLs. You need a key and credits at console.x.ai.
Minimal call
export XAI_API_KEY="your_api_key"
curl https://api.x.ai/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $XAI_API_KEY" \
-d '{
"model": "grok-4.6",
"input": [
{
"role": "user",
"content": "What did xAI ship in the last 7 days? Cite the pages."
}
],
"tools": [
{ "type": "web_search" }
]
}'
Python with the official SDK:
import os
from xai_sdk import Client
from xai_sdk.chat import user
from xai_sdk.tools import web_search
client = Client(api_key=os.getenv("XAI_API_KEY"))
chat = client.chat.create(model="grok-4.6", tools=[web_search()])
chat.append(user("What did xAI ship in the last 7 days? Cite the pages."))
for response, chunk in chat.stream():
if chunk.content:
print(chunk.content, end="", flush=True)
print("\nCitations:", response.citations)
Narrow the search
You can set one of these on the tool, not both:
allowed_domains— search and browse only those hosts (max 5).excluded_domains— skip those hosts (max 5).
OpenAI-compatible clients put the list under filters:
{
"type": "web_search",
"filters": { "allowed_domains": ["docs.x.ai"] }
}
enable_image_search lets Grok pull images and embed them as Markdown. enable_image_understanding lets it inspect images it finds while browsing. Those are two different flags.
Pitfalls
- Tool calls are billed on tokens plus invocations. One question can fire several searches.
allowed_domainsandexcluded_domainscannot share a request.- Citations come back on the response. Open the URLs before you act on a number.
- Console API credits are a separate bill from SuperGrok's weekly pool on grok.com.