Passer au contenu principal
Exemples de bout en bout reliant plusieurs endpoints. Dans toutes les commandes, remplacez $KEY par votre token API et $HOST par le domaine réel de la plateforme.
export KEY="sk-your-api-key"
export HOST="https://api.apimart.ai"

Flux A : texte-vers-image de base (imagine → upscale)

# 1. imagine produit 4 images
curl -sS -X POST "$HOST/v1/midjourney/generations/imagine" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{
    "prompt": "a futuristic city at sunset, photorealistic, cinematic lighting",
    "version": "8.1", "size": "16:9", "speed": "fast", "stylize": 250
  }'
# → {"code":200,"data":[{"task_id":"task_01KQVZAPBW...","status":"submitted"}]}

# 2. Sondez jusqu'à SUCCESS (environ 30 à 60s)
curl -sS "$HOST/v1/midjourney/task_01KQVZAPBW..." -H "Authorization: Bearer $KEY"
# → SUCCESS, contient grid_image_url + 4 image_urls + buttons(U1-U4 / V1-V4 / 🔄)

# 3. upscale sélectionne la 2e image (composé localement, SUCCESS en quelques millisecondes)
curl -sS -X POST "$HOST/v1/midjourney/generations/upscale" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{"task_id": "task_01KQVZAPBW...", "index": 2}'
# → la consultation récupère l'image unique image_urls[0]

Flux B : image de référence → variation forte → upscale

# 1. imagine guidé par image
curl -sS -X POST "$HOST/v1/midjourney/generations/imagine" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{
    "prompt": "turn this product into a luxury studio photo",
    "image_urls": ["https://your-cdn.example.com/product.png"],
    "iw": 1.5, "size": "1:1"
  }'

# 2. Variation forte sur le résultat
curl -sS -X POST "$HOST/v1/midjourney/generations/high-variation" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{"task_id": "task_01XXX...", "index": 1, "speed": "fast"}'

# 3. upscale d'une des variations
curl -sS -X POST "$HOST/v1/midjourney/generations/upscale" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{"task_id": "task_02_variant...", "index": 3}'

Flux C : retouche locale (inpaint + modal en deux étapes)

Prérequis : effectuez d’abord imagine + upscale pour obtenir une tâche d’image unique (voir Flux A).
# 1. Soumettez inpaint → entre en MODAL
curl -sS -X POST "$HOST/v1/midjourney/generations/inpaint" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{"task_id": "task_02_upscaled..."}'
# → {"data":[{"task_id":"task_03_inpaint...","status":"modal"}]}
#   notez status=modal, la tâche attend que vous fournissiez le masque ; timeout de 30 minutes → CANCEL + remboursement automatiques

# 2. Le frontend dessine le masque (blanc = zone à repeindre, transparent = à conserver), le téléverse sur votre propre OSS pour obtenir mask_url (doit être accessible publiquement)

# 3. Soumettez modal pour terminer
curl -sS -X POST "$HOST/v1/midjourney/generations/modal" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{
    "task_id": "task_03_inpaint...",
    "prompt": "replace the selected area with a red leather sofa",
    "mask_url": "https://your-oss.example.com/mask-abc.png"
  }'
# → même task_id, status passe à submitted ; 4. après 60 à 90s de sondage, SUCCESS, contient 4 candidats de retouche locale

Flux D : extension d’image (Zoom Out)

# Produit directement l'image, sans masque (Outpaint / CustomZoom n'entrent pas en MODAL)
curl -sS -X POST "$HOST/v1/midjourney/generations/zoom" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{"task_id": "task_02_upscaled...", "zoom_ratio": 1.5, "speed": "fast"}'

Flux E : image-vers-vidéo (i2v)

# 720p HD + batch=4 (facturation x4)
curl -sS -X POST "$HOST/v1/midjourney/generations/video" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{
    "prompt": "city traffic at night, neon reflections, slow camera dolly",
    "image_urls": ["https://your-cdn.example.com/city.jpg"],
    "video_type": "vid_1.1_i2v_720", "batch_size": 4
  }'
# Débit réel = midjourney@video-720p × 4

# Transition image de début/fin (end_url est automatiquement promu en start_end)
curl -sS -X POST "$HOST/v1/midjourney/generations/video" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{
    "prompt": "transition smoothly from sunrise to sunset",
    "image_urls": ["https://your-cdn.example.com/sunrise.jpg"],
    "end_url": "https://your-cdn.example.com/sunset.jpg",
    "video_type": "vid_1.1_i2v_720"
  }'

Outil générique : encapsulation client Python

import time
import httpx

API_KEY = "sk-..."
HOST = "https://api.apimart.ai"

class MjClient:
    def __init__(self):
        self.client = httpx.Client(
            base_url=HOST,
            headers={"Authorization": f"Bearer {API_KEY}"},
            timeout=30,
        )

    def imagine(self, prompt, **params):
        r = self.client.post("/v1/midjourney/generations/imagine",
                             json={"prompt": prompt, **params})
        return r.json()["data"][0]["task_id"]

    def upscale(self, task_id, index):
        r = self.client.post("/v1/midjourney/generations/upscale",
                             json={"task_id": task_id, "index": index})
        return r.json()["data"][0]["task_id"]

    def query(self, task_id):
        return self.client.get(f"/v1/midjourney/{task_id}").json()

    def wait(self, task_id, timeout=180):
        deadline = time.time() + timeout
        while time.time() < deadline:
            t = self.query(task_id)
            if t["status"] in ("SUCCESS", "FAILURE"):
                return t
            if t["status"] == "MODAL":
                raise RuntimeError(f"task {task_id} nécessite un appel à /modal")
            time.sleep(3)
        raise TimeoutError(task_id)


mj = MjClient()
imagine_id = mj.imagine("a cat", version="8.1", speed="fast", size="16:9")
mj.wait(imagine_id)
upscale_id = mj.upscale(imagine_id, 2)
print(mj.wait(upscale_id)["image_urls"][0])

Outil générique : encapsulation TypeScript

const API_KEY = "sk-...";
const HOST = "https://api.apimart.ai";

async function mj(path: string, body: any) {
  const r = await fetch(`${HOST}${path}`, {
    method: "POST",
    headers: { "Authorization": `Bearer ${API_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify(body),
  });
  return r.json();
}

async function query(id: string) {
  const r = await fetch(`${HOST}/v1/midjourney/${id}`, {
    headers: { "Authorization": `Bearer ${API_KEY}` },
  });
  return r.json();
}

async function waitTask(id: string, timeoutMs = 180_000) {
  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    const t = await query(id);
    if (t.status === "SUCCESS" || t.status === "FAILURE") return t;
    if (t.status === "MODAL") throw new Error(`nécessite un appel à /modal: ${id}`);
    await new Promise((r) => setTimeout(r, 3000));
  }
  throw new Error(`timeout: ${id}`);
}

const r = await mj("/v1/midjourney/generations/imagine",
                   { prompt: "a cat", version: "8.1", speed: "fast" });
const result = await waitTask(r.data[0].task_id);
console.log(result.image_urls);

Machine à états

submit → NOT_START(0%) → SUBMITTED(5-30%) → IN_PROGRESS(~99%) → SUCCESS(100%)
                                                              ↘ FAILURE(100%) → remboursement automatique
inpaint / CustomZoom → MODAL(15%) ──POST /modal {mask_url, prompt}──▶ SUBMITTED → ...
                          └ timeout 30min → CANCEL + remboursement