Blog

Tutorial

Use flux-2/image-to-image via the HiAPI API: curl and Python tutorial

Nov 12, 2026 14 min read
Cover image: on a deep pine green background, several large prisms are sliced diagonally into flat color blocks, with teal and misty green geometric facets that are clean and orderly.
On this page

What flux-2/image-to-image does and when to use it

flux-2/image-to-image is an editing endpoint rather than a pure text-to-image generator. You hand it two things: a reference image and an edit instruction written in natural language. The model reads the reference image as visual context — subject, composition, style, lighting — and produces a new image that follows your instruction while staying anchored to that reference.

That distinction matters when you design a pipeline. With text-to-image you describe everything from scratch and hope the model lands close to your intent. With image-to-image you already have a visual asset and you want a controlled transformation: restyling a product shot, swapping a background, adjusting the mood of a scene, or iterating on a design while keeping the underlying composition stable.

Good fits

  • Asset variation. Generate multiple stylistic treatments of one approved reference image.
  • Guided editing. Apply a targeted change ("make the lighting warmer," "replace the background with a plain studio wall") without regenerating the whole scene.
  • Consistency across a set. Reuse the same reference image so a batch of outputs shares a visual anchor.
  • Human-in-the-loop tools. Let a user upload an image, describe a change, and get a result back inside your own UI.

Poor fits

  • Pixel-exact retouching or compositing. This is a generative model, not a raster editor.
  • Cases where you have no reference image at all — text-to-image is the better starting point there.
  • Any workflow where the instruction alone must carry all the detail; the reference image is doing real work and a poor reference produces a poor result.

Think of the endpoint as reference image + instruction -> edited image. Everything in this tutorial builds on that shape: how to send it, how to read what comes back, and how to keep it running when the network does not cooperate.

Prerequisites and authentication setup

Before your first call, line up three things.

1. A HiAPI account

Sign up and open the dashboard. All requests in this tutorial go through the HiAPI unified API, so there is no separate provider to register with and no per-provider SDK to install.

2. An API key

Create an API key in the dashboard. Treat it like a password: do not commit it to a repository, do not paste it into client-side code, and do not log it. The standard pattern is to load it from an environment variable at runtime:

export HIAPI_API_KEY="your-api-key-here"

Then reference HIAPI_API_KEY wherever the key is needed. If you deploy to a container or a serverless platform, set it as a secret in that environment rather than baking it into the image.

3. A reference image you can reach

The endpoint needs a reference image, so decide up front how you will supply it. Two common approaches:

  • A URL the API can fetch, such as a signed link to your own object storage.
  • Base64-encoded bytes sent inline in the request body, which avoids exposing an internal URL but increases payload size.

Pick a small test image first — a few hundred kilobytes is plenty to validate the integration. Large uploads slow down every retry and make debugging harder.

Checkpoint

You should now have a key in an environment variable and one test image you can access from your machine. Keep the key out of shell history where possible (a .env file loaded by your tooling is usually cleaner than exporting inline).

One more habit worth forming now: log request IDs and timings from day one. When something misbehaves in production, the difference between a request you can trace and one you cannot is enormous.

Crafting the request: reference image and edit instruction

Every image-to-image call is built around two inputs. Get these right and the rest is plumbing.

Input one: the reference image

The reference image is the anchor. It tells the model what the scene contains and how it looks before any edit. Practical guidance:

  • Match the aspect ratio you want out. If your reference is a wide landscape and you need a square output, expect either cropping or distortion depending on how you configure the call.
  • Start from a clean, well-lit image. Muddy references produce muddy edits.
  • Prefer one clear subject. A busy collage gives the model too many competing anchors.

Input two: the edit instruction

The instruction is a natural-language description of the change you want. This is where most quality differences come from. Treat it like a prompt with a reference attached.

  • State the change, not the whole scene. "Replace the background with a plain white studio wall" beats "a product on a white background" — the latter invites the model to redraw everything.
  • Name what must stay. Phrases like "keep the subject's pose and framing unchanged" meaningfully reduce drift.
  • Be concrete about style and light. "Soft overcast lighting, muted colors" gives the model more to work with than "make it nicer."
  • Avoid contradictions. If the reference is a daylit outdoor scene and you ask for a night interior, expect the model to make a judgment call you may not like.

The request body

Your request to flux-2/image-to-image carries the model identifier, the reference image, and the instruction. A useful mental model:

{
  "model": "flux-2/image-to-image",
  "input": {
    "image": "<URL or base64 reference image>",
    "prompt": "<edit instruction>"
  }
}

If your reference is base64, build it as a data URI or pass the raw encoding alongside a MIME type, following the request schema. If it is a URL, make sure the link is publicly reachable for the duration of the call — a signed link that expires mid-request produces an opaque failure.

Iterate before you integrate

Write two or three instructions for the same reference image and compare outputs before you wire anything into code. The model behaves predictably when instructions are specific and inconsistently when they are vague, and it is much cheaper to learn that now than in production.

A working curl request

The fastest way to validate your key, your reference image, and your instruction is a single curl call. The example below assumes your key is in HIAPI_API_KEY and your reference image is reachable at a URL.

curl -sS -X POST "https://api.hiapi.ai/v1/images/generations" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "flux-2/image-to-image",
    "input": {
      "image": "https://your-bucket.example.com/reference.jpg",
      "prompt": "Replace the background with a plain white studio wall. Keep the subject pose, framing, and lighting on the subject unchanged."
    }
  }'

A few things to notice:

  • The key travels in the Authorization header as a bearer token. Never put it in the URL.
  • Content-Type is JSON. Forgetting it is a common reason for a confusing 4xx.
  • The model id goes in the body, so the same endpoint can route to other models by changing one field.
  • The instruction is a full sentence, not a keyword list. This is deliberate — see the previous section.

Reading the raw output

Run it once and look at the whole response before writing any parsing code. Pipe it through a formatter if that helps:

curl -sS -X POST "https://api.hiapi.ai/v1/images/generations" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d @request.json | python -m json.tool

Keeping the body in a file (request.json) makes iteration much easier than editing a shell-quoted string, and it gives you a durable artifact to reproduce a bug later.

If you need base64 instead of a URL

Swap the image value for a data URI built from your file:

python - <<'PY'
import base64, json, pathlib
data = base64.b64encode(pathlib.Path("reference.jpg").read_bytes()).decode()
body = {
    "model": "flux-2/image-to-image",
    "input": {
        "image": f"data:image/jpeg;base64,{data}",
        "prompt": "Make the lighting warmer and slightly reduce contrast.",
    },
}
pathlib.Path("request.json").write_text(json.dumps(body))
PY

Now the same curl invocation works, because the payload lives in request.json. If the call succeeds, you have everything you need to move to Python.

The same call in Python

The Python version is intentionally boring: build the same dictionary, post it with the same headers, and keep the endpoint and model in constants so nothing drifts from your curl version.

import os
import requests

API_URL = "https://api.hiapi.ai/v1/images/generations"
MODEL = "flux-2/image-to-image"


def edit_image(reference_url: str, instruction: str, timeout: float = 60.0) -> dict:
    api_key = os.environ["HIAPI_API_KEY"]  # fail fast if unset
    payload = {
        "model": MODEL,
        "input": {
            "image": reference_url,
            "prompt": instruction,
        },
    }
    response = requests.post(
        API_URL,
        headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
        },
        json=payload,
        timeout=timeout,
    )
    response.raise_for_status()
    return response.json()


if __name__ == "__main__":
    result = edit_image(
        "https://your-bucket.example.com/reference.jpg",
        "Replace the background with a plain white studio wall. "
        "Keep the subject pose, framing, and lighting on the subject unchanged.",
    )
    print(result)

Why it is structured this way

  • os.environ["HIAPI_API_KEY"] over .get() so a missing key raises immediately instead of sending an unauthenticated request.
  • timeout is explicit. Image generation is not instant; a request with no timeout will eventually hang a worker.
  • raise_for_status() before parsing. You want an exception on a 4xx or 5xx, not a confusing KeyError further down.
  • The endpoint and model are module constants, which makes it painless to point a test suite at a stub server.

Using it with base64 input

If you are passing bytes rather than a URL, encode the file and build the data URI in the same place you build the payload:

import base64, pathlib

def as_data_uri(path: str, mime: str = "image/jpeg") -> str:
    raw = pathlib.Path(path).read_bytes()
    return f"data:{mime};base64," + base64.b64encode(raw).decode()

Then call edit_image(as_data_uri("reference.jpg"), instruction). Keep the encoding step separate from the request function so you can unit-test your validation and prompt assembly without touching the network.

Parsing the response

The call returned a JSON object. Now extract the edited image in a way that does not break the day the response grows a field.

Start by inspecting, not assuming

Dump one raw response during development and note where the image reference lives — typically a URL or a base64 payload nested inside a result structure. Then write accessors that check for its presence rather than reaching straight into nested keys.

def extract_image_url(response: dict) -> str:
    data = response.get("data") or []
    if not data:
        raise ValueError(f"no image data in response: {response}")
    first = data[0]
    url = first.get("url") or first.get("b64_json")
    if not url:
        raise ValueError(f"unrecognized image payload: {first}")
    return url

Two habits in that snippet are worth keeping: fail loudly with the actual payload in the error message, and accept either shape (URL or base64) rather than hard-coding one. Response formats evolve; tolerant readers survive.

Persist immediately

A returned URL may be temporary. If the image matters, download it and store it in your own bucket within the same job:

def persist(url: str, dest: str) -> None:
    if url.startswith("data:"):
        header, b64 = url.split(",", 1)
        import base64, pathlib
        pathlib.Path(dest).write_bytes(base64.b64decode(b64))
        return
    with requests.get(url, stream=True, timeout=60) as r:
        r.raise_for_status()
        with open(dest, "wb") as f:
            for chunk in r.iter_content(1 << 16):
                f.write(chunk)

Persisting also gives you a stable key to record in your database, which is far more useful than storing a link that may rot.

Validate what you got

Cheap checks catch expensive mistakes. Confirm the file is non-empty, that its magic bytes match an image format, and optionally that its dimensions match expectations. Rejecting a corrupt or truncated image at the boundary is much better than serving it to a user.

Record provenance

Store the model id, your instruction text, the reference image key, and a timestamp alongside the output. When someone asks why an image looks a certain way three weeks later, that row is the answer — and it makes re-running a specific edit trivial.

Retries and error handling for production

Image generation calls fail for two very different reasons, and conflating them is the classic production bug.

Separate transient from terminal

  • Transient — timeouts, connection resets, 429 rate limits, 5xx responses. The same request may well succeed if repeated after a pause.
  • Terminal — 400 invalid request, 401 bad or missing key, 404 unknown model, validation errors on the payload. Repeating these wastes time and money and delays the real fix.

Retry only the first class. For the second, fail the job immediately and surface the error message — it almost always tells you exactly which field is wrong.

Retry with backoff and jitter

import random, time, requests

RETRYABLE = {429, 500, 502, 503, 504}

def call_with_retries(fn, attempts: int = 5, base: float = 1.0):
    last = None
    for i in range(attempts):
        try:
            return fn()
        except requests.HTTPError as e:
            status = e.response.status_code if e.response is not None else None
            if status not in RETRYABLE:
                raise
            last = e
        except (requests.Timeout, requests.ConnectionError) as e:
            last = e
        delay = base * (2 ** i) + random.uniform(0, 0.5)
        time.sleep(delay)
    raise RuntimeError("exhausted retries") from last

Exponential backoff keeps you from hammering a service that is already struggling; jitter prevents a fleet of workers from retrying in lockstep. Always cap the number of attempts and the total elapsed time — an unbounded loop is worse than a clean failure.

Respect rate limits

On a 429, honor any retry hint in the response headers before backing off. If you are running a large batch, add concurrency limits on your side rather than relying on the server to throttle you.

Make failures visible

  • Tag retries with a unique job id and log every attempt with its outcome and duration.
  • Emit a metric for retry rate; a slow climb is an early warning that something upstream is degrading.
  • After the final attempt fails, move the job to a dead-letter queue with the full response body attached, never just a message like "failed."

Idempotency and cost sanity

A retried request may succeed on the server even if your client never saw the response. If your product cannot tolerate duplicate outputs, key jobs by your own id and reconcile before retrying. And since calls are billed per use, watch that retry loops are not quietly multiplying spend — a stuck consumer retrying forever is the most expensive bug in this area.

Common pitfalls and next steps

Most integration pain around flux-2/image-to-image comes from a short list of mistakes. Check your code against these before you ship.

  • Vague instructions. "Improve it" produces random results; "remove the text from the sign and keep the sign's shape" produces usable ones. Specificity is the single biggest lever on quality.
  • Reference image mismatch. Wrong aspect ratio, a blurry source, or a busy collage will not be rescued by a better prompt.
  • Expiring URLs. Signed links that lapse mid-flight cause failures that look like server errors. Use long-enough expiries or switch to base64.
  • Hard-coding the response shape. Reaching directly into nested keys turns a small schema change into an outage. Use defensive extractors with clear errors.
  • No timeout. A missing timeout ties up a worker indefinitely and masks the real problem.
  • Retrying terminal errors. A 400 will not fix itself. Read the message.
  • Losing the output. If the returned URL is temporary and you did not persist the image, you have nothing.
  • Logging secrets and prompts carelessly. Keys must never appear in logs; user-provided instructions may need redaction depending on your domain.

Next steps

Once the single-call flow is solid, the natural extensions are: wrapping the call in a background job so your UI stays responsive, storing instruction/response pairs so you can A/B test prompt phrasing, and adding a moderation or validation layer on the inputs if users supply their own images. Explore the model page for flux-2/image-to-image and the HiAPI docs to see the parameters your use case may want next. Build the smallest thing that works, measure it, and let the instruction quality do the heavy lifting.

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