The xAI API for developers
On this page
Build Grok into your applications
Everything you’ve learned to do in the Grok interface can be triggered from your own code. The xAI API brings those capabilities into your apps, websites, and services: the conversation stops being a place you go and becomes a function your product calls.
Prerequisites
You need four things before you write your first line of code:
- An xAI account created at accounts.x.ai
- An API key generated on console.x.ai
- A payment method set up (to go beyond the free quota)
- A Python or JavaScript development environment
The first two are things you’ve already done in this course: the account handles authentication, and the key identifies your application to the API. The payment method only comes into play once your usage exceeds the free quota, which happens faster than you’d think as soon as a service runs continuously. As for the environment, Python and JavaScript have the best tooling, but since the API speaks HTTP, any language that can send a request will do.
Initial setup
The first step is to store your API key securely, in an environment variable:
export XAI_API_KEY="xai-your-key-here"
Never hard-code your key in your source code. The reason is mundane: a key written in a file ends up in a Git repository sooner or later, and a key pushed to a public repository gets exploited within minutes by bots that scan commits, while the bill stays in your name.
Next comes choosing an SDK. The native xAI SDK for Python installs with pip install xai-sdk. If your code already calls OpenAI, the openai library works as is, thanks to format compatibility. On the JavaScript side, you add the Vercel AI SDK with npm install ai @ai-sdk/xai, and it integrates with React and Next.js apps.
Your first request
With the native SDK, creating the client and opening a conversation takes three lines:
from xai_sdk import Client
import os
client = Client(api_key=os.getenv("XAI_API_KEY"))
response = client.chat.create(model="grok-4.5")
The OpenAI-compatible route is just as direct: only the base_url changes compared with existing code, which is why many teams switch over in a few minutes.
from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("XAI_API_KEY"),
base_url="https://api.x.ai/v1"
)
response = client.responses.create(
model="grok-4.5",
input="Explain machine learning to me in 3 sentences."
)
To check that a key works before you even write any code, nothing beats a command-line call:
curl https://api.x.ai/v1/responses \
-H "Authorization: Bearer $XAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "grok-4.5",
"input": "Hi, how are you?"
}'
What the API exposes
The foundation is text generation (conversational answers, writing, analysis), along with a reasoning mode that solves complex problems step by step. Streaming adds to that by delivering the answer token by token instead of waiting for generation to finish.
A second set gives access to information: real-time web and X search, and RAG, which queries document collections you’ve built. The multimodal side covers understanding images you provide, generating images and videos with grok-imagine, and voice, with spoken conversations and TTS.
Finally, three mechanisms make the API programmable in the strict sense: function calling, which lets the model call your own functions; structured outputs, which guarantee usable JSON without fragile post-processing; and server-side code execution.
Choose your model
Reasoning varies by model. grok-4.7, the flagship, offers configurable reasoning: the reasoning_effort parameter (low, medium, high, or xhigh) sets how deeply it thinks, request by request. grok-4.3 remains the budget, very-long-context option, at roughly half the price. Non-reasoning versions of the models exist for simple tasks: rewording or classification don’t need internal deliberation.
Naming conventions affect your application’s stability:
grok-4.20: the latest recommended stable versiongrok-4.20-latest: the most recent version (can change)grok-4.20-0309: a version pinned to a specific date (March 9)
In production, a pinned version protects your prompts from silent changes to the model; latest is fine for exploration, as long as you accept that behavior may shift.
Rate limits and best practices
The API enforces rate limits to keep the service stable: on the entry tier, about 10 million tokens per minute and 1,800 requests per minute for models such as grok-4.3, and more as your tier rises. Image and video generation models have their own, much lower caps, from 30 to 300 requests per minute depending on the model, so keep an eye on them for a consumer-facing service.
A few habits separate a prototype from a solid integration. Turn on streaming for long answers, because thirty seconds in front of a blank screen feels like an outage. Pass a conversation ID to benefit from caching. Route each task to the right model: grok-4.3 for simple volume, grok-4.20 for reasoning. Handle errors with retries and exponential backoff, or a traffic spike turns into an avalanche of rejected requests. And watch your usage in the console before you discover the total at the end of the month.
Key takeaways
- The xAI API is compatible with the OpenAI format, which makes migration easy
- Several SDKs are available: native xAI, OpenAI, and the Vercel AI SDK
- The API covers text, images, video, voice, and search
- Two tiers of models: grok-4.7 (flagship, configurable reasoning) and grok-4.3 (budget, 1M context)
- Always store your API key in an environment variable, never hard-coded