xAI Grok API key setup

Published 2026-10-07 · Updated 2026-10-22

xAI keys are easy to spot: xai- followed by 80 letters and digits, 84 characters in all, one of the longest key formats out there. The API itself is OpenAI-compatible, so the setup is short.

Export the key

export XAI_API_KEY="xai-..."

XAI_API_KEY is the name the docs and most tooling look for.

Test it with curl

curl https://api.x.ai/v1/models \
  -H "Authorization: Bearer $XAI_API_KEY"

A model list means the key is good. From there it’s standard chat completions:

curl https://api.x.ai/v1/chat/completions \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-5-mini",
    "messages": [{"role": "user", "content": "Say hello"}]
  }'

With the OpenAI SDK

from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ["XAI_API_KEY"],
    base_url="https://api.x.ai/v1",
)

resp = client.chat.completions.create(
    model="grok-5-mini",
    messages=[{"role": "user", "content": "Say hello"}],
)
print(resp.choices[0].message.content)

Same pattern in Node: new OpenAI({ apiKey, baseURL: "https://api.x.ai/v1" }).

Notes

If you’re migrating OpenAI code, the only real change is base_url, everything else, including streaming and tool calling, maps one-to-one.