Grok API: calling Grok from your own code

Grok models are available to developers through xAI's own API and through model routers such as OpenRouter. Both speak the OpenAI format, so setup takes minutes.

5 min readUpdated

Two ways to reach Grok from code

Developers can call Grok models in two main ways. The first is the xAI API, run by the company itself (now branded SpaceXSI), with keys from console.x.ai. The second is a model router such as OpenRouter, which resells many providers' models behind one key and one bill. Both accept requests in the OpenAI Chat Completions format, so the official OpenAI SDKs work once you change the base address and the model name.

Grok.Online does not offer a public API. Our chat is for people in a browser. For your own apps, use one of the routes on this page.

Which route to pick

  • xAI API if you want every Grok feature first: the full list of models, the Responses API, server-side web search and X search tools, image and video generation with Grok Imagine, voice, batch jobs and cached-prompt discounts. Base URL https://api.x.ai/v1.
  • OpenRouter if you want to switch between Grok and models from other companies without new contracts, or already have an OpenRouter account. Base URL https://openrouter.ai/api/v1, model ids prefixed with x-ai/. Setup is in the OpenRouter quickstart.

Either way, keep the key on a server or in an environment variable. Never ship it inside a web page or a mobile app, where anyone can read it.

Your first request to the xAI API

Create a key in the console, save it as XAI_API_KEY, and send a message to Grok 4.7:

curl

curl https://api.x.ai/v1/chat/completions \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-4.7",
    "reasoning_effort": "low",
    "messages": [
      {"role": "system", "content": "You are a concise assistant."},
      {"role": "user", "content": "Give me three tips for a first marathon."}
    ]
  }'

Python, with the OpenAI library

import os
from openai import OpenAI

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

answer = grok.chat.completions.create(
    model="grok-4.3",
    reasoning_effort="medium",
    messages=[{"role": "user", "content": "Is 391 a prime number? Show your check."}],
)
print(answer.choices[0].message.content)

reasoning_effort controls how long the model thinks before replying. Grok 4.3 accepts none, low, medium, high and xhigh and defaults to low; Grok 4.7 accepts low, medium, high and xhigh and defaults to high. For Grok 4.20, xAI publishes separate ids: grok-4.20-0309-reasoning and grok-4.20-0309-non-reasoning.

The same thing through OpenRouter

On OpenRouter, put the key in OPENROUTER_API_KEY and use the x-ai/ ids. OpenRouter controls thinking with a reasoning object instead. This JavaScript runs in Node.js 18 or newer:

const endpoint = "https://openrouter.ai/api/v1/chat/completions";

const reply = await fetch(endpoint, {
  headers: {
    Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`,
    "Content-Type": "application/json",
  },
  method: "POST",
  body: JSON.stringify({
    model: "x-ai/grok-4.20",
    reasoning: { enabled: false },
    stream: false,
    messages: [{ role: "user", content: "Rewrite this headline in a calmer tone: PRICES EXPLODE AGAIN" }],
  }),
});
const json = await reply.json();
console.log(json.choices[0].message.content);

To make a model think, send reasoning: { effort: "low" } (or medium, high) instead. Add exclude: true if you want the thinking used but not returned. Set stream: true to receive the answer as it is written, which feels much faster in a chat interface.

Sending an image

Grok 4.20, 4.3 and 4.7 all read images. Use the OpenAI-style message with a list of parts. xAI's docs accept JPEG and PNG images up to 20 MiB; a public URL or a base64 data URL both work.

{
  "model": "grok-4.20-0309-non-reasoning",
  "messages": [{
    "role": "user",
    "content": [
      {"type": "image_url", "image_url": {"url": "https://example.com/receipt.png"}},
      {"type": "text", "text": "List the items and the total on this receipt."}
    ]
  }]
}

Grok model ids and prices

These are the current text models OpenRouter lists for SpaceXAI, with context sizes and prices per million tokens (OpenRouter list price, Oct 2026). The xAI API charges the same base rates for prompts under 200,000 tokens.

ModelOpenRouter idxAI idContext (tokens)Input / output per 1M
Grok 4.7x-ai/grok-4.7grok-4.7500,000$2 / $6
Grok 4.6x-ai/grok-4.6grok-4.6500,000$2 / $6
Grok 4.5x-ai/grok-4.5grok-4.5500,000$2 / $6
Grok 4.3x-ai/grok-4.3grok-4.31,000,000$1.25 / $2.50
Grok 4.20x-ai/grok-4.20grok-4.20-0309-reasoning or -non-reasoning2,000,000$1.25 / $2.50
Grok 4.20 Multi-Agentx-ai/grok-4.20-multi-agentgrok-4.20-multi-agent-03092,000,000$1.25 / $2.50
Grok Build 0.1x-ai/grok-build-0.1grok-build-0.1256,000$1 / $2

Some details from xAI's models and pricing page (xAI list price, Oct 2026):

  • Long prompts cost more. Once a prompt reaches 200,000 tokens, the whole request is billed at the higher rate: $4 / $12 for Grok 4.7, $2.50 / $5 for Grok 4.3 and 4.20.
  • Cached input is cheaper: $0.50 per million for Grok 4.7 and $0.20 for Grok 4.3 and 4.20, for repeated prompt prefixes.
  • Batch jobs that can wait get a discount, and OpenRouter also lists x-ai/grok-4.3:batch at $1 / $2.
  • Context differs by source: OpenRouter lists 2,000,000 tokens for Grok 4.20, while xAI's own model page says 1,000,000.

Thinking tokens count as output, so a reasoning model can cost more per answer than its price per token suggests.

Practical tips

  • Start with Grok 4.20 non-reasoning for chat, rewriting and extraction. It is quick and cheap. Move to Grok 4.3 or 4.7 when quality on hard tasks matters more than speed.
  • Remember the knowledge cut-off. Grok 4.7 knows events up to May 2026, per xAI. For anything newer, pass the facts in your prompt, or use xAI's server-side web and X search tools, which are billed per call.
  • Write a system message with the role, tone and output format you want, and ask for JSON with a schema when your code parses the reply.
  • Handle rate limits. Retry after a short pause when you get a 429 response.
  • Follow the rules. xAI's acceptable use policy applies to API use, and a safety_identifier field lets you tag requests per end user.

When something goes wrong

  • 401 or 403: the key is missing, revoked or loaded into the wrong environment. Print its first few characters on the server to confirm it is there.
  • Model not found: check the prefix. OpenRouter wants x-ai/grok-4.7, xAI wants plain grok-4.7.
  • Empty or very slow replies from a reasoning model usually mean it spent its output budget thinking. Lower the effort or raise max_tokens.
  • Image rejected: convert it to JPEG or PNG and keep it under the size limit.

FAQ

Is the Grok API compatible with the OpenAI SDK?

Yes. Point the SDK at https://api.x.ai/v1 with an xAI key, or at OpenRouter with an OpenRouter key, and use a Grok model id.

Is there a free Grok API?

No permanent free tier is listed. Both xAI and OpenRouter charge per token, though short tests cost very little.

Can I generate images with the Grok API?

Yes, through xAI's Grok Imagine models on a separate images endpoint. See our Grok Imagine page. Our chat does not generate images.

Which Grok model does Grok.Online use?

Our chat offers Grok 4.20 with reasoning off, Grok 4.3 at low reasoning effort, and Grok 4.7 for up to 10 messages a day, all through OpenRouter.

Ready to ask Grok something?

No account, no download, no card. Open the chat, type your question and read Grok's answer as it appears.

Open Chat