The xAI API is the right choice when you want to pick a model per request, run jobs from scripts, or pay only for what you use. It is the wrong choice if you mainly chat in the app and never write code. This lesson gets you from zero to a working call and shows what that call costs.
When the API beats the subscription
- Your usage is bursty: heavy some weeks, nothing in others.
- You need bulk processing: classification, extraction, summaries at scale.
- You want the cheapest model per task rather than one default model.
- You are building something other people will use.
Get a key
Sign up at the xAI developer console, create an API key, and add a payment method. Store the key in an environment variable named XAI_API_KEY. Never paste it into a chat or commit it to a repository.
First call with curl
The API is OpenAI-compatible. The base URL is https://api.x.ai/v1 and the chat endpoint is /chat/completions. Model ids follow the catalogue names, for example grok-4-fast.
curl https://api.x.ai/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $XAI_API_KEY" \
-d '{
"model": "grok-4-fast",
"messages": [
{"role": "system", "content": "You are a concise assistant. Plain prose, no jokes."},
{"role": "user", "content": "Summarise the pros and cons of prepaid API credits in three bullets."}
],
"max_tokens": 200
}'The same call in Python
Because the API is OpenAI-compatible, you can use the official openai Python package and point it at xAI's base URL. Nothing else in your code has to change.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.x.ai/v1",
api_key=os.environ["XAI_API_KEY"],
)
resp = client.chat.completions.create(
model="grok-4-fast",
messages=[
{"role": "system", "content": "You are a concise assistant. Plain prose, no jokes."},
{"role": "user", "content": "Summarise the pros and cons of prepaid API credits in three bullets."},
],
max_tokens=200,
)
print(resp.choices[0].message.content)
u = resp.usage
cost = u.prompt_tokens * 0.20 / 1_000_000 + u.completion_tokens * 0.50 / 1_000_000
print(f"input={u.prompt_tokens} output={u.completion_tokens} est_cost=${cost:.6f}")The last three lines read the usage object and estimate cost with the Grok 4 Fast prices from our catalogue. Log this on every call while you are learning. It turns "the API is cheap" from a belief into a number.
Cached input
xAI publishes a discounted cached input price on its official pricing page. We do not quote it here because it is not in our catalogue; check x.ai for the current figure. To benefit, keep long system prompts and reference documents at the start of the message list, byte-for-byte identical between calls, and put the user's question at the end.
Knowledge check
Why does putting a long, unchanging system prompt first in the message list reduce cost on the xAI API?