Blog

Tutorial

How to Call fibo-2.0/image-to-image via the HiAPI API: curl and Python

Nov 13, 2026 11 min read
Cover image: misaligned, overlapping bone-white papers with charcoal-black edge lines, with a rust-red sheet inserted, flat-lay composition.
On this page

What fibo-2.0/image-to-image Does in Your Pipeline

Text-to-image models start from nothing but a prompt. Image-to-image models start from an image you already have. That difference sounds small, but it changes where the model sits in your pipeline: instead of being the first step that produces an asset, fibo-2.0/image-to-image becomes an editing step that transforms one.

A typical workflow looks like this: you source or generate a base image, run it through fibo-2.0/image-to-image with instructions describing the change you want, and then move the returned result into whatever comes next — review, compositing, storage, or another model call. Because the model receives your input image alongside a prompt, it can preserve composition, subject placement, and overall structure while restyling, adjusting, or reworking the parts you describe.

When to choose image-to-image over text-to-image

Reach for image-to-image when the output needs to stay recognizably tied to an existing image: restyling a photo while keeping the subject, adjusting lighting or color treatment, producing variations of an approved asset, or cleaning up a rough base before final use. Choose text-to-image when you have no starting image and only a description.

What the endpoint expects from you

The call is a single job submission: you send an input image plus a prompt and any parameters you want to control, and the API returns a job you can track. Treat the endpoint as one well-defined stage in a larger chain rather than a complete editing application — how you prepare the input image and what you do with the result are both your responsibility.

Because the request is asynchronous by nature, design your integration around that: submit, store the job identifier, poll until the job finishes, then fetch the output reference. The rest of this guide builds exactly that flow.

Before You Send a Request

Three things need to be in place before your first call: credentials, a correct understanding of the endpoint shape, and a prepared input image.

Credentials

Every request to the HiAPI API is authenticated with an API key. Keep the key server-side — never embed it in browser code or commit it to a repository. The cleanest pattern is to read it from an environment variable so the same code runs locally and in your deployment:

export HIAPI_API_KEY="your-api-key"

If you do not yet have a key, create one in your HiAPI account dashboard before continuing.

Endpoint shape

The model is addressed as fibo-2.0/image-to-image on the HiAPI API. All model calls share the same base URL and request conventions, which means once you have one working call, adapting it to a different model is mostly a matter of changing the model identifier and the payload fields.

Preparing the input image

Image-to-image requests need an actual image, not a URL you hope will resolve. Decide up front how you will supply it — as a local file you upload with the request or as a reference the API accepts — and confirm the format works before writing application code. The two most common ways to break a first request are sending a path that only exists on your laptop and sending a file whose format the endpoint does not accept.

A practical checklist before building the call:

  • The image is a real file you can read in the language you will use.
  • The prompt describes the edit you want in plain language, not just a list of keywords.
  • You know which parameters you want to pass and which you will leave at defaults.
  • Your API key is available in the environment where the request runs.

With those settled, you can move to the request itself.

A Working curl Request, Line by Line

Start with curl. It removes every abstraction between you and the HTTP request, so if something fails you know it is the request and not your client library.

curl -X POST "https://api.hiapi.ai/v1/images/generations" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "fibo-2.0/image-to-image",
    "prompt": "turn the scene into a soft watercolor illustration, keep the subject and framing",
    "image": "BASE64_ENCODED_IMAGE_OR_ACCEPTED_REFERENCE",
    "n": 1
  }'

Here is what each piece does.

The request line

-X POST sets the method. The URL is the HiAPI API base plus the image generation path. Keep the base in a variable or config value rather than hardcoding it in many places, so a future change is one edit.

Headers

Authorization: Bearer $HIAPI_API_KEY carries your credential; the shell expands the environment variable you exported earlier, so the key never appears literally in your command history. Content-Type: application/json tells the API to parse the body as JSON. Sending a JSON body without this header is a frequent cause of confusing errors.

The payload

model identifies fibo-2.0/image-to-image. prompt is your instruction — describe the edit, not the entire output image, since the input image already carries the structure. image is the input image in whatever form the endpoint accepts; if you are embedding it, that means base64 encoding the file contents. n controls how many outputs you request, and leaving it at the default is the safest starting point.

If your image is large, embedding it directly in a shell command gets unwieldy. Encode it to a file first and reference it, or move straight to the Python approach in the next section, where reading a file and encoding it is a one-liner.

Reading the response

Do not assume the response contains finished image bytes. Run the curl call and inspect the JSON: you are looking for the job identifier or status field that tells you whether the work is done or still running. Capture that structure before writing any parsing code, because the shape of the response dictates how you poll.

Porting the Request to Python

Python makes the request more maintainable and lets you wrap it in a function you can reuse across your codebase. The same request, expressed as a small client:

import base64
import os
import time

import requests

BASE_URL = "https://api.hiapi.ai/v1"
API_KEY = os.environ["HIAPI_API_KEY"]


def encode_image(path: str) -> str:
    with open(path, "rb") as f:
        return base64.b64encode(f.read()).decode("utf-8")


def submit_image_edit(image_path: str, prompt: str) -> dict:
    payload = {
        "model": "fibo-2.0/image-to-image",
        "prompt": prompt,
        "image": encode_image(image_path),
        "n": 1,
    }
    response = requests.post(
        f"{BASE_URL}/images/generations",
        headers={"Authorization": f"Bearer {API_KEY}"},
        json=payload,
        timeout=60,
    )
    response.raise_for_status()
    return response.json()

Why this shape

Separating encode_image from submit_image_edit keeps file handling and HTTP handling independent, which makes each easier to test. Reading the key from the environment at import time fails fast if it is missing, rather than producing a 401 several layers deep. The explicit timeout prevents a stalled connection from hanging your worker indefinitely.

Handling the response body

raise_for_status() turns HTTP-level failures into exceptions you can catch and log with the response body attached — this is far more useful than silently parsing an error object as if it were a success. Once you have the parsed JSON, record the job identifier it contains and log the full response during development so you can see exactly what fields are present. Do not write your parser against assumptions; write it against a response you have actually observed.

Keeping it reusable

Two small improvements pay off quickly: put the base URL and model name in constants so other model calls can share the client, and return a typed structure (a small dataclass or dict with known keys) from your submit function so the polling code has a stable contract to work against.

Handling the Async Lifecycle and Polling

Image jobs are not instantaneous. Your integration should treat submission and completion as two separate events.

Step 1: Submit and persist

Submit the job, then store the job identifier somewhere durable — a database row, a queue message, or at minimum a log line. If your process crashes between submission and completion, an unrecorded job is lost work. Tie the identifier to whatever entity in your system owns the result, so you can reconcile later.

Step 2: Poll with backoff

Poll the job status endpoint at a sane interval. A tight loop hammering the status endpoint wastes resources and is the most common async mistake:

def wait_for_job(job_id: str, interval: float = 2.0, max_wait: float = 180.0) -> dict:
    deadline = time.monotonic() + max_wait
    while time.monotonic() < deadline:
        response = requests.get(
            f"{BASE_URL}/jobs/{job_id}",
            headers={"Authorization": f"Bearer {API_KEY}"},
            timeout=30,
        )
        response.raise_for_status()
        job = response.json()
        if job.get("status") in {"succeeded", "failed"}:
            return job
        time.sleep(interval)
        interval = min(interval * 1.5, 10.0)
    raise TimeoutError(f"job {job_id} did not finish in {max_wait}s")

Starting with a short interval but growing it gives responsive early checks without long-term spam. The hard deadline prevents infinite waits on a job that will never complete.

Step 3: Treat failure as a normal outcome

A finished job is not always a successful job. Check the status before reading the output, and branch on failure explicitly: log the error details the job returns, surface a retryable signal to your caller, and decide whether a retry should reuse the same input or regenerate it. A job that timed out client-side may still be running server-side, so avoid blindly resubmitting without checking first.

Step 4: Fetch and store the result

Once the job reports success, read the output reference it provides and download it promptly. If you are storing results long-term, copy them into your own storage rather than depending on a reference remaining valid indefinitely.

Common Errors and How to Fix Them

Most failures fall into a few predictable categories. Work through this checklist in order.

Authentication failures

A 401 or 403 almost always means the header is wrong or the key is not present. Verify the header is exactly Authorization: Bearer <key> with a single space after Bearer, and confirm the environment variable is actually set in the process making the request — not just in your interactive shell. Keys pasted with trailing whitespace or stray quotes account for a surprising share of these.

Malformed payloads

A 400 or 422 usually means the API could not interpret the body. Check three things in order: that Content-Type: application/json is present, that the JSON actually parses (a trailing comma will break it), and that required fields are present with the right names. If you are sending base64 image data, confirm it is valid base64 and that the underlying file is a supported format — a truncated or double-encoded string produces confusing validation errors.

Polling mistakes

If jobs never appear to finish, confirm you are polling with the identifier the submit response actually returned, and that you are reading the correct status field. A tight loop that ignores the failed status will look like a hang. Add a hard timeout and log the status transitions you observe; that log usually reveals the mistake immediately.

Response-parsing pitfalls

If your code throws while reading the result, do not guess at the response shape. Log the raw response body first. Common issues include assuming the output is bytes when it is a reference, assuming a field is always present when it is conditional on success, and parsing a success response with a failure-path parser. Build extraction around responses you have actually seen.

A quick triage habit

When something breaks, isolate the layer: run the curl command with the same payload. If curl succeeds and Python fails, the bug is in your client. If both fail, the bug is in the request. That single test saves more time than any other debugging habit.

With a working call and a resilient polling loop in place, fibo-2.0/image-to-image becomes a dependable editing step you can build on — start from the model page on HiAPI and adapt the request above to your own images.

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