Grok 4
Xai • OpenAI-compatible REST (Chat Completions) and Anthropic-compatible Messages
xai
Grok 4
Model ID
grok-4Endpoints
base_url
https://api.x.ai/v1chat_completions
/chat/completionsmessages
/messagesInstall
Node
— use fetch/axios or a community provider (e.g. @ai-sdk/xai)Python
pip install requests # (or use the xAI Python SDK if preferred)Environment
api_key
XAI_API_KEYCode examples
JavaScript
const resp = await fetch("https://api.x.ai/v1/chat/completions", {\n method: "POST",\n headers: {\n "Authorization": `Bearer ${process.env.XAI_API_KEY}` ,\n "Content-Type": "application/json"\n },\n body: JSON.stringify({\n model: "grok-4",\n messages: [{ role: "user", content: "Write a 3-line haiku about sunrise over London." }]\n })\n});\nconst data = await resp.json();\nconsole.log(data.choices?.[0]?.message?.content);Python
import os, requests\nheaders = {\n "Authorization": f"Bearer {os.environ['XAI_API_KEY']}",\n "Content-Type": "application/json"\n}\npayload = {\n "model": "grok-4",\n "messages": [{"role": "user", "content": "Write a 3-line haiku about sunrise over London."}]\n}\nr = requests.post("https://api.x.ai/v1/chat/completions", headers=headers, json=payload)\nprint(r.json()["choices"][0]["message"]["content"])Documentation
Notes
xAI’s REST is OpenAI-compatible for Chat Completions, and they also offer an Anthropic-compatible Messages endpoint. Use model id "grok-4".