📊 We use cookies & analytics to improve your experience. Learn more
Latest

Module 3 · Files, tools and your own data Lesson 10 of 15

The xAI API and your first script

Learning objective

xAI serves Grok over an API that is deliberately close to the OpenAI request format, so a script written for one moves to the other with a base URL change. You do not need this to finish the course, and you do not need it for a fresher job either — but an afternoon here is what turns "I have used Grok" into "I have built with it", which is a different sentence in an interview.

The concept

xAI serves Grok over an API that is deliberately close to the OpenAI request format, so a script written for one moves to the other with a base URL change. The idea is simple: the same model you have been chatting with also answers a web request, so you can put it inside a script, a spreadsheet or a page. A key identifies you; a request sends the text; a response comes back as data.

The reason to try it once, even if you never build anything: it makes the chat version less mysterious. You see that the whole conversation is text in and text out, that your instructions are literally lines of a request, and that "the model" is one parameter among several.

A first call looks like this:

Python
from openai import OpenAI

client = OpenAI(
    api_key="YOUR_XAI_KEY",
    base_url="https://api.x.ai/v1",
)

r = client.chat.completions.create(
    model="grok-2-latest",
    messages=[{"role": "user", "content": "Name three things a fresher should check before joining a startup."}],
)

print(r.choices[0].message.content)

Common mistakes

The mistake is wiring live search into a script and trusting the output. If the answer decides something, the source is the thing you keep, not the summary.

Worked example

A script that watches one topic and returns a daily three-line summary is a weekend project, and it teaches the same request shape as every other API here.

Your practice task

Get a key, run one request that works, and change one word in it to see the answer change. That is the whole of the first afternoon.

Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.

Key takeaway

xAI serves Grok over an API that is deliberately close to the OpenAI request format, so a script written for one moves to the other with a base URL change.

Create free account or sign in

Almost there

15 lessons left of 15

Finish every lesson to unlock the certificate. Each one ends in a practice task — do them and the final project brief writes itself.