GrokAdvanced

How to Call the Grok API from Python

Send your first request to the xAI Grok API in Python using the OpenAI-compatible endpoint and a secure API key.

9 minAdvanced

Beyond the chat interface, xAI offers an API so you can call Grok from your own code. It is OpenAI-compatible, which means existing OpenAI client libraries work with only a base URL and key change. This guide gets you from zero to a working Python request, with the key kept out of your source.

What you need

  • An xAI account with API access and billing set up
  • Python 3.9 or newer installed
  • Basic comfort with the terminal and pip
  • About 10 minutes

Step 1: Create an API key

Sign in to the xAI developer console and create a new API key. Copy it once and store it somewhere safe; you cannot view it again after closing the dialog. Never paste a key into code you will commit or share.

xAI console - API keys
API Keys
+ Create new key
Name: my-first-key
Key: xai-************************ [Copy]
Creating a new key in the xAI developer console.

Step 2: Store the key as an environment variable

Export the key in your shell so your code reads it from the environment instead of a hardcoded string. This keeps the secret out of your codebase. Add the export to your shell profile if you want it to persist.

zsh - setup
$export XAI_API_KEY="xai-your-key-here"
$python3 -m venv venv && source venv/bin/activate
$pip install openai
Successfully installed openai
$

Step 3: Write the request

Point the OpenAI client at the xAI base URL and pass a Grok model name. The rest of the call looks like any chat completion. The example below reads the key from the environment and prints Grok's reply.

grok_hello.py
import os
from openai import OpenAI

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

resp = client.chat.completions.create(
    model="grok-4",
    messages=[
        {"role": "system", "content": "You are a concise assistant."},
        {"role": "user", "content": "Give me 3 uses for the xAI API."},
    ],
)

print(resp.choices[0].message.content)
Check current model names
Model names change as xAI ships new versions. If a call returns a model-not-found error, list available models in the console or docs and update the model string.

Step 4: Run it and handle errors

Run the script. A 401 means your key is wrong or not exported; a 429 means you hit a rate or spend limit. Wrap the call in a try block in real code so a failed request does not crash your program.

zsh - run
$python grok_hello.py
1. Real-time chatbots 2. Content drafting 3. Data summarization
$

Result

You have made a live API call to Grok from Python with your key safely in the environment. From here you can swap in your own prompts, stream responses, or wire it into an app.

Watch related tutorials

Tags
#api#python#xai#developers