Explain it simply
Explain it simply
Text APIs return words wrapped in JSON. An image API returns a picture, and a picture is bytes. Stability AI's Stable Image Core endpoint takes a prompt and sends an image back, which changes two habits you built in the earlier lessons. The request is a form, the kind a browser sends for a file upload, called multipart/form-data, instead of a JSON body. And one header decides whether the reply is the picture itself or the picture wrapped as text.
Think of ordering a print from a photo lab. You fill in an order form, which is the multipart request. Then you say whether you want the print in an envelope, which is binary, or a scanned copy by email, which is base64 inside JSON.
Problem → Why → Solution
The problem: binary replies break JSON habits
The curl command below works on the first try, and that is exactly the trap. In code, someone calls res.json() on the success response and gets a SyntaxError, because the body is PNG bytes. Someone else keeps curl's --output flag in a script, so when the key is wrong the JSON error text is saved into out.png and the picture will not open.
A third person trusts the .png name and stores or serves whatever came back. A file name is a label, not evidence, and generated media should be treated like any other untrusted upload.
# works once; on a 4xx/5xx the error JSON is written into out.png as well
curl -X POST "https://api.stability.ai/v2beta/stable-image/generate/core" \
-H "Authorization: Bearer $STABILITY_API_KEY" \
-H "Accept: image/*" \
-F "prompt=Myanmar landscape at sunrise" \
--output out.pngThree assumptions that fail at once
JSON habits assume that every body is text, that every status code has the same content type and that a name tells you what a file is. An image endpoint breaks all three: success is binary, errors are JSON, and only the first bytes say what the file really is. The fix is to check the status first, read the body in the way the Accept header promised, and verify the signature before storing anything.
Core concept: a form in, bytes or base64 out
The facts below come from Stability AI's API reference. Endpoints and parameters are still under the v2beta path, so keep the docs open when you build on them.
1. Endpoint, base URL and key
Send POST to https://api.stability.ai/v2beta/stable-image/generate/core with the header Authorization: Bearer $STABILITY_API_KEY. A missing or invalid key returns 401. Each successful request consumes credits, and the amount depends on the service; the Pricing page lists the cost of each one.
2. A multipart/form-data body
Generation endpoints take their text parameters as form fields. For Stable Image Core only prompt is required. Optional fields include aspect_ratio, negative_prompt, seed, style_preset and output_format, which can be png, jpeg or webp and defaults to png. In curl you write -F name=value; in JavaScript you build a FormData object and let fetch add the Content-Type with its boundary.
3. Accept chooses the reply format
Send Accept: image/* to receive the image bytes in the format given by output_format. Send Accept: application/json to receive JSON with the image encoded as base64 in an image field, plus seed and finish_reason. Base64 turns every three bytes into four characters, so the JSON route moves roughly a third more data.
4. finish-reason: success or filtered
Binary replies carry seed and finish-reason as response headers; JSON replies carry seed and finish_reason as fields. SUCCESS is a normal image. CONTENT_FILTERED means the generation worked but the output violated the content moderation policy and was blurred, so check it before you show or store the picture.
5. Errors are JSON with a name and a list
A failure returns JSON with an id, a machine-readable name and an errors list of readable strings, for example name bad_request with errors ["prompt: is required"]. Check res.ok before you treat the body as an image, because the error is JSON even when you asked for image bytes.
| Status | Meaning | What to do |
|---|---|---|
| 400 | Invalid parameter | Read errors, fix the form |
| 403 | Flagged by moderation | Do not retry the same prompt |
| 413 | Request body too large | Send smaller inputs |
| 422 | Cannot be processed | Check the input image |
| 429 | Rate limit exceeded | Back off, then retry |
| 500 | Server-side problem | Retry, then contact support |
- Form fields describe the picture
- Accept picks bytes or base64
- Check status, then check the bytes
- Save to a safe place, then use it
A successful HTTP status says the call worked. It does not say the bytes are what you expect; only the signature and the finish reason can tell you that.
General pattern
curl -X POST "https://api.stability.ai/v2beta/stable-image/generate/core" \
-H "Authorization: Bearer $STABILITY_API_KEY" \
-H "Accept: image/*" \
-F "prompt=<prompt>" \
-F "output_format=<png|jpeg|webp>" \
--output <file-name>Every -F is one form field, and --output saves the reply. The angle-bracket parts are placeholders. This is illustrative: check the current docs and keep your key in an environment variable.
Binary and JSON replies, then checking the bytes
The mock server parses the multipart form and answers in the documented shapes: raw PNG bytes with seed and finish-reason headers, or JSON with a base64 image, and JSON errors with an id, a name and an errors list. The client sends the same form twice, once with each Accept value, checks the first bytes of each reply, writes the file into a temporary directory and removes the directory at the end.
import http from "node:http";
import { mkdtemp, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
const KEY = "sk-demo-stability-key";
// A real 1x1 PNG, so the byte checks below have something genuine to inspect.
const PNG_BASE64 =
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAC" +
"hwGA60e6kgAAAABJRU5ErkJggg==";
const PNG = Buffer.from(PNG_BASE64, "base64");
// Mock server: same SHAPE as POST /v2beta/stable-image/generate/core.
const server = http.createServer((req, res) => {
const chunks = [];
req.on("data", (chunk) => chunks.push(chunk));
req.on("end", async () => {
const fail = (status, name, errors) => {
res.writeHead(status, { "content-type": "application/json" });
res.end(JSON.stringify({ id: "demo", name, errors }));
};
if (req.headers.authorization !== "Bearer " + KEY) {
return fail(401, "unauthorized", ["invalid or missing API key"]);
}
const contentType = req.headers["content-type"] ?? "";
const form = await new Response(Buffer.concat(chunks), {
headers: { "content-type": contentType },
}).formData();
const prompt = form.get("prompt");
if (!prompt) return fail(400, "bad_request", ["prompt: is required"]);
if (prompt === "forbidden") {
return fail(403, "content_moderation", ["flagged by content moderation"]);
}
const finish = prompt === "borderline" ? "CONTENT_FILTERED" : "SUCCESS";
if ((req.headers.accept ?? "").includes("application/json")) {
res.writeHead(200, { "content-type": "application/json" });
return res.end(
JSON.stringify({ image: PNG.toString("base64"), seed: 7, finish_reason: finish }),
);
}
res.writeHead(200, {
"content-type": "image/png",
seed: "7",
"finish-reason": finish,
});
res.end(PNG);
});
});
// Client: multipart request, Accept header chooses binary or base64 JSON.
async function generate(base, fields, accept) {
const form = new FormData();
for (const [name, value] of Object.entries(fields)) form.append(name, value);
const res = await fetch(base + "/v2beta/stable-image/generate/core", {
method: "POST",
headers: { authorization: "Bearer " + KEY, accept },
body: form, // fetch adds the multipart boundary itself
});
if (!res.ok) {
const err = await res.json();
throw new Error(res.status + " " + err.name + ": " + err.errors.join(", "));
}
if (accept === "application/json") {
const data = await res.json();
return { bytes: Buffer.from(data.image, "base64"), finish: data.finish_reason };
}
const bytes = Buffer.from(await res.arrayBuffer());
return { bytes, finish: res.headers.get("finish-reason") };
}
// Never trust a file extension or a content-type: look at the first bytes.
function sniff(bytes) {
if (bytes.subarray(0, 4).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47]))) return "png";
if (bytes.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff]))) return "jpeg";
const riff = bytes.subarray(0, 4).toString() === "RIFF";
if (riff && bytes.subarray(8, 12).toString() === "WEBP") return "webp";
return null;
}
await new Promise((resolve) => server.listen(0, resolve));
const base = "http://127.0.0.1:" + server.address().port;
const dir = await mkdtemp(join(tmpdir(), "stability-demo-"));
const fields = { prompt: "Myanmar landscape at sunrise", aspect_ratio: "16:9" };
for (const accept of ["image/*", "application/json"]) {
const { bytes, finish } = await generate(base, fields, accept);
const kind = sniff(bytes);
if (!kind) throw new Error("the reply is not an image");
const file = join(dir, "out." + kind);
await writeFile(file, bytes);
const size = (await stat(file)).size;
console.log(accept, "->", kind, size, "bytes, finish:", finish);
}
const filtered = await generate(base, { prompt: "borderline" }, "image/*");
console.log("filtered image finish:", filtered.finish, "(blurred, do not publish)");
for (const body of [{ aspect_ratio: "1:1" }, { prompt: "forbidden" }]) {
try {
await generate(base, body, "image/*");
} catch (err) {
console.log("error:", err.message);
}
}
await rm(dir, { recursive: true });
server.close();Code breakdown
- A form, not JSON
for (const [name, value] of Object.entries(fields)) form.append(name, value);Each field becomes one part of the multipart body. Adding a field such as aspect_ratio is one more key in the fields object.
- No hand-written Content-Type
body: form, // fetch adds the multipart boundary itselffetch sees a FormData body and writes Content-Type with the correct boundary. Setting that header yourself would leave the server unable to split the parts.
- Status before body
if (!res.ok) {The 400 and 403 replies are JSON even though the request asked for image bytes, so the error branch runs before any arrayBuffer() call.
- Binary: arrayBuffer
const bytes = Buffer.from(await res.arrayBuffer());Binary data is read with arrayBuffer(), never with text() or json(), which would corrupt or reject it. The finish reason comes from the finish-reason header.
- JSON: decode base64
return { bytes: Buffer.from(data.image, "base64"), finish: data.finish_reason };The image field holds base64 text. Decoding it gives the same 70 bytes as the binary route, which the output confirms for both Accept values.
- Sniff the signature
if (bytes.subarray(0, 4).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47]))) return "png";A PNG always begins with the bytes 89 50 4E 47. The saved file name uses the detected kind, not text from the request or the reply headers.
image/* -> png 70 bytes, finish: SUCCESS
application/json -> png 70 bytes, finish: SUCCESS
filtered image finish: CONTENT_FILTERED (blurred, do not publish)
error: 400 bad_request: prompt: is required
error: 403 content_moderation: flagged by content moderationThe same call in curl
Both commands are illustrative: check the current docs and use your own key in STABILITY_API_KEY. The -f flag makes curl exit with an error instead of saving an error body as an image, and -sS hides the progress meter but keeps error messages. The second command asks for JSON and decodes the image field with jq and base64.
# Illustrative - check the current docs, and use your own key in STABILITY_API_KEY.
# -f: exit with an error instead of saving the API error body as sunrise.png.
curl -sS -f -X POST "https://api.stability.ai/v2beta/stable-image/generate/core" \
-H "Authorization: Bearer $STABILITY_API_KEY" \
-H "Accept: image/*" \
-F "prompt=Myanmar landscape at sunrise" \
-F "aspect_ratio=16:9" \
-F "output_format=png" \
--output sunrise.png# Illustrative: ask for JSON instead, then decode the base64 field yourself.
curl -sS -f -X POST "https://api.stability.ai/v2beta/stable-image/generate/core" \
-H "Authorization: Bearer $STABILITY_API_KEY" \
-H "Accept: application/json" \
-F "prompt=Myanmar landscape at sunrise" \
-o response.json
jq -r '.finish_reason' response.json
jq -r '.image' response.json | base64 --decode > sunrise.pngSaving generated files safely
Generated media is bytes from a network service, so give it the same care as a user upload.
- Build the file name yourself from an id you generate and the type you detected, never from prompt text.
- Cap the size you accept, and store files outside the directory your web server publishes.
- When you serve a file, send the detected content type and X-Content-Type-Options: nosniff.
- Keep seed and finish reason with the record, so a result can be reproduced and a filtered one can be hidden.
Credits, limits and moderation
Every successful request spends credits, so a loop with a bug becomes a bill. The API allows up to 150 requests in any 10-second window; going over returns 429 and blocks your requests for 60 seconds, so a shared limiter in your own back end is safer than reacting to the 429. A 403 from moderation or a CONTENT_FILTERED reply means the prompt or the result broke the policy, and repeating the same prompt will not change that. Decide up front what your product shows in that case, and what your policy says about copyright and privacy for generated images.
In real projects
How to apply it in a real project
Imagine a marketing tool where staff generate banner images. The browser never sees the Stability key: it calls your endpoint, which checks the signed-in user and a per-user daily quota and only then calls Stability. The endpoint sends Accept: image/*, checks the status, checks the signature and the finish reason, and stores the file in object storage under a name it generated, together with the seed and the prompt.
A 403 or a CONTENT_FILTERED result shows the user a clear message instead of a broken image. A 429 goes back onto a queue with a delay. The tests use a mock endpoint that returns a binary success, a JSON error, a moderation rejection, a 429, an oversized body and a reply with the wrong content type, so every path has run before a real user triggers it.
Common mistakes
Common mistakes
Four mistakes cause nearly all broken-image bugs.
Calling res.json() on a binary success
With Accept: image/* the success body is image bytes, so res.json() throws. Read it with arrayBuffer(), or ask for application/json and decode the image field yourself.
Saving every reply into the image file
Plain curl --output writes whatever arrives, including a JSON error body. Use -f in scripts, and in code branch on res.ok before touching the file.
Trusting the file name or the content type
Both are labels that can be wrong. Check the first bytes of the file, cap the size and name the stored file yourself.
Setting Content-Type by hand on a multipart request
Writing Content-Type: multipart/form-data without a boundary leaves the server unable to read your fields, and you get a 400. Pass a FormData body and let fetch set the header.
Best practices
Habits worth keeping
- Log status, finish reason and seed for every call, but never the key.
- Prefer the binary reply for storage pipelines and the JSON reply when the image travels inside another JSON document.
- Put the generation behind a queue with a shared rate limiter so a burst cannot reach the 429 block.
Mini challenge
Build a reply checker
Write checkReply(res) for image replies. It reads the body as base64 JSON or as raw bytes depending on the content-type, refuses a CONTENT_FILTERED finish reason, refuses bodies over 100 bytes, detects PNG, JPEG or WebP by signature, and returns text such as png (70 bytes). Prove it with a mock server on port 0 that has an honest binary path, a JSON path, a filtered path, a liar path and a huge path.
- Decode the image field from base64 when the content-type contains json
- Refuse CONTENT_FILTERED from either the header or the JSON field
- Detect the format from the first bytes, and refuse anything that is not an image
- Refuse bodies over the byte limit with a message that shows both numbers
import http from "node:http";
const MAX_BYTES = 100;
function detect(bytes) {
// TODO 1: look at the first bytes and return "png" (89 50 4E 47), "jpeg" (FF D8 FF)
// or "webp" ("RIFF" at 0-3 and "WEBP" at 8-11); return null for anything else
return null;
}
async function checkReply(res) {
// TODO 2: if the content-type contains "json", read { image, finish_reason } and
// decode image from base64; otherwise read the body bytes and the
// finish-reason response header
// TODO 3: throw "CONTENT_FILTERED" when the finish reason says so
// TODO 4: throw "<n> bytes is over the 100 byte limit" for a body over MAX_BYTES
// TODO 5: throw "not a PNG, JPEG or WebP image" when detect() finds nothing
// TODO 6: return a text such as "png (70 bytes)"
return "";
}
// TODO 7: start a mock server on port 0 with five paths: /binary (a real PNG),
// /json (the same PNG as base64), /filtered (a PNG with the CONTENT_FILTERED
// header), /liar (HTML sent as image/png) and /huge (a PNG followed by 200 zero bytes)
// A 1x1 PNG in base64, to be joined into one string:
// iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAC
// hwGA60e6kgAAAABJRU5ErkJggg==
// TODO 8: request every path, print "<path> -> accepted <result>" or
// "<path> -> refused: <message>", then close the serverExpected: Five lines: /binary and /json are accepted as png (70 bytes), /filtered is refused with CONTENT_FILTERED, /liar is refused because it is not an image, and /huge is refused for being 270 bytes over a 100 byte limit.
Show hint
Read the finish reason before the size and the signature. Buffer.toString("latin1", 0, 4) gives you the RIFF marker, and Array.prototype.every compares a signature array with the first bytes.
Show solution
import http from "node:http";
const PNG = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAC" +
"hwGA60e6kgAAAABJRU5ErkJggg==",
"base64",
);
const MAX_BYTES = 100;
// The first bytes of a file say what it really is, whatever the name or header claims.
const MAGIC = { png: [0x89, 0x50, 0x4e, 0x47], jpeg: [0xff, 0xd8, 0xff] };
function detect(bytes) {
for (const [kind, magic] of Object.entries(MAGIC)) {
if (magic.every((value, i) => bytes[i] === value)) return kind;
}
const head = bytes.toString("latin1", 0, 4);
if (head === "RIFF" && bytes.toString("latin1", 8, 12) === "WEBP") return "webp";
return null;
}
async function checkReply(res) {
const isJson = (res.headers.get("content-type") ?? "").includes("json");
const body = isJson ? await res.json() : null;
const raw = body ? body.image : await res.arrayBuffer();
const bytes = body ? Buffer.from(raw, "base64") : Buffer.from(raw);
const finish = body ? body.finish_reason : res.headers.get("finish-reason");
if (finish === "CONTENT_FILTERED") throw new Error("CONTENT_FILTERED");
if (bytes.length > MAX_BYTES) {
throw new Error(bytes.length + " bytes is over the " + MAX_BYTES + " byte limit");
}
const kind = detect(bytes);
if (!kind) throw new Error("not a PNG, JPEG or WebP image");
return kind + " (" + bytes.length + " bytes)";
}
// Mock server: five replies, some of them dishonest.
const server = http.createServer((req, res) => {
const send = (type, body, extra = {}) => {
res.writeHead(200, { "content-type": type, ...extra });
res.end(body);
};
if (req.url === "/binary") return send("image/png", PNG);
if (req.url === "/json") {
const image = PNG.toString("base64");
return send("application/json", JSON.stringify({ image, finish_reason: "SUCCESS" }));
}
if (req.url === "/filtered") {
return send("image/png", PNG, { "finish-reason": "CONTENT_FILTERED" });
}
if (req.url === "/liar") return send("image/png", "<html>sorry</html>");
send("image/png", Buffer.concat([PNG, Buffer.alloc(200)]));
});
await new Promise((resolve) => server.listen(0, resolve));
const base = "http://127.0.0.1:" + server.address().port;
for (const path of ["/binary", "/json", "/filtered", "/liar", "/huge"]) {
try {
console.log(path, "-> accepted", await checkReply(await fetch(base + path)));
} catch (err) {
console.log(path, "-> refused:", err.message);
}
}
server.close();Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A request is POST /v2beta/stable-image/generate/core with a Bearer key and a multipart/form-data body where prompt is the only required field.
- Accept: image/* returns raw bytes, and Accept: application/json returns base64 in an image field; read each with the right method.
- Check res.ok first, then finish-reason, then the first bytes of the file, before you store or show it.
- Errors are JSON with id, name and errors; 429 means more than 150 requests in 10 seconds and a 60 second block.
Stability AI — API Reference — Stability AI