OverpayingForAIPricing desk

Lesson 7 of 8 · 10 min read · Beginner → Intermediate

xAI API quickstart

When the API beats a subscription, how to call it with an OpenAI-compatible client in curl and Python, and how tokens and cached input affect the bill.

In this lesson you will

  • Decide when the xAI API is cheaper than a Grok subscription
  • Make a first chat completion call with curl and with the OpenAI Python client
  • Explain how tokens, context, and cached input drive the API bill

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.
Tokens and the context windowA token is roughly ¾ of an English word. The context window is the maximum tokens the model can hold at once — everything you send plus everything it writes.System prompt + instructionsConversation history + documentsNew answerfreeWhy it costs moneyEvery turn re-sends the whole history. A 40-message chat with a pasted PDF bills that PDF 40 times unless the provider caches it.“1M context” is a ceiling, not a target. Filling it on every request is the fastest way to overpay.rule of thumb: 1,000 tokens ≈ 750 words ≈ 1.5 pages
Figure 1.Everything you send is input tokens; everything the model writes is output tokens. Output usually costs more per token, and the whole conversation history counts as input on every turn.

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.

bashMinimal chat completion with curl
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.

pythonPython with the OpenAI client pointed at xAI
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

Prompt caching: stop paying full price for the same prefixIf the start of your request is identical each time (system prompt, docs, tool list), the provider can serve it from cache at a fraction of the input price.Request 1Stable prefix — written to cache (full price)new questionRequest 2Stable prefix — cache hit (discounted)new questionRequest 3Stable prefix — cache hit (discounted)new questionRule: put the unchanging parts first, the changing parts last. A timestamp at the top of a system prompt silently kills the cache on every call.
Figure 2.When the start of your prompt is identical across calls, the provider can reuse its work and charge a lower cached-input rate for those tokens. Put the stable material first and the changing part last.

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?

Lesson FAQ

Do I need a special SDK for the xAI API?

No. Because it is OpenAI-compatible you can use the official OpenAI client in Python or JavaScript with the base URL set to https://api.x.ai/v1. xAI also documents its own SDKs on the console site.

Which model id should I start with?

Start with the fast tier, for example grok-4-fast. It is the cheapest row in our catalogue. Confirm the exact current id list in the xAI console, since ids change with releases.

Can I use the same key from the app?

No. App subscriptions and API keys are separate products with separate billing.

Finished reading?

Mark it done to track your progress through the course.

Compare, calculate, decide — for Grok

If our calculators helped you cut down on hidden AI wallet leaks, consider buying us a coffee. A tiny fraction of your savings keeps our pricing indexes updated daily.

Not sure which AI is cheapest for your use case? Find out in 30 seconds — no signup required.

AI cost intelligence

Stop overpaying for AI tools

Join the OverpayingForAI list for pricing updates, cheaper alternatives, and practical buying guidance.

Now tracking 50+ AI tools, models, platforms, subscriptions, coding tools, and automation products.

We use your email only for OverpayingForAI updates. Unsubscribe anytime.