Blog

Tutorial

How to Use grok-imagine/text-to-image via the HiAPI API: curl & Python Guide

Nov 12, 2026 10 min read
Layered paper cover art in cream and graphite with a single terracotta sheet stepped into shallow depth.
On this page

What grok-imagine/text-to-image Gives You

grok-imagine/text-to-image is a text-to-image endpoint available through HiAPI: you send a prompt and a few generation parameters as JSON over HTTP, and you get back an image. That is the whole contract. There is no SDK to install, no session to initialize, and no background job to poll before you can see your first picture.

Where it fits in a developer workflow:

  • Prototyping. You can go from an idea to a rendered image in one terminal command, which makes it practical to test prompt ideas quickly.
  • Content pipelines. Because it is a plain HTTP call, you can call it from a backend service, a queue worker, or a build script the same way you call any other API.
  • Product features. User-facing image generation usually means you need predictable request/response handling, structured errors, and retries. A stateless endpoint is a good fit for all three.

What this endpoint is not: it does not store your prompts for you, it does not manage a library of generated images, and it does not replace your own orchestration. You own the request, you own the output, and you decide where the bytes go.

This guide focuses on getting a request working, then making it reliable. The pattern is identical whether you call it from curl or Python, because it is one authenticated HTTP request in both cases. Start minimal, confirm the round trip, then layer on complexity.

Prerequisites and Authentication

Before your first call, confirm you have the following:

  1. A HiAPI account and an API key. Treat the key as a secret: load it from an environment variable, never hardcode it in a script you might commit.
  2. A tool to make HTTP requests. curl is enough for the first test. For Python, use requests or httpx; both are covered later.
  3. Network access to the HiAPI API host. If you are behind a corporate proxy, make sure HTTPS_PROXY is set for your shell so curl and Python both pick it up.

The key is passed as a bearer token in the Authorization header:

export HIAPI_API_KEY="your-key-here"

Then every request carries:

Authorization: Bearer $HIAPI_API_KEY
Content-Type: application/json

Two habits worth adopting immediately:

  • Keep the key out of URLs. Nothing in the request should put credentials in a query string, where they end up in logs and shell history.
  • Use one environment per key. A development key and a production key should be different values so you can rotate one without breaking the other.

If you have not generated a key yet, create one in the HiAPI dashboard and store it in your secret manager or a local .env file that is excluded from version control. Once echo $HIAPI_API_KEY prints a value, you are ready for the first request.

A Minimal Working Request in curl

The smallest useful call sends a model identifier and a prompt. Everything else has a default, so resist the urge to tune parameters until you have seen one image come back.

curl -sS -X POST "$HIAPI_BASE_URL/v1/images/generations" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-imagine/text-to-image",
    "prompt": "a lighthouse on a rocky coast at dusk, calm sea, soft overcast light"
  }'

What each part does:

  • -X POST with a JSON body is the standard shape for generation endpoints.
  • model selects grok-imagine/text-to-image explicitly. Pin the model name in your scripts rather than relying on a default, so a change in defaults never silently alters your output.
  • prompt is the only content input. Keep it a single clear sentence for this first test.

A successful response returns JSON containing the generated image, typically as a URL or a base64 payload depending on the response format you request. Read the response with a JSON formatter before you write any parsing code. If you are inspecting output in a terminal, piping through python -m json.tool makes the structure readable.

Once that works, save the raw response to a file so you have a known-good baseline:

curl -sS -X POST "$HIAPI_BASE_URL/v1/images/generations" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d @request.json \
  -o response.json

With the request body in request.json, you can edit the prompt without fighting shell quoting, which matters as soon as prompts get long or contain punctuation.

The Same Request in Python

The Python version is the same HTTP call with better ergonomics: dicts instead of nested quotes, and straightforward handling of the image bytes.

import os
import requests

api_key = os.environ["HIAPI_API_KEY"]
base_url = os.environ["HIAPI_BASE_URL"]

payload = {
    "model": "grok-imagine/text-to-image",
    "prompt": "a lighthouse on a rocky coast at dusk, calm sea, soft overcast light",
}

response = requests.post(
    f"{base_url}/v1/images/generations",
    headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    },
    json=payload,
    timeout=120,
)
response.raise_for_status()
data = response.json()
print(data)

Two details are worth calling out. First, timeout=120 — image generation is not instantaneous, and a request with no timeout will hang a worker indefinitely when something upstream stalls. Second, raise_for_status() before parsing, so an error body never gets mistaken for a successful image response.

To save the image, handle both response shapes:

item = data["data"][0]

if item.get("b64_json"):
    import base64
    image_bytes = base64.b64decode(item["b64_json"])
else:
    image_bytes = requests.get(item["url"], timeout=60).content

with open("output.png", "wb") as f:
    f.write(image_bytes)

If you prefer a single dependency set, httpx works the same way with httpx.post(..., json=payload). The important part is that the request body and headers are unchanged from the curl example — that consistency is what makes the two examples interchangeable and what makes debugging predictable.

Structuring Prompts for Wide Aspect Ratios

Wide output fails in a specific way: the model has a lot of horizontal space to fill, so it either duplicates elements or floats a small subject in an empty frame. You fix that with prompt structure, not with more adjectives.

Use a three-part skeleton:

  1. Subject — what the image is about, stated first and specifically. "A cargo ship entering a harbor" beats "a ship."
  2. Style — the rendering language: photographic, flat vector, watercolor, cinematic still. One or two terms is enough.
  3. Composition — how the frame is organized, and this is where wide ratios are won or lost.

For composition, name the horizontal structure explicitly:

  • Name a left-to-right or panoramic reading: "wide establishing shot, subject on the right third, open sky on the left."
  • Describe the foreground, middle ground, and background as separate bands, since a wide frame naturally reads as layers.
  • Specify what fills the edges: "harbor cranes at the far left, open water at the far right." Edges are the first place a wide image goes empty.
  • Avoid prompts that imply a portrait or square composition — close-up faces, single centered objects — and expect them to stretch or letterbox.

When you set an aspect ratio parameter for a panoramic format, change the prompt at the same time. A prompt written for a square frame will produce a square idea inside a wide canvas. Rewrite it as a scene with horizontal distance in it: horizons, streets, rows of objects, crowds spread across a room.

Iterate one variable at a time. Hold the aspect ratio fixed and vary wording; then hold the wording fixed and vary the ratio. Log both alongside the output so you can tell which change actually helped.

Handling Errors and Response Codes

Read the status code before the body. Each common failure points at a different fix, and mixing them up wastes time.

401 Unauthorized

The key is missing, malformed, or revoked. Check that the header is exactly Authorization: Bearer <key>, that the environment variable actually expanded (print its length, not its value), and that you are not sending a key from a different environment.

400 Bad Request

Your JSON is valid HTTP but invalid for this endpoint. Usual suspects:

  • model is misspelled or omitted. It must be grok-imagine/text-to-image.
  • prompt is empty or missing.
  • A parameter has the wrong type — a string where a number is expected, or vice versa.
  • The request body is not valid JSON at all, commonly from shell quoting in curl. Move the body into a file and use -d @request.json.

Read the error message body; it usually names the offending field.

429 Too Many Requests

You are sending requests faster than your allowance. The fix is client-side: back off, queue, and retry. Do not tighten a retry loop in response to 429 — that makes it worse.

5xx Server Errors

These are transient or upstream conditions. Retry with a delay, and if the failure persists across several attempts, capture the request payload and response body for diagnosis rather than retrying indefinitely.

Timeouts and Connection Errors

These are not HTTP statuses at all, and they are the most common failure in practice. If requests raises a connection timeout, the request may still have been processed. Decide whether a timeout means "retry" or "give up" for your use case before you write the retry loop.

Tuning and Retrying in Production

Once the baseline request works, tune in small steps: change the prompt wording, then the aspect ratio, then any other parameter, and compare outputs side by side. Save each request payload next to its output so a result is always reproducible.

A production wrapper does three things: it retries only the failures worth retrying, it logs enough to debug, and it fails loudly when it gives up.

import time
import requests

def generate(payload, max_attempts=4):
    for attempt in range(1, max_attempts + 1):
        try:
            r = requests.post(
                f"{base_url}/v1/images/generations",
                headers=headers,
                json=payload,
                timeout=120,
            )
        except requests.RequestException as exc:
            log.warning("request failed attempt=%d err=%s", attempt, exc)
            time.sleep(2 ** attempt)
            continue

        if r.status_code == 429 or r.status_code >= 500:
            log.warning("retryable status=%d attempt=%d", r.status_code, attempt)
            time.sleep(2 ** attempt)
            continue

        if r.status_code >= 400:
            raise RuntimeError(f"{r.status_code}: {r.text[:500]}")

        return r.json()

    raise RuntimeError("exhausted retries")

Notes on the pattern:

  • Exponential backoff (2 ** attempt) with a cap keeps a rate-limited client from hammering the endpoint. Add jitter if you run many workers.
  • Only retry 429, 5xx, and network errors. A 400 or 401 will fail identically on every attempt.
  • Log the attempt number and status, not the API key, and never log the full prompt if it may contain user data.
  • Bound the total time. A retry loop with no ceiling turns one slow request into a stalled worker.

Measure your own latency and success rate rather than assuming them; those two numbers tell you whether you need more parallelism or more backoff. Start with the minimal request from this guide, wrap it in the helper above, and iterate from there.

Related articles

View all articles →

Start building with persistent AI artifacts

Get your API key and call image, video and audio models through one task-based API.

Read the API docs