Adlark

Guide

Build ad creative with the Adlark API in Python

A working Python script: check credits, generate ad images from product photos, download them, write ad copy and handle errors.

· 7 min read

This guide walks through a small Python script that does what most teams want from an ad API on day one: check the balance, turn a product photo into a few ad images, save them to disk, and write copy to go with them. Everything uses the plain requests library, so it runs anywhere Python 3.9+ runs. The full endpoint list lives in the API docs.

1. Get a key and set it as an environment variable

Create a key in the studio under Account -> API keys. Keys start with adl_. Never paste a key into code you commit; read it from the environment instead.

export ADLARK_KEY="adl_your_key_here"
pip install requests

API calls spend the same credits as the studio, plus 10% (rounded up). There is no separate API plan: a Pro membership or a credit pack covers both. See pricing.

2. A small client with retries

Every response is JSON. Errors come back as {"error": "..."} with a status code. The ones worth handling in code:

StatusMeaningWhat to do
401Missing or wrong keyStop. Fix the key.
402Not enough creditsStop. Top up; retrying will not help.
429Too many requestsWait and retry with backoff.
503A model provider is busy or downWait and retry a few times.
import base64
import os
import time
from pathlib import Path

import requests

BASE = "https://adlark.alexshipit.com"
KEY = os.environ["ADLARK_KEY"]
HEADERS = {"Authorization": f"Bearer {KEY}"}


class AdlarkError(Exception):
    def __init__(self, status, message):
        super().__init__(f"{status}: {message}")
        self.status = status


def call(method, path, *, json=None, files=None, data=None, retries=4):
    """Call the API. Retries 429 and 503 with backoff; raises on anything else."""
    for attempt in range(retries + 1):
        r = requests.request(
            method, BASE + path, headers=HEADERS,
            json=json, files=files, data=data, timeout=300,
        )
        if r.ok:
            return r.json()
        try:
            message = r.json().get("error", r.text)
        except ValueError:
            message = r.text
        if r.status_code in (429, 503) and attempt < retries:
            wait = 2 ** attempt * 2  # 2, 4, 8, 16 seconds
            print(f"{r.status_code}, retrying in {wait}s")
            time.sleep(wait)
            continue
        raise AdlarkError(r.status_code, message)

The timeout is long on purpose. Image calls are synchronous: the request stays open until the images exist, which is usually seconds but can be longer at 2K or with four images.

3. Check credits before a batch

def credits():
    c = call("GET", "/api/v1/credits")
    print(f"{c['credits']} credits ({c['plan_credits']} plan, {c['pack_credits']} pack), rank {c['rank']}")
    return c["credits"]

It is worth estimating before you loop. At the API rate one FLUX.2 klein image costs 9 credits at 1K and 16 at 2K, FLUX.1 schnell drafts cost 5, and an ad copy set costs 6. If the balance is below the batch estimate, stop before you start rather than failing halfway through.

4. Generate ad images from a product photo

FLUX.2 klein (model: "klein") accepts up to four reference images. Send them as base64 strings or data URLs. Use a clean product photo as the first reference; extra angles help keep the label and shape right.

def as_data_url(path):
    p = Path(path)
    mime = "image/png" if p.suffix.lower() == ".png" else "image/jpeg"
    return f"data:{mime};base64," + base64.b64encode(p.read_bytes()).decode()


def generate(prompt, refs=(), aspect="4:5", size="1K", count=2, model="klein"):
    body = {
        "prompt": prompt,
        "model": model,
        "size": size,
        "aspect": aspect,
        "count": count,
    }
    if refs:
        body["reference_images"] = [as_data_url(r) for r in refs[:4]]
    out = call("POST", "/api/v1/images", json=body)
    print(f"job {out['job']} used {out['credits']} credits")
    return out["images"]

Write prompts like a shot list: subject, setting, light, framing, and what space to leave for text. For example: Studio photo of the bottle from the reference on wet black slate, single hard side light, water droplets, centered, empty top third for a headline. More prompt patterns are in AI image prompts for ads.

5. Download the files

Image URLs in the response are private: fetch them with the same bearer header. The helper below also accepts a relative URL, just in case.

def download(url, dest):
    full = url if url.startswith("http") else BASE + url
    r = requests.get(full, headers=HEADERS, timeout=120)
    r.raise_for_status()
    Path(dest).write_bytes(r.content)
    return dest

6. Write the copy

POST /api/v1/copy takes a product name plus optional context and returns angles, hooks, headlines, primary texts, descriptions and CTAs. The more specific the details and offer, the less generic the result.

def write_copy(product, **extra):
    out = call("POST", "/api/v1/copy", json={"product": product, **extra})
    return out["copy"]

7. Put it together

if __name__ == "__main__":
    if credits() < 24:  # two klein 1K images + one copy set
        raise SystemExit("Top up credits first")

    images = generate(
        "The serum bottle from the reference on a bathroom shelf at golden hour, "
        "soft window light, plants out of focus, room at the top for text",
        refs=["bottle-front.jpg"],
        aspect="4:5",
        count=2,
    )
    Path("out").mkdir(exist_ok=True)
    for i, img in enumerate(images):
        download(img["url"], f"out/serum-{i + 1}.png")
        print("saved", img["width"], "x", img["height"])

    copy = write_copy(
        "Vitamin C serum",
        details="15% vitamin C, fragrance free, 30 ml",
        audience="women 25-40 with dull skin",
        offer="20% off first order",
        platform="instagram",
        tone="friendly",
        language="English",
    )
    for key in ("hooks", "headlines", "ctas"):
        print(key.upper())
        for line in copy.get(key, []):
            print(" -", line)

The balance check uses today's API prices (9 per klein 1K image, 6 per copy set). Adjust it to the models and sizes you actually use; current prices are on pricing.

Other endpoints in the same style

  • POST /api/v1/ugc-script with product and length (15, 30 or 60) returns a scene-by-scene script (6 credits).
  • POST /api/v1/voiceover with text and a voice (thalia, andromeda, helena, apollo, arcas, orion) returns audio.url (15 credits per 1,000 characters).
  • POST /api/v1/analyze is multipart: pass files={"file": open("ad.mp4", "rb")} and data={"caption": "...", "platform": "tiktok"} to call (56 credits).
  • POST /api/v1/captions is multipart too: file plus data={"style": "bold-pop"}. It returns video.url and srt.url (28 credits).
  • GET /api/v1/jobs/{id} returns the status and output of any job id you got back, which is handy for logging and re-downloading.

Practical tips

  • Store the job id with every output. It is the simplest audit trail when a client asks where an image came from.
  • Draft with schnell (text only, cheapest), then re-run the winning prompt with klein and your product references.
  • Run requests one or two at a time. Firing fifty in parallel mostly buys you 429s.
  • Video generation is not in the API yet; see video generation API for what is planned.

Prefer JavaScript? The same flow is in Build with the API in JavaScript.

Make your next ad today

Pro is $39.99 a month with 3,000 credits. Cancel anytime.