xAI API (Grok)
Chat with Grok, stream, keep server-side history, call functions, search the web and X, get JSON, read and generate images.
AI & machine learningGuided#grok#xai#llm#chat#function-calling#image-generation#search
Fork copies the collection into your workspace, without the publisher's secrets, so you can add your own key and send requests. Star saves it to your starred APIs (Account › Marketplace) and helps others find it.
Overview
The xAI API serves the Grok models: chat and writing, reasoning, code, reading images, calling your own functions, searching the web and X (Twitter) in real time, and generating and editing images. The main endpoint is the Responses API (POST /v1/responses), which can keep conversation state on the server; xAI recommends it for new integrations. The older, stateless, OpenAI-compatible Chat Completions endpoint (POST /v1/chat/completions) still works and is covered at the end of this collection for existing code.
Get an API key
- Sign in at the xAI Console (create a team if asked).
- Load your account with credits (Billing in the console); the API needs credit to run requests.
- Open API Keys in the console, create a key and copy it.
- Paste it into the apiKey variable in this collection. It is marked secret, so it is never shown or shared when you fork or publish.
Authentication and base URL
Every request sends Authorization: Bearer <key>; the collection sets it for you. Base URL: https://api.x.ai/v1. Requests with a body use Content-Type: application/json. Because the API follows the OpenAI request format, OpenAI SDKs also work by pointing them at this base URL.
Models
The model variable defaults to grok-4.7, xAI's flagship and its recommendation for chat and code (500k-token context). grok-4.6 and grok-4.5 are earlier versions; grok-4.3 and the grok-4.20-0309-reasoning / -non-reasoning variants offer a 1M context at lower prices. Image generation uses grok-imagine-image-2.0 (recommended) or the cheaper grok-imagine-image. A plain model name points to the latest stable version, <name>-latest to the newest, and a dated name pins a release. Run List models for what your key can use, with prices. See Models and pricing.
How to use this collection
- Fill in apiKey, then run 1. Start here: list models, then create your first response.
- 2. Conversations covers instructions and reasoning effort, server-side history with
previous_response_id, streaming, and reading or deleting stored responses. Create a response savesresponseId. - 3. Structured output returns JSON matching a schema.
- 4. Tools is a function-calling round trip (the first request saves
callIdandresponseId) plus web search and X search with citations. - 5. Images reads an image and generates and edits images (generation saves
imageUrl). - 6. Chat Completions shows the OpenAI-compatible endpoint.
Common errors
| Status | Meaning | What to do |
|---|---|---|
| 400 | Bad request | Check the body and URL; unsupported schema features in structured output also return 400. |
| 401 | Missing or invalid key | Send Authorization: Bearer <key>; create a new key in the console. |
| 403 | Forbidden | The key or team is not allowed this model or endpoint (key restrictions, or no credits); ask your team admin. |
| 404 | Not found | Wrong path, model name or response id (stored responses are deleted after 30 days). |
| 405 / 415 | Wrong method / content type | Check the method and send Content-Type: application/json. |
| 422 | Invalid field format | A field in the body has the wrong type or value. |
| 429 | Rate limited | Slow down and retry with backoff, or raise limits in the console. |
| 5xx | Server problem | Retry later; check status.x.ai. |
Limits and pricing
Text models are billed per input, cached-input and output token (reasoning tokens count as output), with a higher rate for every token once a prompt passes the long-context threshold; server-side tools such as web and X search add a per-use charge, and images are billed per image. Every response includes usage, with the cost in cost_in_usd_ticks. Rate limits depend on your team and model and are shown in the console. See Pricing, Rate limits, Debugging errors and the REST API reference.
Endpoints 18
1. Start here
- GETList models
/modelsLists every model your key can use (text, image and video) in the OpenAI list shape: data[] with id (the value for model), aliases, owned_by, context_length,… - GETList language models with details
/language-modelsLike List models, but only text models and with more detail: input_modalities and output_modalities (for example text, image), version, fingerprint,… - POSTCreate a response
/responsesThe core call. Send model and input (a string, or a list of messages with role and content) and get back a response with output items. Reading the answer: the…
2. Conversations
- POSTInstructions and reasoning effort
/responsesinstructions sets the role, tone and rules (like a system prompt). reasoning.effort trades speed and cost against depth: low for quick replies, high (the… - POSTContinue with previous_response_id
/responsesPass the id of an earlier stored response as previous_response_id and send only the new message; xAI supplies the earlier turns (and reasoning) from storage,… - POSTStream a response (SSE)
/responsesSet "stream": true to get Server-Sent Events while the answer is written. Each event is a JSON object with a type; text arrives in small delta events, Grok… - GETGet a stored response
/responses/{{responseId}}Fetches a stored response by id, with the same shape as when it was created (status, output, usage). Useful to recover an answer after a dropped connection or… - DELETEDelete a stored response
/responses/{{responseId}}Deletes a stored response before the 30-day expiry, for example when a user asks for their data to be removed. Afterwards it can no longer be fetched or used…
3. Structured output
- POSTJSON that matches a schema
/responsesSet text.format to {"type": "json_schema", "name": ..., "schema": ..., "strict": true}. The JSON arrives as the output_text of the message item; parse it. Use…
4. Tools
- POST1) Offer a function
/responsesTools are listed in tools; a function tool has type: "function", name, description and JSON Schema parameters at the top level of the object. When Grok wants… - POST2) Send the function result back
/responsesContinue from the previous response with previous_response_id and send a function_call_output item whose call_id matches the call and whose output is your… - POSTWeb search with citations
/responsesThe built-in web_search tool lets Grok search and read web pages on xAI's side, then answer with sources. Sources come back two ways: a top-level citations… - POSTX search
/responsesThe x_search tool searches posts on X. Narrow it with: Citations work as for web search. Good for "what are people saying about ..." and following official…
5. Images
- POSTAsk about an image
/responsesSend a message whose content is a list of parts: input_image (with image_url: a public URL or a data:image/...;base64, URL, and optional detail) and… - POSTGenerate an image
/images/generationsPOST /images/generations creates images from a text prompt. Returned URLs are temporary, so download the image promptly. The test script saves the first URL… - POSTEdit an image
/images/editsPOST /images/edits changes an existing image according to prompt. Pass one image (with url: a public or base64 data URL, or file_id for an uploaded file), or…
6. Chat Completions (OpenAI-compatible)
- POSTCreate a chat completion
/chat/completionsOpenAI-style request: model plus messages (system, user, assistant, tool roles). Nothing is stored, so send the full history every time. The answer is in… - POSTStream a chat completion
/chat/completionsWith "stream": true the reply arrives as data: lines, each a chat.completion.chunk whose choices[0].delta carries new content (and reasoning_content on…
API details
- Base URL
https://api.x.ai/v1- Authentication
- A bearer token in the Authorization header
- Operations
- 18 operations on 18 pathsPOST 14GET 3DELETE 1
- Main resources
- 1. Start here 32. Conversations 53. Structured output 14. Tools 45. Images 36. Chat Completions (OpenAI-compatible) 2
- Description format
- Swastik Codes guided collection, API version
checked against the docs on 2026-11-17 - Links
- Documentation
How to test the xAI API (Grok) in Swastik Codes
- Open the APISelect “Fork & run in Swastik Codes” on this page. Sign in or create a free account if asked.
- Fork it into your workspaceChoose a workspace. You get your own copy of the xAI API (Grok) collection, without the publisher's secrets.
- Add your credentialsThis API uses A bearer token in the Authorization header. Add yours in the collection's variables or an environment; the requests already reference it.
- Send a requestPick an endpoint, for example “List models” (GET /models), and press Send. Check the response, add tests and run the whole collection with the runner.
Frequently asked questions
What is the xAI API (Grok)?
Chat with Grok, stream, keep server-side history, call functions, search the web and X, get JSON, read and generate images. It is listed under AI & machine learning and has 18 endpoints.
Who publishes the xAI API (Grok)?
It is listed from xAI's public API description (an OpenAPI document), not published by xAI on Swastik Codes. Anyone who controls x.ai can claim the profile by adding a DNS TXT record.
What is the base URL of the xAI API (Grok)?
Requests go to https://api.x.ai/v1. Endpoint paths are added to this base URL.
How do I authenticate with the xAI API (Grok)?
With A bearer token in the Authorization header.
How many endpoints does the xAI API (Grok) have?
18 operations on 18 paths (14 POST, 3 GET, 1 DELETE). The largest groups are 1. Start here, 2. Conversations, 3. Structured output, 4. Tools.
Is forking the xAI API (Grok) free?
Yes. Forking copies the collection into your workspace for free. It has been starred 0 times and forked 0 times.