Guide
Build ad creative with the Adlark API in JavaScript
Node 20+ and TypeScript examples: credits, ad images from reference photos, downloads, copy, plus multipart uploads for analysis and captions.
· 7 min read
Node 20 and later ship fetch, FormData and Blob, so you need no packages at all to use the Adlark API. This guide builds a small typed client, then uses it to make images, copy, an ad analysis and a captioned video. Field names match the API docs.
Setup
Create a key under Account -> API keys in the studio and keep it in an environment variable. Run the examples as .mjs files, or as TypeScript with npx tsx script.ts.
export ADLARK_KEY="adl_your_key_here"Keys are server-side only. Do not ship one in browser code or a mobile app: anyone could read it and spend your credits. Call the API from your backend, a serverless function or a script.
A typed client with retries
const BASE = "https://adlark.alexshipit.com";
const KEY = process.env.ADLARK_KEY;
if (!KEY) throw new Error("Set ADLARK_KEY");
const auth = { Authorization: `Bearer ${KEY}` };
export class AdlarkError extends Error {
constructor(public status: number, message: string) {
super(`${status}: ${message}`);
}
}
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
export async function call<T>(path: string, init: RequestInit = {}, retries = 4): Promise<T> {
for (let attempt = 0; ; attempt++) {
const res = await fetch(BASE + path, {
...init,
headers: { ...auth, ...(init.headers ?? {}) },
});
if (res.ok) return (await res.json()) as T;
const body = (await res.json().catch(() => ({}))) as { error?: string };
// 429 = slow down, 503 = provider busy: retry. 402 = out of credits: stop.
if ((res.status === 429 || res.status === 503) && attempt < retries) {
await sleep(2000 * 2 ** attempt);
continue;
}
throw new AdlarkError(res.status, body.error ?? res.statusText);
}
}
const json = (body: unknown): RequestInit => ({
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});Note that the multipart calls below pass a FormData body without a Content-Type header; fetch sets the boundary itself. Setting it by hand is the most common reason an upload fails.
Credits
type Credits = { credits: number; plan_credits: number; pack_credits: number; rank: string };
const c = await call<Credits>("/api/v1/credits");
console.log(`${c.credits} credits, rank ${c.rank}`);API prices are studio credits plus 10%, rounded up: 9 credits per FLUX.2 klein image at 1K, 16 at 2K, 5 per FLUX.1 schnell draft, 6 per copy set, 56 per analysis and 28 per captioned video. A 402 means the balance ran out; retrying will not help.
Images from product photos
import { readFile, writeFile, mkdir } from "node:fs/promises";
type ImageOut = { job: string; credits: number; images: { url: string; width: number; height: number }[] };
async function dataUrl(path: string) {
const mime = path.endsWith(".png") ? "image/png" : "image/jpeg";
return `data:${mime};base64,${(await readFile(path)).toString("base64")}`;
}
const out = await call<ImageOut>("/api/v1/images", json({
prompt: "The sneaker from the reference mid-air over a wet city street at night, neon reflections, low angle, empty space at the top for a headline",
model: "klein",
size: "1K",
aspect: "9:16",
count: 2,
reference_images: [await dataUrl("shoe-side.jpg"), await dataUrl("shoe-top.jpg")],
}));
console.log(`job ${out.job}: ${out.credits} credits`);Up to four references are accepted. Use your sharpest packshot first; the others can show angles or the logo up close. FLUX.1 schnell (model: "schnell") ignores references and is meant for cheap concept drafts.
Download with the same bearer header
Output URLs are private to your account, so a plain <img src> will not work for them. Download them on the server and host the files wherever you like.
async function download(url: string, dest: string) {
const full = url.startsWith("http") ? url : BASE + url;
const res = await fetch(full, { headers: auth });
if (!res.ok) throw new AdlarkError(res.status, "download failed");
await writeFile(dest, Buffer.from(await res.arrayBuffer()));
}
await mkdir("out", { recursive: true });
for (const [i, img] of out.images.entries()) {
await download(img.url, `out/shoe-${i + 1}.png`);
}Ad copy
type CopyOut = { job: string; credits: number; copy: Record<string, unknown[]> };
const { copy } = await call<CopyOut>("/api/v1/copy", json({
product: "Trail running shoe",
details: "Vibram outsole, 240 g, waterproof upper",
audience: "weekend trail runners",
offer: "free returns for 60 days",
platform: "tiktok",
tone: "energetic",
language: "English",
}));
for (const key of ["hooks", "headlines", "ctas"]) {
console.log(key, (copy[key] ?? []).map(String));
}Multipart: analyze an ad
/api/v1/analyze takes a file (image or video) plus an optional caption and platform. It returns the analysis, the transcript for videos and the key frames it looked at.
type AnalyzeOut = { job: string; credits: number; analysis: unknown; transcript: unknown; frames: unknown };
async function fileField(path: string, type: string) {
return new Blob([await readFile(path)], { type });
}
const form = new FormData();
form.append("file", await fileField("competitor-ad.mp4", "video/mp4"), "competitor-ad.mp4");
form.append("caption", "POV: you finally found running shoes that don't hurt");
form.append("platform", "tiktok");
const report = await call<AnalyzeOut>("/api/v1/analyze", { method: "POST", body: form });
console.log(JSON.stringify(report.analysis, null, 2));Multipart: burn captions into a video
type CaptionsOut = { job: string; credits: number; video: { url: string }; srt: { url: string } };
const cap = new FormData();
cap.append("file", await fileField("ugc-take.mp4", "video/mp4"), "ugc-take.mp4");
cap.append("style", "karaoke"); // bold-pop | clean | boxed | neon | karaoke
cap.append("uppercase", "true");
const done = await call<CaptionsOut>("/api/v1/captions", { method: "POST", body: cap });
await download(done.video.url, "out/ugc-captioned.mp4");
await download(done.srt.url, "out/ugc-take.srt");The SRT file is useful even when you keep the burned-in version: upload it as a separate caption track where the platform supports one.
Voiceover and UGC scripts
type VoiceOut = { job: string; credits: number; audio: { url: string } };
const vo = await call<VoiceOut>("/api/v1/voiceover", json({
text: "I ran twelve miles in these on Saturday. Zero blisters.",
voice: "helena",
}));
await download(vo.audio.url, "out/vo.mp3");
type ScriptOut = { job: string; credits: number; script: unknown };
const s = await call<ScriptOut>("/api/v1/ugc-script", json({ product: "Trail running shoe", length: 30 }));
console.log(s.script);The saved file extension above is a guess for convenience; check the response Content-Type if your pipeline cares.
Things to get right in production
- Keep one or two requests in flight per key. The retry helper absorbs the occasional 429, but it cannot fix a flood.
- Log
jobids next to your own records.GET /api/v1/jobs/{id}gives the status and output again later. - Treat 402 as a business event, not an error to retry: alert someone and pause the queue.
- Video generation is coming soon, not live. Today you can storyboard, voice and caption; see video generation API.
Using Python instead? See Build with the API in Python. Want to skip code entirely? Try n8n or Make.