Guides

Grok API: How to Get a Key and Make Your First Grok 4.7 Call

How to use the Grok API: get an xAI or Modellix key, make a first Grok 4.7 call in curl, Python and Node, pick a model, and fix 401 and 429 errors.

8 min read
GrokxAIAPI KeyLLM APILLM Gateway
On this page
Modellix Team
Written byModellix TeamOfficial
Grok API guide cover: a glowing key in a beam of light against a black starfield, generated with Grok Imagine

The Grok API is xAI's developer API for its Grok models. It speaks the OpenAI format at https://api.x.ai/v1, its default model is grok-4.7 (500K context, $2 per million input tokens and $6 per million output), and you get a key from the xAI console after loading credits. You can also call the same model with one Modellix key at https://llm.modellix.ai/v1 as xai/grok-4.7, at the same price.

This guide covers both ways to get a key, a first call in curl, Python, and Node that we ran as written, which Grok model to pick, the rate limits by tier, and the errors you will actually hit. For a full cost breakdown with tested bills, see Grok API pricing. Image and video generation use a different endpoint, covered in our Grok Imagine API guide.

Item xAI direct Modellix gateway
Base URL https://api.x.ai/v1 https://llm.modellix.ai/v1
Key from console.x.ai modellix.ai console
Model ID grok-4.7 xai/grok-4.7
Price (Grok 4.7) $2 / $0.50 cached / $6 per 1M tokens Same
Protocols Chat Completions, Responses, xAI SDK Chat Completions, Responses, Anthropic Messages
Free API credits None published None; first top-up 10% off

How to Get a Grok API Key

There are two legitimate routes. Pick the xAI console if you want a direct account with xAI, its Batch discount, and its US endpoint. Pick a gateway key if Grok is one model among several in your stack.

Route 1: the xAI console

  1. Create an account at console.x.ai. xAI's console and docs now carry the SpaceXSI name, so expect that brand on the sign-up page.
  2. Load credits. The quickstart puts this before the first call, and the pricing docs publish no free API tier. With the default $0 invoiced billing limit, requests are rejected once the prepaid balance hits zero.
  3. Create a key on the API Keys page. The same page lets you rotate and revoke keys later.
  4. Export it as an environment variable instead of pasting it into code: export XAI_API_KEY="your_api_key".
xAI quickstart: step 1 create an account and load credits, step 2 generate an API key and export XAI_API_KEY

xAI's quickstart: account and credits first, then the key. Source: docs.x.ai quickstart.

Route 2: one Modellix key

  1. Sign up at Modellix and top up your balance.
  2. Create a key under Console, then API Key. It starts with mdlx-.
  3. Point your client at https://llm.modellix.ai/v1 and set the model to xai/grok-4.7.

The same key also works for the image and video models on the media API, which runs on a separate host, api.modellix.ai.

Modellix LLM quickstart: create an API key, choose the base URL for your protocol, pass a provider/name model ID

Grok is not Groq

Groq is a separate company that sells fast inference for open models, with its own console and GROQ_API_KEY. A Groq key will not authenticate against xAI, and the reverse is also true. If a tutorial sends you to console.groq.com, you are in the wrong place.

Your First Grok API Call: curl, Python, and Node

We ran each snippet below exactly as written, with a real key in the environment. Each one returned a correct ZIP code regex from Grok 4.7; the Python and Node calls took 5.2 s and 5.9 s.

curl, direct to xAI

bash
curl https://api.x.ai/v1/chat/completions \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "grok-4.7", "messages": [{"role": "user", "content": "Write a regex that matches a US ZIP code, with or without the +4 suffix. Reply with the regex only."}]}'

Python, OpenAI SDK

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["MODELLIX_API_KEY"],  # mdlx-••••, or XAI_API_KEY for xAI direct
    base_url="https://llm.modellix.ai/v1",    # or https://api.x.ai/v1
)

resp = client.chat.completions.create(
    model="xai/grok-4.7",                     # "grok-4.7" on xAI direct
    messages=[{"role": "user", "content": "Write a regex that matches a US ZIP code, with or without the +4 suffix. Reply with the regex only."}],
)
print(resp.choices[0].message.content)

Node, OpenAI SDK with the Responses API

javascript
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.MODELLIX_API_KEY,
  baseURL: "https://llm.modellix.ai/v1",
});

const response = await client.responses.create({
  model: "xai/grok-4.7",
  input: "Write a regex that matches a US ZIP code, with or without the +4 suffix. Reply with the regex only.",
});
console.log(response.output_text);

Moving between xAI and Modellix changes three things: the base URL, the key, and the model ID (grok-4.7 versus xai/grok-4.7). Everything else in the request stays the same.

Chat Completions or Responses

Both endpoints work for Grok, but the bodies differ. Chat Completions takes messages; Responses takes input. When we sent a messages body to /v1/responses on the gateway, it came back as a 500 rather than a clear 400, so check the body shape before you blame the server. xAI's own quickstart uses Responses, and on that endpoint Grok 4.7 always returns encrypted reasoning content.

Reasoning effort

Grok 4.7 always reasons. Set reasoning_effort on Chat Completions, or reasoning.effort on Responses, to low, medium, high (the default), or xhigh. Reasoning tokens bill as output, which is why they matter for cost; see Grok API pricing for how much of a bill they make up.

Grok API Models and Which One to Call

xAI's own advice is short: use Grok 4.7 for code, chat, and everything else in text. Images and video have their own Imagine models.

Model Best for Context Input / output per 1M On Modellix
grok-4.7 Default for code, chat, and agents 500K $2.00 / $6.00 Yes
grok-4.6 Pinned older flagship 500K $2.00 / $6.00 Yes
grok-4.5 Pinned older flagship, cheapest cache 500K $2.00 / $6.00 Yes
grok-4.3 Cheaper output, 1M context 1M $1.25 / $2.50 No
grok-4.20-0309-reasoning Low-cost reasoning, 1M context 1M $1.25 / $2.50 No
grok-4.20-0309-non-reasoning Low-cost answers without reasoning 1M $1.25 / $2.50 No
grok-4.20-multi-agent-0309 Multi-agent research tasks 1M $1.25 / $2.50 No
grok-build-0.1 Budget coding model 256K $1.00 / $2.00 No

For the three models on Modellix, we sent the same short coding prompt twice each. Grok 4.7 averaged 13.2 s and $0.0078 per call, against 33.6 s and $0.0122 for Grok 4.6 and 30.3 s and $0.0103 for Grok 4.5. Same rate card, but 4.7 spent far fewer reasoning tokens. For what changed in the model itself, see our Grok 4.7 guide.

Modellix LLM price table filtered to xAI: Grok 4.7, 4.6 and 4.5 at the same rates as xAI

Model aliases: pin or follow

On xAI, <model> points at the latest stable version, <model>-latest at the newest one, and a dated name such as a -0309 suffix stays fixed. Modellix offers ~xai/grok-latest; when we called it, the response reported xai/grok-4.7 as the model that served it. Pin a version in production so an upgrade never changes behavior without a deploy, and follow latest in development to try new releases first.

Grok API Rate Limits, Errors, and Fixes

Rate limits by tier

xAI sets limits per model, in requests per second and tokens per minute. Your tier depends on cumulative API spend since January 1, 2026, and it never drops back.

Tier Spend to unlock Grok 4.7 RPS Grok 4.7 TPM
Tier 0 $0 150 50M
Tier 1 $50 172 53M
Tier 2 $250 208 60M
Tier 3 $1,000 312 74M
Tier 4 $5,000 500 100M

Going over any limit returns 429. Even Tier 0 allows 150 requests per second on Grok 4.7, so most teams hit the token limit before the request limit. Imagine (image and video) limits do not follow these tiers; raising them means contacting xAI sales. On Modellix, a 429 may include X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset headers, so you can wait exactly as long as needed.

Retry 429 with exponential backoff instead of rotating keys:

python
import time
from openai import RateLimitError

def call_with_backoff(make_request, retries=5):
    for attempt in range(retries):
        try:
            return make_request()
        except RateLimitError:
            if attempt == retries - 1:
                raise
            time.sleep(2 ** attempt)

Common errors

Status What it means Fix
400 Bad request body or model ID On Modellix, a bare grok-4.7 returns: "Invalid model name passed in model=grok-4.7. Call /v1/models to view available models for your key." Add the xai/ prefix
401 Missing or invalid key We got "invalid API key" from a wrong key. Check that the key matches the host
402 No balance (Modellix) Top up; xAI direct simply rejects calls once prepaid credits run out
403 Key accepted, action refused Ask your team admin for the permission
404 Unknown path or model Check the endpoint path and model ID
422 A field has the wrong format Compare the body against the API reference
429 Rate limit, or the model is busy Back off and retry; read Retry-After if present
5xx Server error, or a wrong body on the gateway Retry once, then check you sent input to Responses and messages to Chat Completions

Keep the key out of your code

Read the key from an environment variable or a secrets manager, never from a source file. Treat a key pasted into a notebook, a screenshot, or a support thread as leaked, and rotate it the same day. Rotation takes a minute in either console, so schedule it rather than waiting for an incident.

xAI Direct or One Gateway Key: How to Choose

If you need Use Why
Batch 20% discount, Priority, or the US endpoint xAI direct Those options are only on xAI's API
Grok 4.3, 4.20, or Build models xAI direct Modellix lists 4.7, 4.6, and 4.5
Grok next to Claude, GPT, Gemini, or DeepSeek Modellix One key, one balance, one log
Grok plus image and video generation Modellix The same key covers the media API
The lowest Grok 4.7 token price Either Same rates; the first Modellix top-up is 10% off

Why Modellix is the best way to call Grok next to other models

Why Modellix

  • No markup on Grok. Grok 4.7, 4.6, and 4.5 cost the same per token as on xAI. Our test bills matched xAI's formula, long-context tier included.
  • One key, every vendor. The key that calls xai/grok-4.7 also calls the other 36 text models and the image and video APIs. Switching models is a one-string change.
  • Drop-in for OpenAI and Anthropic clients. Chat Completions, Responses, and Anthropic Messages all work on the same host, so Cursor, Codex, Claude Code, and the OpenAI SDK connect by changing only the base URL and key.

Create your account →

Grok on the Modellix LLM gateway

Base URL, auth headers, the xai/grok-4.7 model ID, protocol examples, error codes, and token billing.

View Docs

If you route several vendors through one base URL already, our notes on the Anthropic base URL and the OpenAI-compatible API cover the same pattern for other clients.

Grok API FAQ

How do I get a Grok API key?

Create an account at console.x.ai, load credits, and generate a key on the API Keys page. Or create one Modellix key and call Grok as xai/grok-4.7 at https://llm.modellix.ai/v1 without an xAI account. If you want to try Grok next to other models without a separate account for each vendor, Modellix is the fastest and cheapest way to do it, at xAI's own Grok price.

Is the Grok API free?

No. xAI's quickstart asks you to load credits before the first call, and its docs publish no free API tier. The key itself costs nothing; you pay per token.

Is the Grok API compatible with the OpenAI SDK?

Yes. Set the OpenAI SDK's base URL to https://api.x.ai/v1 (or https://llm.modellix.ai/v1), use your key, and call Chat Completions or Responses. We ran the Python and Node examples above with the stock OpenAI SDK.

How much does the Grok API cost?

Grok 4.7 costs $2.00 per million input tokens, $0.50 cached, and $6.00 output, doubling for prompts of 200K tokens or more. A short coding call cost us about $0.008. Full details are in Grok API pricing.

Which Grok model should I use?

Grok 4.7 for almost everything in text: it was the fastest and cheapest per call of the three versions we tested. Consider Grok 4.3 or the 4.20 models on xAI direct when output cost matters more than quality, or when you need a 1M context window.

What are the Grok API rate limits?

They depend on your tier. At Tier 0, Grok 4.7 allows 150 requests per second and 50M tokens per minute; Tier 4 (after $5,000 of spend) allows 500 and 100M. Exceeding either returns 429.

Is Grok the same as Groq?

No. xAI makes Grok. Groq is a separate company with its own console and keys, and the two do not work interchangeably.