Skip to content
mentoor

Topic 1 of 6 · 4 min read

Calling image generation APIs from a product

Goal: Write a server-side image generation call with size, quality, timeout and storage handled, and spot a call that leaks user input or keys.

Treat an image call as a slow, paid, untrusted-input job that runs on your server: set size and quality on purpose, give it a timeout, copy the result into your own storage, and never pass raw user text or your key through the browser.

Check yourself · 1 of 3

A web app calls the image API straight from the browser with the team's key. What is the main problem?

Choose one answer

Why it matters

An image call is unlike a text call. It can take many seconds, it costs real money per image, and the URL or bytes you get back may not live long. If the call sits in client code, the API key ships to every visitor. If the user's text goes straight into the prompt, the user controls what you generate and pay for.

How to do it

  1. Call from your server. The browser sends a short request to your endpoint. Your endpoint holds the key, builds the prompt and calls the provider.
  2. Set size and quality explicitly. OpenAI's image endpoint takes size and quality; Gemini and FLUX expose similar controls such as aspect ratio. Defaults are rarely the cheapest choice. Use a small, low-quality setting for previews and the final setting only after the user accepts.
  3. Match the endpoint style. Some providers return the image in the response. FLUX returns a job id and a polling address, so you poll until the job is ready. Treat both as a job with a state: queued, running, done, failed.
  4. Add a timeout and a limited retry. Retry only on timeouts and 5xx errors, with a pause between tries, and cap the number. A retry is a new paid image.
  5. Store the result yourself. Write the bytes to your own bucket under your own key, and save the path in your database. Provider links expire.
  6. Wrap user text in a template. Put the user's words in a labelled slot inside a prompt you wrote, after length limits and moderation.

Before and after

// Before: key in the browser, raw input, no limits
const res = await fetch("https://api.openai.com/v1/images/generations", {
  method: "POST",
  headers: { Authorization: `Bearer ${OPENAI_KEY}` },
  body: JSON.stringify({ prompt: userText }),
});
// After: server route, template, explicit settings, timeout, own storage
app.post("/api/images", async (req, res) => {
  const subject = clean(req.body.subject, 200);
  const prompt = `Studio product photo of ${subject}, white background`;
  const out = await client.images.generate(
    { model: IMAGE_MODEL, prompt, size: "1024x1024", quality: "low" },
    { timeout: 60_000, maxRetries: 1 },
  );
  const key = await storage.put(`images/${req.user.id}/${newId()}.png`, decode(out));
  res.json({ key });
});

What goes wrong

  • The key is bundled into a mobile or web app and is scraped within days.
  • The request waits for a slow job while the HTTP gateway times out at thirty seconds, so the user sees an error for an image that was still billed.
  • The code saves the provider's temporary URL, and the image is gone next week.
  • A retry loop with no cap turns one outage into hundreds of paid calls.

Examples

Preview first, final later

A poster tool calls the endpoint with a small size and quality: "low" for the first look. Only when the user presses Save does the server call again at full size. Most abandoned drafts cost the cheap price.

Polling a FLUX-style job

const job = await submit(prompt);          // returns { id, pollingUrl }
for (let i = 0; i < 30; i++) {
  const r = await poll(job.pollingUrl);
  if (r.status === "Ready") return download(r.resultUrl);
  if (r.status === "Failed") throw new Error("generation failed");
  await sleep(2000);
}
throw new Error("timed out");

The loop has a ceiling, so a stuck job ends as a clear error and not a hung request.

Key points

  • Call image APIs from your server so the key never reaches a browser or app bundle.
  • Set size and quality on purpose, and use cheap settings for previews.
  • Some providers return a job to poll, so model the call as a job with states and a timeout.
  • Copy the result into your own storage; provider URLs and returned files are not permanent.
  • Put user text into a labelled slot of your own prompt template, after length limits and moderation.

Common mistakes

  • Calling the provider from browser or mobile code with the real key.
  • Sending the user's text as the whole prompt instead of a slot in a template.
  • Keeping the provider's result URL instead of copying the file to your own storage.
  • Retrying without a cap or a pause, so one outage becomes many paid calls.

Check yourself · 2 of 3

Your provider returns a temporary image URL. Users open their gallery a month later and see broken images. What should the server have done?

Choose one answer

Check yourself · 3 of 3

Which retry rule is safest for an image generation call?

Choose one answer

Practice items, not counted towards your mastery.

Start here

Where to go in your country