Connecting to the Grok API is not complicated in itself. What actually stops people is a set of three questions: where the key comes from, how the base URL should be written, and whether the key and the address belong together. The most common 401 is not an expired key; it is a key from one platform pasted into another platform's endpoint.

This guide follows a practical order: choose an access path, create a key, configure the address, make a minimal call, then secure and troubleshoot. Model names and availability are subject to model pricing on this site. Console menu labels may change, so follow what the actual page shows.

Note: xAI and Grok are trademarks of their respective owners. This article is for technical reference only. Interfaces, models, and prices may change; refer to xAI's official documentation and model pricing on this site.

1. Decide which kind of key you need

There are two common sources of a Grok API key: the official xAI console and a domestic AI gateway that exposes an OpenAI-compatible endpoint. Both can call Grok, but the account, payment, and billing entity are different.

Comparison Official xAI console ZSQH AI Gateway
Who it suits Teams with an overseas payment method and stable access Teams paying in RMB that need local invoices
Account system xAI account Gateway account
Payment Payment methods supported by xAI RMB top-up
Base URL https://api.x.ai/v1 https://ai.zhongshangqihang.com/v1
Billing USD invoice; you handle exchange rates RMB invoice; unified multi-model usage
Model scope xAI's own models Multiple models enabled on the gateway

Keys from the two paths are not interchangeable. An official key only works with the official address, and a gateway key only works with the gateway address. Choose the path first, then create the key, and do not mix them halfway through.

2. Official xAI: getting a key

  1. Prepare a usable xAI account, and confirm its status, the terms of service, and any regional usage requirements.
  2. Sign in to the xAI console and find the API key management entry. Menu labels can change between versions; follow what the page shows.
  3. Complete billing setup or prepaid top-up as the console requires. Without usable credit, a key may be created successfully but still fail every call.
  4. Create a new key and name it after the project and environment, for example prod-customer-service, so rotation and audits are easier later.
  5. Copy and store the key immediately after creation. Most platforms show the full value only once; after you close the page, it cannot be viewed again.
  6. If the console offers quota, permission, or IP restrictions, apply least privilege instead of enabling everything by default.
  7. Verify with a minimal request to confirm that the key, address, and model name all pass.

The official path suits teams that only need Grok and have stable overseas payment and network access. If payment or connectivity is unreliable, the problem shifts from "is the model good?" to "can we reach it today?", and the operational cost is easy to underestimate.

3. Gateway: getting a key

  1. Open the ZSQH AI Gateway, register an account, and complete any required identity or company information.
  2. Top up a small amount first to verify payment, credit arrival, and the call path, then add balance according to actual usage.
  3. Create an API key in the console, name it after the project, and set a spending limit or alert.
  4. Record the gateway base URL: https://ai.zhongshangqihang.com/v1.
  5. Send a minimal request with the curl command below and confirm a 200 response with content.
  6. Once that works, integrate it into your application and keep the key in a server-side environment variable.

The value of the gateway path is not only reachability. It also includes RMB payment, consolidated billing, switching between models, and managing several models with one key. Whether it fits depends on your payment method, invoice requirements, and operational boundaries.

4. Base URL and endpoint syntax

The base URL is the easiest place to make a mistake. Usually it should stop at /v1, and the SDK appends the rest of the path automatically. If you write the full address by hand, make sure you do not append the path twice.

Item Official xAI ZSQH AI Gateway
Base URL https://api.x.ai/v1 https://ai.zhongshangqihang.com/v1
Chat endpoint /chat/completions /chat/completions
Auth header Authorization: Bearer <key> Authorization: Bearer <key>
Model name See the official model list See model pricing on this site

A common mistake is writing https://api.x.ai/v1/v1/chat/completions, or adding a trailing slash to the base URL before joining the path. Another is using an Anthropic-style x-api-key header with Grok. The OpenAI-compatible Grok endpoint uses Bearer authentication.

5. Minimal call verification

Use curl first to rule out problems in your application code. The command below sends one short message. A 200 response containing a choices field means the key, base URL, and model name all match:

export GROK_API_KEY="sk-your-key"

curl "https://ai.zhongshangqihang.com/v1/chat/completions" \
  -H "Authorization: Bearer $GROK_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-4",
    "messages": [{"role": "user", "content": "Reply with OK only"}],
    "max_tokens": 16
  }'

Python projects can reuse the OpenAI SDK and change only the key and base URL:

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["GROK_API_KEY"],
    base_url="https://ai.zhongshangqihang.com/v1",
)

resp = client.chat.completions.create(
    model="grok-4",
    messages=[{"role": "user", "content": "Explain what an API gateway is in three sentences."}],
    max_tokens=256,
)
print(resp.choices[0].message.content)

Do not write the model name from memory. Different accounts and gateways may have different models enabled, so use model pricing or the console's model list. A wrong model name usually returns 404 or model not found; it is not a key problem.

6. Key security

  1. Keep keys only in server-side environment variables or a secrets manager, never in a code repository.
  2. Do not embed a key in a frontend bundle, a browser request, or a mobile app package. The frontend should call your own backend, and the backend should hold the key.
  3. Use one key per project, with separate test and production keys, to simplify limits, rotation, and usage tracing.
  4. Log only the first few characters or a hash of the key, never the full value.
  5. Revoke and recreate a key immediately when an employee leaves, a project ends, or a leak is suspected.
  6. Review usage curves regularly. If you see abnormal calls, disable the key first and investigate; do not start by changing application code.

A leaked key does not simply mean "someone else spends your money." Data, quota, and billing can all go out of control at the same time. Treat a key like a database password and many problems disappear before they happen.

7. Common configuration errors

Symptom Common cause Fix
401 Key and base URL do not match; key contains spaces or a newline Confirm they come from the same source and copy the key again
404 Path joined twice; wrong endpoint Stop the base URL at /v1; use /chat/completions
model not found Misspelled model name or model not enabled Copy the model name from the pricing page or console
429 Request rate, concurrency, or token limit exceeded Lower concurrency and retry with backoff
insufficient quota Low balance or key limit reached Top up and check the key's quota settings
Timeout Network path, proxy, or long output Check the egress path and set reasonable connect and read timeouts

When troubleshooting, save the request ID and status code from the response before changing the request. Without a status code and request ID, you can only guess.

FAQ

Must the key and base URL come from the same provider?

Yes. An official key goes with the official address, and a gateway key goes with the gateway address. Mixing them usually produces a 401; in some cases it appears as a 404 or a permission error.

Can I put the key in a browser?

Not recommended. Browser code is visible to users, and the key can be extracted easily. The correct pattern is for the frontend to call your own backend, which holds the key and forwards the request.

Can one key call multiple models?

In gateway mode, usually yes. Specify the model name in the request, provided your account has access to it. For an official account, the available models are determined by the official console.

What should I do if a key leaks?

Revoke or disable the key in the console immediately, create a replacement, and review recent usage and billing. Do not merely change the string in your code while leaving the old key active.

Why does a freshly copied key keep returning 401?

First check for extra spaces, newlines, or quotation marks from the copy, then confirm that the base URL matches. If it still fails, test directly with curl to rule out SDK configuration and proxy environment issues.

Next steps

If you want one entry point for Grok and other models, create a test key at the ZSQH AI Gateway, verify it with a minimal request, and then integrate it into your application. Model availability and prices are subject to model pricing.

Related reading: