Grok API Key Setup Guide
From console.x.ai to a working production call — and every reason a valid key still returns 401 or 403.
TL;DR
- →Base URL is
https://api.x.ai/v1— the/v1is not optional. - →The OpenAI SDK works: override
base_urlandapi_key. - →401 with a "correct" key is almost always a trailing newline from .env or CI.
- →403 is entitlement or billing, not the key. Rotating it changes nothing.
Six Steps to a Working Key
Create the key in console.x.ai
Fund the account first — an unfunded organization can hold a valid key that still returns 403 on every call. Copy the key into your secret manager at creation time; it is not retrievable later.
Set the base URL to https://api.x.ai/v1
The /v1 suffix is required. Omitting it yields a 404 that is easy to misread as a bad model ID and costs people an afternoon.
Point your existing OpenAI SDK at it
Override base_url and api_key and leave the rest of the call shape alone. Strip provider-specific parameters that xAI does not implement rather than passing a foreign request object through wholesale.
Resolve model IDs at runtime
Call the models endpoint and cache the result rather than hard-coding a string. Model IDs are lowercase and hyphenated (grok-3, grok-3-mini) — display names sent as IDs are a frequent 404.
Verify with one minimal call
A single short completion proves auth, base URL, model ID and billing in one shot. Do this in CI on deploy, not manually — a key rotated by someone else should fail your pipeline, not your users.
Separate keys per environment
Distinct keys for dev, staging and production make rate limit attribution readable and let you revoke a leaked development key without an outage.
401 vs 403: Diagnose Before You Rotate
These two get conflated constantly, and the conflation wastes real time because the fixes do not overlap at all. A 401 says the credential was rejected. A 403 says the credential was accepted and the account is not allowed to do that. Rotating a key is a valid response to the first and a pure waste of a deploy for the second.
401 Unauthorized — the key
Whitespace, typo, missing Bearer prefix, revoked key, or the wrong environment variable being read. Check the header bytes before you check anything else.
403 Forbidden — the account
Model not entitled, billing unconfigured, or a spend cap reached. Fix it in the Console; the code does not need to change.
Key Hygiene That Prevents Outages
Once the key works, the remaining failure mode is operational. Keys leak into logs, get committed to repositories, and get rotated by whoever is on call without the deploy pipeline finding out. Three habits remove most of that risk: never log the key value (log its length and last four characters), scope one key per environment so revocation is surgical, and add a single minimal completion call to your deploy health check so a broken credential fails the pipeline instead of the first user request.
For the failure classes that survive good hygiene — capacity, quota, and genuine incidents — see the error code reference and the monitoring guide.
Alert Pro
14-day free trialStop checking — get alerted instantly
Next time Grok goes down, you'll know in under 60 seconds — not when your users start complaining.
- Email alerts for Grok + 9 more APIs
- $0 charged today — card required to start
- Cancel anytime — $9/mo after trial
Related Guides
Frequently Asked Questions
Where do I get an xAI Grok API key?
API keys are issued from the xAI Console at console.x.ai, under the API keys section. Keys are shown once at creation and cannot be retrieved afterwards, so store the value in a secret manager immediately rather than planning to copy it again later. The Console is also where you check your current rate limits and spend.
What is the base URL for the Grok API?
https://api.x.ai/v1 — note the /v1 suffix, which is the most common setup mistake. Because xAI implements an OpenAI-compatible surface, most SDKs work by pointing base_url at that address and passing your xAI key as the API key. Omitting /v1 produces a 404 that looks confusingly like a bad model ID.
Can I use the OpenAI SDK with Grok?
Yes. xAI exposes an OpenAI-compatible chat completions interface, so the official OpenAI SDKs work once you override the base URL and API key. This is the fastest migration path for an existing integration. Compatibility is close but not total — parameters unique to another provider may be rejected with a 400 or 422, so do not pass an untouched request object through from a different vendor.
My Grok API key is correct but I still get 401. Why?
The overwhelmingly common cause is invisible whitespace — a trailing newline picked up from an .env file, a CI secret store, or a shell heredoc. Other causes: the key was revoked or rotated, the Authorization header is missing the Bearer prefix, or two environments are loading different variables and the one you inspected is not the one being sent. Log the length and last four characters of the key at startup, never the key itself.
Why do I get 403 instead of 401?
A 403 means authentication succeeded but authorization did not — the key is real and the account is not entitled to what you asked for. Typical triggers are a model your organization has not been granted, billing not configured, or a spend limit reached. Reissuing the key will not fix a 403; check entitlements and billing in console.x.ai instead.
📡 Monitor your APIs — know when they go down before your users do
Better Stack checks uptime every 30 seconds with instant Slack, email & SMS alerts. Free tier available.
Affiliate link — we may earn a commission at no extra cost to you