
Generate Imagine API images as base64
Ask the Imagine API to return image bytes inline when you need to embed a still without downloading a temporary hosted URL first. Official Image Generation documents response_format on the REST and OpenAI-compatible path (url default, or b64_json) and the xAI Python SDK’s image_format="base64" on sample(). Model id for current Quality Mode parity is grok-imagine-image-2.0. Get a key and credits at console.x.ai.
What you need
An XAI_API_KEY with Console balance, a prompt that states the scene clearly, and a reason to prefer inline bytes (server-side embed, offline save, or a pipeline that should not depend on a short-lived URL). When a temporary URL is fine, leave the default url response and download promptly — the same docs page warns that hosted URLs expire.
Request base64
- Export the key:
export XAI_API_KEY="your_api_key"
- Call generations with
response_formatset tob64_json:
curl -X POST https://api.x.ai/v1/images/generations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $XAI_API_KEY" \
-d '{
"model": "grok-imagine-image-2.0",
"prompt": "A serene Japanese garden with a stone path and soft morning mist",
"response_format": "b64_json"
}'
- Or use the xAI Python SDK and write the bytes to disk:
import os
import xai_sdk
client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))
response = client.image.sample(
prompt="A serene Japanese garden with a stone path and soft morning mist",
model="grok-imagine-image-2.0",
image_format="base64",
)
with open("garden.jpg", "wb") as f:
f.write(response.image)
- With the OpenAI-compatible client, decode
response.data[0].b64_jsonafterresponse_format="b64_json". The Vercel AI SDK’sgenerateImagepath already returns base64 by default for embedding. - Keep aspect ratio, resolution, and quality knobs the same as a URL response — Set aspect ratio on Imagine API images and Set resolution on Imagine API images still apply on the same request.
After you have the bytes
Save the file, run your own moderation or size checks, then hand the asset to the next step (CMS upload, email attach, or an edit that starts from a data URI). When the next job is an edit, the editing docs accept a base64 data URI as the source image — Edit an image with the Imagine API. For several candidates from one prompt, combine n with base64 only if your client can hold the larger payload — Generate image variations with the Imagine API.
Pitfalls
Leaving the default url format when your worker cannot fetch outbound hosts forces a second hop you did not plan. Logging full base64 strings into chat or tickets leaks the asset and bloats logs. Assuming every SDK uses the same parameter name mixes response_format, image_format, and AI SDK defaults — match the client you actually call. Mixing Console API spend with SuperGrok weekly Imagine quotas on grok.com confuses two different meters. Skipping a local save after a base64 response still loses the only copy if the process exits.