how-tos

Kling Image 4.0 API Guide: First Request in cURL and Python

Poyo.ai Team
9 min read
Share:

Kling Image 4.0 API guide: first request in cURL and Python

This Kling Image 4.0 API guide takes you from an API key to a finished image: one cURL call, a bounded Python polling loop, then a working JSON body for every input mode of kling-4.0-image and kling-4.0-long-image. Try any of them first in the Kling Image 4.0 playground; every request body below follows the PoYo docs.

Your first Kling Image 4.0 API request with cURL

Create a key in the PoYo dashboard and keep it on your server as POYO_API_KEY. Then submit a 2K text-to-image task:

curl --fail-with-body https://api.poyo.ai/api/generate/submit \
  -H "Authorization: Bearer $POYO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "kling-4.0-image",
    "input": {
      "prompt": "High fashion model wearing a dress made of living moss, standing in an abandoned greenhouse, shafts of light, editorial photography",
      "size": "16:9",
      "resolution": "2K"
    }
  }'

The response has code: 200 and data.task_id, with status: "not_started". A submitted task is not a finished image. Check it with:

curl --fail-with-body \
  https://api.poyo.ai/api/generate/status/YOUR_TASK_ID \
  -H "Authorization: Bearer $POYO_API_KEY"

Statuses are not_started, running, finished and failed. When finished, data.files holds one entry per image with file_url and file_type: "image", and data.credits_amount shows what the task cost. When failed, read data.error_message.

A bounded Python polling loop

This runs on your backend with requests. It checks both the HTTP status and the code field in the body (validation errors can arrive as HTTP 200 with code: 400), stops on failed, and gives up waiting after 20 minutes without resubmitting, because a second submit is a second bill.

import os
import time
import requests

BASE = "https://api.poyo.ai"
session = requests.Session()
session.headers["Authorization"] = "Bearer " + os.environ["POYO_API_KEY"]

def checked(resp):
    resp.raise_for_status()
    body = resp.json()
    if body.get("code") != 200:
        raise RuntimeError(f"PoYo error {body.get('code')}: {body.get('error')}")
    return body["data"]

def run(payload, max_wait=1200, every=10):
    task = checked(session.post(BASE + "/api/generate/submit", json=payload, timeout=60))
    task_id = task["task_id"]
    deadline = time.monotonic() + max_wait
    while time.monotonic() < deadline:
        task = checked(session.get(BASE + "/api/generate/status/" + task_id, timeout=60))
        if task["status"] == "failed":
            raise RuntimeError(task.get("error_message") or "generation failed")
        if task["status"] == "finished":
            return [f["file_url"] for f in task.get("files", []) if f.get("file_type") == "image"]
        time.sleep(every)
    raise TimeoutError("still running, poll task " + task_id + " again later")

urls = run({
    "model": "kling-4.0-image",
    "input": {
        "prompt": "A ceramic pour-over kettle on a walnut counter, morning window light",
        "size": "1:1",
        "resolution": "2K",
    },
})
print(urls)

For long jobs, add a top-level "callback_url": "https://your-domain.com/poyo-hook" to the payload instead. PoYo POSTs the same task data (without the code/data wrapper) when the task finishes or fails, signed with HMAC-SHA256 in X-Webhook-Signature; the webhook docs show how to verify it.

Image-to-image with image_urls

Pass 1 to 10 public HTTP(S) URLs in image_urls. The first is @Image1, the second @Image2, in array order. Give each one a role in the prompt and say what must stay unchanged.

{
  "model": "kling-4.0-image",
  "input": {
    "prompt": "Turn @Image1 into a late-evening scene with warm window light. Keep the furniture, layout and camera angle of @Image1 unchanged.",
    "image_urls": ["https://example.com/living-room.png"],
    "resolution": "2K"
  }
}

image_urls must be an array even for one image. Each image must be at most 30 MB, at least 300 px wide and high, with a width/height ratio between 0.4 and 2.5.

Consistent subjects with kling_elements

An element is one character or object shown from 2 to 4 angles, frontal view first. Elements need at least one image_urls entry, and you can pass up to 7 of them; images plus elements are capped at 10.

{
  "model": "kling-4.0-image",
  "input": {
    "prompt": "Place @Element1 sitting on the sofa in @Image1, reading a book in warm evening light. Keep the room layout of @Image1 unchanged.",
    "image_urls": ["https://example.com/living-room.png"],
    "kling_elements": [
      {
        "element_input_urls": [
          "https://example.com/character-front.png",
          "https://example.com/character-side.png",
          "https://example.com/character-back.png"
        ]
      }
    ],
    "resolution": "2K"
  }
}

This request costs 13 credits for the 2K image plus 1 for the reference image and 1 for the element: 15 credits ($0.075).

Image sets with enable_sequential

With enable_sequential: true, n runs from 2 to 10 (default 4) and the model plans the images as one set with the same subjects and style, returned in order. With it off, n from 1 to 9 returns independent images.

{
  "model": "kling-4.0-image",
  "input": {
    "prompt": "A four-panel story of a paper boat drifting from a rainy city gutter to a calm sunny lake, same boat in every panel, watercolor style",
    "size": "3:2",
    "enable_sequential": true,
    "n": 4
  }
}

In our launch-day test (PoYo production API, November 19, 2026), a 16:9, 2K set with n: 4 returned four 2720×1536 images with the same rider, bike and outfit across dawn, noon, sunset and night. It costs 52 credits and took about 4.9 minutes from submit to result.

Long webpage and ecommerce pages

Switch the model ID to kling-4.0-long-image and pick a skill. A webpage design, optionally following a style reference:

{
  "model": "kling-4.0-long-image",
  "input": {
    "prompt": "Design a long image for a specialty coffee brand's official website, including the hero section, product showcase, roasting philosophy, store information, and footer. Follow the visual style of @StyleImage. All text on the page is in English.",
    "skill": "webpage",
    "style_image_url": "https://example.com/style-reference.png",
    "resolution": "2K"
  }
}

An ecommerce detail page from one product photo:

{
  "model": "kling-4.0-long-image",
  "input": {
    "prompt": "Design a product detail page for the insulated water bottle in @Image1: hero shot, key features, capacity and size, materials, and lifestyle scenes. All text on the page is in English.",
    "skill": "ecommerce",
    "image_urls": ["https://example.com/water-bottle.png"],
    "length": "medium",
    "resolution": "1K"
  }
}

Tip: name the page language. In our test, an English webpage prompt that did not say what language the copy should be in came back with Chinese text on the page. Adding "All text on the page is in English." to the prompt fixed it, which is why both bodies above end with that line. Our 1K webpage test returned one 1024×4257 image for 110 credits in about 1.7–2.2 minutes.

image_urls and length belong to ecommerce; style_image_url and subject_image_url belong to webpage. More on page lengths and 8K output in 8K and long images with the Kling Image 4.0 API.

Saving the results

Each files[].file_url points to a PNG. Copy it to your own storage rather than hot-linking it from your app. Three things from our launch-day run to plan for:

  • Size. One 16:9 8K image was a 10880×6144 PNG of about 128 MB. Stream it to disk instead of loading it into memory, and raise your client's read timeout.
  • Alpha channel. Downloads were RGBA PNGs even for opaque images. If your pipeline, CDN or print workflow expects RGB or JPEG, convert after download.
  • Order. An image set is returned in order, so the index in files is the frame number of your storyboard or slide set.

Validation rules worth checking before you submit

RuleModel
prompt 1–50,000 characters, not just whitespaceboth
image_urls 1–10 items; 30 MB, ≥300 px, ratio 0.4–2.5 eachkling-4.0-image
kling_elements ≤ 7, each 2–4 URLs, only with image_urls; images + elements ≤ 10kling-4.0-image
n 1–9 without a set, 2–10 with enable_sequential: truekling-4.0-image
resolution 2K / 4K / 8Kkling-4.0-image
skill: "ecommerce" needs 1–3 image_urls; resolution 1K / 2Kkling-4.0-long-image
No extra fields (output_format, seed, negative_prompt are rejected)both

Errors worth handling

codeMeaningWhat to do
400Invalid parametersFix the body; do not retry unchanged
401Missing or invalid API keyCheck the header
402Insufficient creditsTop up, then resubmit
429Rate limitBack off and retry later
500 / 502 / 503Server or upstream errorRetry the submit with backoff

A failed task is not charged, so resubmitting after a failure is safe. Resubmitting after a timeout on your side is not: poll the same task_id first.

How your first bill is calculated

kling-4.0-image costs the per-image price times the number of images, plus 1 credit for each image_urls item and each element, once per request. At 1 credit = $0.005:

RequestCreditsUSD
First cURL call above (2K, one image)13$0.065
Same prompt at 8K32$0.16
Element edit above (2K, 1 image + 1 element)15$0.075
Four-image 2K set52$0.26
1K webpage, no references110$0.55
1K medium ecommerce page, 1 product photo95$0.475

Full tables and more examples are in Kling Image 4.0 API pricing. For an overview of both model IDs, see What is Kling Image 4.0.

Frequently asked questions

How do I call the Kling Image 4.0 API with Python? POST the JSON body to https://api.poyo.ai/api/generate/submit with requests, read data.task_id, then poll /api/generate/status/{task_id} until finished and read files[].file_url. The loop above does this with a deadline and error checks.

What is the Kling Image 4.0 API model ID? kling-4.0-image for text-to-image, edits and image sets, and kling-4.0-long-image for long webpage and ecommerce pages. kling-4-0-image is only the page slug.

Does the Kling Image 4.0 API support webhooks? Yes. Add callback_url at the top level of the request. PoYo sends a signed POST when the task finishes or fails.

Can I get JPEG output from the Kling Image 4.0 API? No output format field exists; results are PNG. Our downloads were RGBA PNGs even for opaque images, so convert on your side if you need JPEG.

Why did my Kling Image 4.0 long webpage come back in another language? If the prompt does not name the language of the page copy, the model may choose one. State it, for example "All text on the page is in English."

Share: