# Lahjty Partner API Guide

Last reviewed: 2026-09-05

Base URL: https://www.lahjty.com/api/v1

This is the canonical machine-readable integration guide. The localized human documentation is at https://www.lahjty.com/en/api-docs and https://www.lahjty.com/ar/api-docs. The authoritative schemas are at https://www.lahjty.com/api/v1/openapi and live values are at https://www.lahjty.com/api/v1/capabilities.

## Authentication

Send partner keys only from a trusted server:

~~~http
Authorization: Bearer lhj_live_replace_with_your_key
Content-Type: application/json
Idempotency-Key: one-unique-value-per-logical-operation
~~~

Never expose a partner key in a browser, mobile binary, public prompt, log, screenshot, analytics event, or repository. Every billable POST requires an Idempotency-Key of 1–200 characters.

## Server helpers

Persist one operation key and the exact request body before sending. Reuse both after a timeout, network error, 429, 5xx, or 409 request_in_progress; honor Retry-After and bound retries. A 409 idempotency_conflict requires correcting your integration, not retrying with a new key. The helpers never create a key or retry automatically.

The examples allocate a key once to illustrate a new operation. In a job system, save it with the job and load that same value on every attempt, including after a process restart. Do not rerun the key-allocation line when retrying.

The endpoint examples below use this TypeScript helper:

~~~ts
async function lahjty(
  path: string,
  init: { method?: "GET" } | { method: "POST"; body: unknown; idempotencyKey: string } = {},
) {
  const method = init.method ?? "GET";
  if (init.method === "POST" && !init.idempotencyKey?.trim()) {
    throw new Error("Persist an Idempotency-Key for this logical operation first");
  }
  const response = await fetch(
    "https://www.lahjty.com/api/v1" + path,
    {
      method,
      headers: {
        Authorization: "Bearer " + process.env.LAHJTY_API_KEY,
        ...(init.method === "POST"
          ? {
              "Content-Type": "application/json",
              "Idempotency-Key": init.idempotencyKey,
            }
          : {}),
      },
      body: init.method === "POST" ? JSON.stringify(init.body) : undefined,
    },
  );
  const result = await response.json();
  if (!response.ok) {
    throw Object.assign(new Error(result.code + ": " + result.detail), {
      status: response.status, code: result.code, requestId: result.request_id,
      retryAfter: response.headers.get("Retry-After"),
    });
  }
  return result;
}
~~~

Python:

~~~python
import os
import uuid
import requests

def lahjty(path, method="GET", payload=None, *, idempotency_key=None):
    headers = {"Authorization": "Bearer " + os.environ["LAHJTY_API_KEY"]}
    if method == "POST":
        if not idempotency_key or not idempotency_key.strip():
            raise ValueError("Persist an Idempotency-Key for this operation first")
        headers["Content-Type"] = "application/json"
        headers["Idempotency-Key"] = idempotency_key
    response = requests.request(
        method,
        "https://www.lahjty.com/api/v1" + path,
        headers=headers,
        json=payload,
        timeout=150,
    )
    response.raise_for_status()
    return response.json()
~~~

## 1. Capabilities

GET /capabilities is public, free, and authoritative for supported values, credit costs, scopes, and rate limits. Image prices depend on the rendered resolution: `credit_costs` includes `image`, `image_2k`, `image_edit` and `image_edit_2k`, and `image_controls.credits_by_resolution`, `image_edits.credits_by_resolution` and `ad_library.generation_credits_by_resolution` map each tier to its credits.

~~~bash
curl https://www.lahjty.com/api/v1/capabilities
~~~

~~~ts
const capabilities = await lahjty("/capabilities");
~~~

~~~python
capabilities = lahjty("/capabilities")
~~~

## 2. Arabic and English copy

POST /copy-generations costs 2 credits for ad copy or headlines.

~~~ts
const operationKey = crypto.randomUUID(); // Save with your job before sending.
const copy = await lahjty("/copy-generations", {
  method: "POST",
  idempotencyKey: operationKey,
  body: {
    type: "ad_copy",
    description: "Weekend offer: 20% off specialty coffee subscriptions",
    output_language: "ar",
    market: "SA",
    dialect: "saudi",
    platform: "whatsapp",
    tone: "warm",
    framework: "aida",
    audience: "specific",
    specific_audience: "Young professionals in Riyadh",
    required_keywords: ["قهوة مختصة"],
    excluded_keywords: ["مجاني"],
    call_to_action: "اطلب الآن",
    external_customer_id: "merchant-91",
  },
});
~~~

~~~python
operation_key = str(uuid.uuid4())  # Save with your job before sending.
copy = lahjty("/copy-generations", "POST", {
    "type": "ad_copy",
    "description": "Weekend offer: 20% off specialty coffee subscriptions",
    "output_language": "ar",
    "market": "SA",
    "dialect": "saudi",
    "platform": "whatsapp",
    "framework": "aida",
    "required_keywords": ["قهوة مختصة"],
    "excluded_keywords": ["مجاني"],
    "call_to_action": "اطلب الآن",
},
    idempotency_key=operation_key,
)
~~~

For English copy or headlines, set output_language to en, include an ISO market such as AE, and omit dialect. English is supported; English dialects are not. The v1 response returns `"dialect": "none"` as a backward-compatible string sentinel; it is not an English dialect selector. For headlines, set type to headlines.

For Arabic dialect conversion, set type to dialect_conversion, pass the approved Arabic text as description, and include target_dialect. Source Arabic variety is auto-detected; source_dialect is optional. Conversion costs 1 credit.

~~~json
{
  "type": "dialect_conversion",
  "description": "قهوتك المفضلة توصلك لين باب البيت. اطلب الآن.",
  "output_language": "ar",
  "market": "IQ",
  "source_dialect": "saudi",
  "target_dialect": "iraqi",
  "platform": "whatsapp"
}
~~~

## 3. Campaign image

POST /image-generations costs 5 credits at 1K (the default) or 8 credits at 2K, and returns a durable private media URL. The deprecated `512` tier is rendered and charged as 1K. A failed attempt refunds exactly the charged amount; a replay with the same Idempotency-Key never charges again.

~~~ts
const operationKey = crypto.randomUUID(); // Save with your job before sending.
const image = await lahjty("/image-generations", {
  method: "POST",
  idempotencyKey: operationKey,
  body: {
    prompt: "Premium Saudi specialty coffee campaign",
    type: "product_showcase",
    output_language: "ar",
    market: "SA",
    dialect: "saudi",
    platform: "instagram",
    style: "photorealistic",
    aspect_ratio: "1:1",
    resolution: "1K",
    visual_keywords: ["Saudi coffee cup", "coffee beans"],
    excluded_visuals: ["people", "logos", "text"],
    include_text: false,
  },
});
~~~

~~~python
operation_key = str(uuid.uuid4())  # Save with your job before sending.
image = lahjty("/image-generations", "POST", {
    "prompt": "Premium Saudi specialty coffee campaign",
    "type": "product_showcase",
    "output_language": "ar",
    "market": "SA",
    "dialect": "saudi",
    "platform": "instagram",
    "style": "photorealistic",
    "aspect_ratio": "1:1",
    "resolution": "1K",
    "include_text": False,
},
    idempotency_key=operation_key,
)
~~~

For model-rendered image text, set include_text to true, supply overlay_text, and set overlay_text_language to ar, en, or auto. Model-rendered spelling is probabilistic and must be reviewed.
With owned references, include_text=false forbids new advertising copy while preserving the supplied product's existing packaging marks and any explicitly requested logo.

For your own product photo and logo, first import each through `/ad-library/uploads` with its explicit `reference` or `logo` role. Send up to two distinct `reference_storage_ids` and a separate `logo_storage_id` to `/image-generations`. `logo_mode` defaults to `model` when a logo is supplied and `none` otherwise. `model` gives the real logo to the image model; `overlay` places it deterministically; `none` ignores a supplied logo. Model rendering may alter the mark. Use overlay when the original mark must remain exact. Product and logo roles come from the visible images and your request, never filenames alone.

### Edit a saved image

POST /image-edits costs 5 credits at 1K or 8 credits at 2K, the same as an image edit in the Lahjty dashboard. It is charged at the rendered resolution: the request's `resolution`, otherwise the source image's recorded resolution, otherwise 1K. Send the `request_id` of an earlier completed image generation, image edit, Ad Library generation, or campaign whose image completed as `source_request_id`, plus a short `instruction` such as "make the background white" (3 to 1,000 characters). Lahjty reads that saved image from its own storage, changes only what the instruction asks, and returns a new image in the same `image_generation` shape with `edit_of`. Unknown, foreign, failed, still-processing, or image-less sources fail before any credit is charged.

~~~ts
const editKey = crypto.randomUUID(); // Save with your job before sending.
const edited = await lahjty("/image-edits", {
  method: "POST",
  idempotencyKey: editKey,
  body: {
    source_request_id: image.request_id,
    instruction: "Make the background plain white and keep the product unchanged.",
    output_language: "ar",
  },
});
~~~

~~~python
edit_key = str(uuid.uuid4())  # Save with your job before sending.
edited = lahjty("/image-edits", "POST", {
    "source_request_id": image["request_id"],
    "instruction": "Make the background plain white and keep the product unchanged.",
},
    idempotency_key=edit_key,
)
~~~

The edit keeps the source canvas unless you set `aspect_ratio`, and the source resolution (or 1K) unless you set `resolution`. To put a different product in the scene, import its photo with role `reference` and send it in `reference_storage_ids` (maximum two). `logo_storage_id` and `logo_mode` work as for image generation; when you supply a logo for an Ad Library result that has an overlaid logo, Lahjty edits its logo-free original so the new mark is not duplicated. Set `output_language` to ar or en for text the edit adds or changes. The instruction goes to the image model without the prompt optimizer and edited text is not verified, so review it. Accounts without paid access receive the Lahjty watermark and no deterministic logo overlay; an earlier watermark on the source is covered before the image is sent, and the result gets its own. Chain edits by passing the edit's own `request_id` as the next `source_request_id`. POST /quote with operation `image_edit` checks the source and returns the cost without charging.

#### Another size of the same ad

To post the same ad as a feed post (4:5), a square (1:1) or a Story (9:16), send `resize: true` with that `aspect_ratio` and no instruction (a request without an instruction is a resize too). It costs the same as an edit. Lahjty writes the instruction itself and changes nothing else: the scene, product, words and any logo in the picture move to fit the new frame. The new size is then read back like a new image: its words must match the source's (the copy the source's own text check verified, otherwise a careful reading of the source that is never shown to the image model), and the whole ad must pass the visual check, with the product compared to the source image. A failed check renders once more with a correction; if it still fails, the request returns 422 `content_rejected` with `errors.reason` `ad_copy_mismatch` or `ad_check_failed`, is refunded and saves nothing. The result reports `resize: true`, `text_policy.copy_verified` and `quality_policy` like a new image. A resize takes no `instruction`, `reference_storage_ids`, logo fields or `output_language`; send other changes as a normal edit. Asking for the source's own size returns 422 `invalid_request` before any charge.

~~~json
{ "source_request_id": "req_01jimagesource", "resize": true, "aspect_ratio": "9:16" }
~~~

## 4. Arabic and English speech

POST /speech-generations costs 5 credits and returns a hosted MP3. It reads the exact approved transcript; it is not a copywriting prompt. Set output_language to ar or en (default ar). Arabic defaults to saudi when dialect is omitted; English must omit dialect and returns dialect: null.

For English, send `{ "text": "Your order is ready for delivery.", "output_language": "en", "delivery": "natural", "voice_profile": "warm_storyteller" }`. Campaign speech inherits brief.output_language and supports both languages; omit brief.dialect for English campaigns.

~~~ts
const operationKey = crypto.randomUUID(); // Save with your job before sending.
const speech = await lahjty("/speech-generations", {
  method: "POST",
  idempotencyKey: operationKey,
  body: {
    text: "طلبك صار جاهز، ونوصله لك بكرة بإذن الله.",
    dialect: "gulf",
    tone: "warm",
    platform: "whatsapp",
    delivery: "natural",
    content_type: "marketing",
    voice_profile: "warm_storyteller",
    external_customer_id: "merchant-91",
  },
});
~~~

~~~python
operation_key = str(uuid.uuid4())  # Save with your job before sending.
speech = lahjty("/speech-generations", "POST", {
    "text": "طلبك صار جاهز، ونوصله لك بكرة بإذن الله.",
    "dialect": "gulf",
    "tone": "warm",
    "platform": "whatsapp",
    "delivery": "natural",
    "content_type": "marketing",
    "voice_profile": "warm_storyteller",
},
    idempotency_key=operation_key,
)
~~~

## 5. Complete campaign

POST /campaigns costs 2 credits for copy, plus 5 for an image at 1K or 8 at 2K (`deliverables.image.resolution`) and 5 for speech when enabled, so a campaign costs 2 to 15 credits.

~~~ts
const operationKey = crypto.randomUUID(); // Save with your job before sending.
const campaign = await lahjty("/campaigns", {
  method: "POST",
  idempotencyKey: operationKey,
  body: {
    external_id: "campaign-1849",
    external_customer_id: "merchant-91",
    brief: {
      description: "Weekend specialty coffee subscription offer",
      offer: "20% off through Saturday",
      objective: "Drive WhatsApp orders",
      output_language: "ar",
      market: "SA",
      dialect: "saudi",
      platform: "whatsapp",
      tone: "warm",
      required_keywords: ["قهوة مختصة"],
      excluded_keywords: ["مجاني"],
      call_to_action: "اطلب الآن",
    },
    deliverables: {
      copy: { type: "ad_copy", framework: "aida" },
      image: {
        enabled: true,
        type: "product_showcase",
        style: "photorealistic",
        aspect_ratio: "1:1",
        resolution: "1K",
        include_text: false,
      },
      speech: {
        enabled: true,
        voice_profile: "confident_announcer",
        delivery: "natural",
        content_type: "marketing",
      },
    },
  },
});
~~~

~~~python
operation_key = str(uuid.uuid4())  # Save with your job before sending.
campaign = lahjty("/campaigns", "POST", {
    "external_id": "campaign-1849",
    "external_customer_id": "merchant-91",
    "brief": {
        "description": "Weekend specialty coffee subscription offer",
        "output_language": "ar",
        "market": "SA",
        "dialect": "saudi",
        "platform": "whatsapp",
        "call_to_action": "اطلب الآن",
    },
    "deliverables": {
        "copy": {"type": "ad_copy", "framework": "aida"},
        "image": {"enabled": False},
        "speech": {"enabled": False},
    },
},
    idempotency_key=operation_key,
)
~~~

## 6. WhatsApp template draft

POST /whatsapp-template-drafts costs 2 credits. It returns an UNSUBMITTED Meta-shaped payload. Lahjty does not submit the template, guarantee Meta approval, or deliver WhatsApp messages.

~~~ts
const operationKey = crypto.randomUUID(); // Save with your job before sending.
const draft = await lahjty("/whatsapp-template-drafts", {
  method: "POST",
  idempotencyKey: operationKey,
  body: {
    name: "order_shipped",
    category: "UTILITY",
    output_language: "ar",
    language_code: "ar",
    market: "SA",
    dialect: "saudi",
    purpose: "Tell a customer that their order has shipped",
    customer_action_context: "The recipient placed the referenced order",
    variables: [
      { name: "customer_name", example: "نورة" },
      { name: "order_number", example: "A-1842" },
      { name: "delivery_date", example: "الخميس" },
    ],
    header: "TEXT",
    footer: true,
    buttons: [{ type: "QUICK_REPLY", text: "تواصل معنا" }],
    external_customer_id: "merchant-91",
  },
});
~~~

~~~python
operation_key = str(uuid.uuid4())  # Save with your job before sending.
draft = lahjty("/whatsapp-template-drafts", "POST", {
    "name": "order_shipped",
    "category": "UTILITY",
    "output_language": "ar",
    "language_code": "ar",
    "market": "SA",
    "dialect": "saudi",
    "purpose": "Tell a customer that their order has shipped",
    "customer_action_context": "The recipient placed the referenced order",
    "variables": [
        {"name": "customer_name", "example": "نورة"},
        {"name": "order_number", "example": "A-1842"},
    ],
    "header": "TEXT",
    "footer": True,
},
    idempotency_key=operation_key,
)
~~~

UTILITY needs customer_action_context. MARKETING needs opt_in_context. AUTHENTICATION uses the authentication settings. Every variable needs a realistic example. English templates are supported; omit dialect when output_language is en.

## 7. Report a WhatsApp template outcome

POST /whatsapp-template-drafts/{draft_id}/outcomes costs 0 credits. Submit the generated meta_payload through the partner's WhatsApp provider, then report each Meta state change.

~~~ts
const operationKey = crypto.randomUUID(); // Save with your job before sending.
const outcome = await lahjty(
  "/whatsapp-template-drafts/wtd_01jexample/outcomes",
  {
    method: "POST",
  idempotencyKey: operationKey,
    body: {
      outcome: "REJECTED",
      meta_template_id: "123456789012345",
      provider_event_id: "provider-meta-event-3001",
      submitted_payload_hash:
        "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
      category: "UTILITY",
      reason: "Meta rejection reason",
      occurred_at: "2026-09-04T09:30:00Z",
    },
  },
);
~~~

~~~python
operation_key = str(uuid.uuid4())  # Save with your job before sending.
outcome = lahjty(
    "/whatsapp-template-drafts/wtd_01jexample/outcomes",
    "POST",
    {
        "outcome": "REJECTED",
        "meta_template_id": "123456789012345",
        "provider_event_id": "provider-meta-event-3001",
        "submitted_payload_hash":
            "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
        "category": "UTILITY",
        "reason": "Meta rejection reason",
    },
    idempotency_key=operation_key,
)
~~~

Outcome reports are partner-supplied measurement data, not proof of a Meta decision. An unchanged draft reported as rejected becomes a refund candidate with `PENDING_VERIFICATION`; the report itself never changes the balance. Lahjty applies the 2-credit refund exactly once only after an administrator verifies trusted Meta/provider evidence. Edited submissions are recorded but are not candidates.

## 8. Usage

GET /usage costs 0 credits. Use limit=1..100 (default 20) and the opaque next_cursor to paginate every retained attempt: /usage?limit=20&cursor=URL_ENCODED_CURSOR. Stop when is_done is true.

The top-level counters always summarize the latest 50 retained attempts, independently of pagination; summary_scope, summary_limit, and summary_truncated make that bound explicit. credits_used is gross successful generation usage, not a net credit ledger total, and excludes subsequent template-outcome refunds. Per-attempt credits_charged, credits_refunded, and refund_pending are booleans. Terminal records are retained for 30 days; unresolved debits remain until reconciled.

~~~ts
const usage = await lahjty("/usage");
~~~

~~~python
usage = lahjty("/usage")
~~~

## 9. Stored request

GET /requests/{request_id} costs 0 credits. Terminal request records and generated response payloads are retained for 30 days.

~~~ts
const request = await lahjty("/requests/req_01jexample");
~~~

~~~python
request = lahjty("/requests/req_01jexample")
~~~

## Reliability

- Same idempotency key and same body: replay a completed result without a second charge. A reconciled retryable failure permits another attempt under that key; each attempt keeps its own request_id and audit record.
- Same key and changed body: 409 idempotency_conflict.
- Original request still running: 409 request_in_progress.
- Client timeout: retry the exact body with the same key or retrieve the request by request_id.
- Errors use application/problem+json with code, detail, and request_id.
- Honor Retry-After and rate-limit headers.
- A failed generation may have refund_pending=true while the ledger outcome is reconciled. Do not assume a refund from the HTTP status alone. Recovery runs after interrupted requests become stale (five minutes) and retries during outages. Poll the stored request before treating its credit outcome as final.
- Keep a merchant-owned plain-text fallback. Campaign sending must not depend on Lahjty availability.

## Output validation and quality limits

Copy and headlines must contain three non-empty, distinct variants. Lahjty checks keywords and basic Arabic/Latin script presence, attempts one repair for failed copy checks, and returns content_rejected if repair still fails. Script checks cannot certify language fluency, dialect authenticity, factual truth, or three distinct marketing strategies. Human review remains necessary.

A valid JSON object from an incomplete provider response is rejected with provider_unavailable. Conversion accepts up to 8,000 source characters without clipping; its result can use up to 12,000 characters to accommodate expansion. Conversion checks preserve numeric values, HTTP(S) links, and supported {{...}} / ${...} placeholders; these checks do not prove semantic equivalence.

Explicit image text translation fails if the fallback still lacks the requested script; it does not silently generate the image with wrong-language fallback text. UTILITY checks cover generated header/body/footer and supplied button labels. Meta retains the final approval decision. Check the stored request for the final debit/refund outcome.

## Ad Library API

The API supports the same catalog IDs shown in Lahjty. Use `GET /ad-library?id=AD_ID` for an exact selection, or pass a short `q` filter and an optional `brief` (up to 2,000 characters) to rank matches. Rankings use bilingual catalog metadata and editorial tie breaks; they do not predict measured ad performance. Follow the returned `next.page` and `next.offset` for another bounded page.

Every item carries `kind`: `product_photo_format` (232 curated `image-lib-*` formats built around the customer's own product photo), `lahjty_template`, `analyzed_ad` (ships its contract) or `gallery_ad` (may need paid preparation). Filter with `kind=product_photo_format` for physical products. Product-photo formats report `requires_product_photo: true` and a `product_photo_format` object (photo subject, one or two required `reference` photos, `keeps_product_label`, `palette_role`, visible text fields, `text_free`, `suggested_aspect_ratio`). They are always prepared (zero analysis credits), require at least one owned product photo at generation (400 before any charge otherwise), and keep the text printed on that product. Supported generation shapes are 1:1, 4:5, 9:16, 16:9, 3:4 and 4:3.

1. Read `GET /ad-library/{id}` to inspect the editable fields, product-reference requirements and preparation state. This read does not charge credits.
2. If the contract is missing, explicitly call `POST /ad-library/{id}/prepare` with `{}` and a persisted `Idempotency-Key`. Analysis costs one credit when needed and has its own atomic ledger and refund recovery. An existing contract costs zero. The returned `usage.credits_used` reports the analysis charge; `balance_after` is null. A pending 409 or daily-allowance 429 can be retried with the same body/key after completion or the reported reset time; it does not permanently lock that key to an error. Each attempt remains inspectable.
3. Import a product image or logo using `POST /ad-library/uploads` with `{ "url": "https://your-attachment-host/image.png", "role": "reference" }` or role `logo`. Preserve the Idempotency-Key. Images are private, ownership checked, and unattached uploads expire after 24 hours. Existing owned uploads are supplied by storage ID, never by a private Lahjty URL.
4. Call `POST /ad-library/{id}/generations` with approved `template_fields`, `locale`, supported `aspect_ratio`, optional `reference_storage_ids` (maximum two), `logo_storage_id`, `logo_mode`, hex-color `palette` and `resolution` (`1K` by default or `2K`). Logo modes work as described for generic images: model by default with a logo, overlay for deterministic placement, none to ignore it. Reuse the same body/key after uncertainty. This consumes the image credit cost of the requested resolution (5 credits at 1K, 8 at 2K) and never starts analysis implicitly. The result includes the durable image, saved snippet ID, rendered `resolution`, text policy and explicit logo policy. Overlay mode also preserves the clean original and editable logo composition; model-rendered branding is part of the image and cannot be edited as a separate overlay.

Catalog reads require `ad-library:read`; preparation and uploads require `ad-library:write`; generation requires `images:write`. API keys and authorized MCP OAuth connections share these checks. `DELETE /ad-library/uploads?storage_id={storageId}` removes only owned, unattached temporary images. PNG, JPEG and WebP must be non-animated and within the documented byte/pixel limits. Downloads use DNS-pinned public-network checks and reject redirects into Lahjty or Convex media namespaces.
