Blog

Tutorial

How to Use krea-3/text-to-image via the HiAPI API: curl, Python, and a Working Request

Nov 10, 2026 13 min read
Cover image: On a warm charcoal-gray background, an amber light band cuts diagonally across the frame, with thin accent-colored lines along its edges.
On this page

Why call krea-3/text-to-image through an aggregated API

Every new image model means another SDK, another auth scheme, another set of response quirks. If you only ever ship one image feature, that cost is tolerable. If you ship several — or if you want the freedom to swap models later — it becomes the dominant cost of the work.

Calling krea-3/text-to-image through HiAPI collapses that cost. You integrate once against a single endpoint convention, a single credential, and a single response shape. The model identifier becomes a field in your payload rather than a fork in your codebase. When you want to compare outputs against another image model, or migrate a workload, you change a string, not an integration.

For this particular model the practical benefits are concrete:

  • One request shape for everything. Text-to-image calls follow the same authentication and payload conventions across the platform, so knowledge from your first call transfers to the next model.
  • Model-agnostic application code. Keep the model name in configuration. Prototyping against krea-3/text-to-image and later serving a different model shouldn't require touching your HTTP layer.
  • A single place to observe usage. Billing, request logs, and error responses come from one surface instead of N vendor dashboards.
  • Fewer secrets. One key to store, rotate, and scope, regardless of how many models you call.

The trade-off is the usual one with aggregation: you're working through a common interface, so model-specific oddities are normalized. In practice that's what you want — normalized inputs, predictable errors, and the freedom to treat the model as a tunable parameter.

This tutorial is deliberately narrow. We'll build one working request, run it twice (curl, then Python), look at how prompt phrasing steers photographic versus illustrative output, and then debug the handful of failures that account for most first-call problems. No architecture diagrams, no framework opinions — just a request you can send in the next five minutes and a checklist for when it doesn't work.

Assumptions: you have a HiAPI account, you can read your API key from the dashboard, and you're comfortable with a terminal and a Python interpreter. Nothing else is required.

Before you send a request

Three things need to be true before your first call. Get these right and most of the rest is tuning; get them wrong and you'll spend an hour debugging the wrong layer.

1. An account and an API key

Sign in to HiAPI and retrieve your API key from the dashboard. Treat it as a secret: it belongs in an environment variable or your secret manager, never in a committed file and never in a prompt or support message. The examples below read it from the environment:

export HIAPI_API_KEY="your-key-here"

If your organization supports multiple keys, use a dedicated key for this integration so you can rotate it independently of anything else you run.

2. The endpoint convention and auth header

HiAPI requests are authenticated with a bearer token — the same pattern you've seen in a hundred other APIs:

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

Use the base URL shown in the HiAPI API reference for your account region, and append the image generation path documented there. Don't guess the path from memory or from a blog post (including this one) — the API reference is the source of truth, and paths are the one part of the request that changes without warning. The tutorial approach: check the reference once, copy the URL, and keep it in a config value.

3. The model identifier, spelled exactly

The model identifier is krea-3/text-to-image. Keep the namespace prefix and the hyphenation exactly as written — krea3/text2image or krea-3 alone will fail with a model-not-found response. Case matters too. Store it as a constant:

MODEL = "krea-3/text-to-image"

This is the string that makes your integration model-agnostic, so give it a name and treat it as configuration rather than hard-coding it at each call site.

What you don't need to figure out up front

You don't need to know the field names for image dimensions, seed, or step count before your first call. Start with the minimum: authentication, model identifier, prompt. Add parameters one at a time once you have a 200 response, because a request that fails with five fields set gives you five suspects. A minimal request that fails gives you exactly one.

Build a working request with curl

curl is the fastest way to isolate the two things that break first calls: credentials and payload shape. No SDK version, no virtualenv, no async runtime — just a request on the wire.

A minimal call carries only what the model actually needs: an authentication header, a model identifier, and a prompt.

curl -sS -X POST "$HIAPI_BASE_URL/v1/images/generations" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "krea-3/text-to-image",
    "prompt": "A weathered fisherman mending a net on a dock at dawn, overcast light, 35mm photograph"
  }'

Two notes before you run it. First, $HIAPI_BASE_URL is a placeholder — set it to the base URL from the HiAPI API reference, and confirm the path segment against that same reference. Second, the -sS flags keep the output quiet but still show errors, which is what you want while debugging.

What a healthy response looks like: a JSON object containing the generated image reference or data, plus metadata for the request. The exact shape is documented in the API reference; don't write parsing code against a shape you haven't observed. Save a real response to a file so you have ground truth:

curl -sS -X POST "$HIAPI_BASE_URL/v1/images/generations" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"krea-3/text-to-image","prompt":"A neon-lit alley after rain, cinematic still"}' \
  -o response.json

Then inspect it with jq or your editor. This file is your fixture: when you port to Python, compare outputs. If the Python response differs structurally from response.json, the bug is in your code, not the model.

The reason to do this in curl first is diagnostic leverage. If the curl call succeeds, your key is good, the URL is right, and the model identifier resolves — so any later failure lives in your application code. If the curl call fails, the error body tells you which of those three broke, and you haven't written a line of code yet.

Once the minimal request works, add one parameter at a time. Re-run curl after each addition. Keep the successful payloads; they become the accepted input fixtures for your tests.

The same request in Python

The Python version is intentionally boring: same URL, same headers, same JSON body. The point is portability — the request shape you proved in curl should survive the move into a script and then into a service without redesign.

import os
import json
import requests

BASE_URL = os.environ["HIAPI_BASE_URL"].rstrip("/")
API_KEY = os.environ["HIAPI_API_KEY"]
MODEL = "krea-3/text-to-image"

def generate(prompt: str) -> dict:
    response = requests.post(
        f"{BASE_URL}/v1/images/generations",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json",
        },
        json={"model": MODEL, "prompt": prompt},
        timeout=120,
    )
    response.raise_for_status()
    return response.json()

if __name__ == "__main__":
    result = generate(
        "A weathered fisherman mending a net on a dock at dawn, overcast light, 35mm photograph"
    )
    print(json.dumps(result, indent=2))

A few deliberate choices:

  • Environment variables, not literals. The key never appears in source. os.environ["HIAPI_API_KEY"] fails loudly at startup if the variable is missing, which is better than a confusing 401 three layers down.
  • raise_for_status() before parsing. You want an HTTP error surfaced as an exception, not a KeyError when you try to read a field from an error body that happens to be JSON.
  • A generous timeout. Image generation is not an instant endpoint. Set a timeout that reflects that and handle it explicitly in production (see the production section).
  • json= rather than hand-built strings. Let the library serialize. Hand-rolled JSON is where trailing-comma and quoting bugs come from.

Run it once and compare the output to the response.json you captured earlier. The structures should match. Print the image reference or decode the image data depending on what the response returns — again, code against observed shape, not assumed shape.

Because MODEL is a constant, the same generate() function works for any image model on the platform. That's the payoff of the aggregation model: moving this into a service, adding a second model, or A/B testing outputs is a parameter change, not a rewrite.

Controlling photographic versus illustrative style

Style is not a switch; it's a direction you push the model in, and krea-3/text-to-image responds to the same levers you'd use with a photographer or an illustrator: subject, medium, lighting, and the vocabulary of the craft.

Push toward photographic

Photographic output is mostly about naming the apparatus and its consequences. Words that describe a camera, a lens, a film stock, and real light do more work than the word "realistic."

  • Name the medium and the capture: "35mm photograph," "editorial portrait," "documentary still."
  • Name the light: "overcast daylight," "golden hour backlight," "single softbox at camera left."
  • Name the imperfection: "slight motion blur," "visible grain," "shallow depth of field."

Compare "a fisherman on a dock" with "a weathered fisherman mending a net on a dock at dawn, overcast light, 35mm photograph, visible grain". The second prompt constrains the model toward the textures and lighting of photography rather than a generic depiction.

Push toward illustrative

Illustration is about naming a tradition, a line quality, and a palette — and often about removing the photographic cues you just learned.

  • Name the idiom: "flat vector illustration," "ink and watercolor," "mid-century editorial illustration," "isometric line art."
  • Name the line: "clean uniform strokes," "loose gestural linework."
  • Name the palette: "restrained two-color palette," "muted pastels."

Iterate, don't preset

Treat prompts as tunable configuration. Change one dimension at a time — swap only the medium phrase, keep subject and lighting constant — so you learn what each token is doing. Keep a short log of prompt variants and the outputs they produced; that log is more valuable than any preset library, because it's calibrated to your model and your content.

If the request exposes parameters beyond the prompt — dimensions, seed, or similar — adjust them after you've settled the prompt, not before. Changing the prompt and three parameters at once tells you nothing about which change mattered.

Troubleshooting common errors

Most first-call failures fall into four buckets. Work the checklist in order; each step eliminates a layer.

Authentication failures

Symptoms: a 401 or 403 with a message about credentials or permissions.

  • Is HIAPI_API_KEY actually set in the shell that runs the command? echo $HIAPI_API_KEY — an empty string looks a lot like a wrong key.
  • Is the header exactly Authorization: Bearer <key>? A missing Bearer, a stray quote, or a newline pasted into the key will all fail.
  • Did the key get revoked or is it scoped to a different environment? Regenerate if in doubt and retest with the curl call.

Malformed payloads

Symptoms: a 400 with a message about the body, a field, or JSON parsing.

  • Validate the JSON before sending. In curl, a single unescaped quote inside your prompt breaks the body. In Python, json= handles this for you — another reason to prefer it.
  • Check Content-Type: application/json is present.
  • Check field names against the API reference. A correctly spelled value under the wrong field name is still a 400.
  • Strip back to the minimal payload — model and prompt only — and confirm that works before adding fields back.

Wrong model identifier

Symptoms: a 404 or a 400 saying the model is unknown or unavailable.

  • Compare your string to krea-3/text-to-image character by character. Namespace prefix, hyphen, and path segment all matter.
  • Check for accidental whitespace or smart quotes introduced by copy-paste from a document.
  • Confirm the value isn't being overridden by a config default somewhere in your code.

Rate and quota responses

Symptoms: a 429, or a message about limits or insufficient balance.

  • Back off and retry after a short delay rather than hammering the endpoint.
  • Check your usage and balance in the dashboard.
  • If this happens during development, look for a retry loop that's firing faster than you think — a failed request inside a try block with an aggressive retry can exhaust limits quickly.

If none of that resolves it, capture the full request ID and error body from the response and send them to support. Error bodies on an aggregated API are usually specific enough to name the problem; the mistake is paraphrasing them instead of pasting them.

Taking it to production

The request you have now is a prototype. Four practices turn it into something you can leave running.

Handle errors as categories, not strings

Map HTTP status codes to behavior: authentication errors are configuration bugs and should page someone; 4xx payload errors are code bugs and should fail the request loudly; 429 and 5xx are transient and should be retried with exponential backoff and jitter. Never retry a 400 — you'll just burn quota confirming the same bug. Set an explicit timeout and treat timeouts as transient.

if response.status_code == 429 or response.status_code >= 500:
    raise TransientError(response.status_code)
response.raise_for_status()

Log the prompt, versioned

Every generated image should be traceable to the exact prompt that produced it. Store the prompt, the model identifier, the parameters, and the response request ID together. Treat prompt text as versioned configuration — a prompt_v3 string checked into a config file, not a literal buried in a function. When output quality shifts, you need to know whether the prompt, the parameters, or the model changed.

Keep the model name in config

krea-3/text-to-image should appear once, in a constant or config entry. That's what makes the aggregation model pay off: swapping models, running a comparison, or rolling back becomes a config change rather than a deploy of new code paths. It also makes it trivial to route different workloads to different models later.

Test against fixtures

Save the successful responses you captured during this tutorial as fixtures. Assert that your parsing code handles them, and use a recorded error body to test your error mapping. You'll catch response-shape drift before your users do.

Start with the minimal curl call, confirm the response shape, port it to Python unchanged, then iterate on prompts one dimension at a time — and consult the HiAPI API reference for the endpoint details that are subject to change.

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