MuseSpark
MuseSpark
Start here

Create your first task

Submit an image-generation task, follow its progress, and retrieve the result.

This example uses the published nano-banana item. Check that it is present in your authorized catalog, then read its model guide.

1. Configure access

Create a key with product openapi_tools and scope task:write. This scope currently also permits status and catalog reads.

export MUSESPARK_API_KEY='YOUR_API_KEY'
export MUSESPARK_BASE_URL='https://api.musespark.ai'

2. Check the model catalog

curl --fail-with-body "$MUSESPARK_BASE_URL/api/v1/openapi/models" \
  -H "Authorization: Bearer $MUSESPARK_API_KEY"

The list is at data.data. Use its item_key as the task identifier. A documentation slug identifies a guide; the catalog's invocation identifier identifies the model in a request.

3. Create a task

curl --fail-with-body "$MUSESPARK_BASE_URL/api/v1/openapi/task" \
  -H "Authorization: Bearer $MUSESPARK_API_KEY" \
  -H 'Content-Type: application/json' \
  -H 'X-Idempotency-Key: YOUR_STABLE_REQUEST_ID' \
  -d '{"item_key":"nano-banana","parameters":{"prompt":"A paper city under soft morning light","aspect_ratio":"1:1","resolution":"1K","batch_size":1}}'

A successful creation response contains a task ID. This response uses a synthetic example ID:

{"code":200,"msg":"success","data":{"task_id":"123e4567-e89b-42d3-a456-426614174000","status":"pending"}}

4. Retrieve the result

curl --fail-with-body "$MUSESPARK_BASE_URL/api/v1/openapi/task/status/YOUR_TASK_ID" \
  -H "Authorization: Bearer $MUSESPARK_API_KEY"

Poll with backoff until the status is completed, failed, or cancelled. finalizing is still processing. On success, save data.result.output_urls or the applicable batch_results. Terminal status records with a completion timestamp expire after 30 minutes.

Complete programs

The programs below save the request identity before submission and the task ID before polling. They write the completed result to musespark-task.json and print it. Set MUSESPARK_TASK_STATE to use a different state file for a new task; run only one process per state file.

Rerunning with the same file resumes its known task or reads its saved result. If submission ended before a task ID was received, the program stops so you can reconcile that request using the saved identity. Do not delete uncertain state or replace its idempotency key just to retry: the original request may already have created paid work. See retry guidance.

The saved result includes output URLs, not the media bytes. Download the files your application needs promptly; the task-status retention period does not define an output URL's lifetime.

Python

Use Python 3 with requests installed. Download the complete Python program.

"""Run with Python 3 and requests. State contains request/result data; keep it private."""
import json
import os
from pathlib import Path
import time
import uuid
import requests

base = os.environ.get("MUSESPARK_BASE_URL", "https://api.musespark.ai").rstrip("/")
headers = {"Authorization": "Bearer " + os.environ["MUSESPARK_API_KEY"]}
state_path = Path(os.environ.get("MUSESPARK_TASK_STATE", "musespark-task.json"))

def save(state):
    temporary = state_path.with_name(state_path.name + ".tmp")
    with open(temporary, "w", encoding="utf-8") as handle:
        os.chmod(temporary, 0o600)
        json.dump(state, handle, indent=2)
    os.replace(temporary, state_path)

def read(response):
    response.raise_for_status()
    payload = response.json()
    if payload.get("code") != 200:
        raise RuntimeError(payload.get("msg", "Request failed"))
    return payload["data"]

if state_path.exists():
    state = json.loads(state_path.read_text(encoding="utf-8"))
    if state["base_url"] != base:
        raise RuntimeError("This state belongs to a different API base URL")
    if not state.get("task_id"):
        raise RuntimeError("A submission may already exist. Reconcile it before retrying; preserve the saved request_id and request.")
else:
    state = {
        "base_url": base,
        "request_id": str(uuid.uuid4()),
        "request": {"item_key": "nano-banana", "parameters": {
            "prompt": "A paper city under soft morning light",
            "aspect_ratio": "1:1", "resolution": "1K", "batch_size": 1,
        }},
    }
    save(state)  # Persist the request identity before sending any paid work.
    print("Request state:", state_path)
    created = read(requests.post(
        base + "/api/v1/openapi/task",
        headers={**headers, "X-Idempotency-Key": state["request_id"]},
        json=state["request"], timeout=30,
    ))
    state["task_id"] = created["task_id"]
    save(state)

if "result" in state:
    print(json.dumps(state["result"], indent=2))
else:
    print("Task:", state["task_id"])
    deadline = time.monotonic() + 600
    delay = 2
    while time.monotonic() < deadline:
        task = read(requests.get(
            base + "/api/v1/openapi/task/status/" + state["task_id"],
            headers=headers, timeout=30,
        ))
        if task["status"] == "completed":
            state["result"] = task.get("result", {})
            save(state)
            print(json.dumps(state["result"], indent=2))
            break
        if task["status"] in ("failed", "cancelled"):
            state["terminal_status"] = task["status"]
            state["error"] = task.get("error") or task.get("message")
            save(state)
            raise RuntimeError(state["error"] or state["terminal_status"])
        if task["status"] not in ("pending", "running", "finalizing"):
            raise RuntimeError("Unknown task status: " + task["status"])
        time.sleep(delay)
        delay = min(delay * 1.5, 15)
    else:
        raise TimeoutError("Polling stopped. Run again with the same state file to resume the existing task.")

JavaScript

Use Node.js 20 or later. Download the complete JavaScript program.

// Run on Node.js 20+; state contains request/result data and should remain private.
import { randomUUID } from 'node:crypto';
import { existsSync, readFileSync, writeFileSync, renameSync } from 'node:fs';

const base = (process.env.MUSESPARK_BASE_URL ?? 'https://api.musespark.ai').replace(/\/$/, '');
if (!process.env.MUSESPARK_API_KEY) throw new Error('Set MUSESPARK_API_KEY');
const headers = { Authorization: `Bearer ${process.env.MUSESPARK_API_KEY}` };
const statePath = process.env.MUSESPARK_TASK_STATE ?? 'musespark-task.json';
function save(state) {
  writeFileSync(`${statePath}.tmp`, JSON.stringify(state, null, 2), { mode: 0o600 });
  renameSync(`${statePath}.tmp`, statePath);
}
async function read(response) {
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  const payload = await response.json();
  if (payload.code !== 200) throw new Error(payload.msg ?? 'Request failed');
  return payload.data;
}
let state;
if (existsSync(statePath)) {
  state = JSON.parse(readFileSync(statePath, 'utf8'));
  if (state.base_url !== base) throw new Error('This state belongs to a different API base URL');
  if (!state.task_id) throw new Error('A submission may already exist. Reconcile it before retrying; preserve the saved request_id and request.');
} else {
  state = { base_url: base, request_id: randomUUID(), request: {
    item_key: 'nano-banana', parameters: {
      prompt: 'A paper city under soft morning light',
      aspect_ratio: '1:1', resolution: '1K', batch_size: 1,
    },
  } };
  save(state); // Persist the request identity before sending any paid work.
  console.log('Request state:', statePath);
  const created = await read(await fetch(`${base}/api/v1/openapi/task`, {
    method: 'POST',
    headers: { ...headers, 'Content-Type': 'application/json', 'X-Idempotency-Key': state.request_id },
    body: JSON.stringify(state.request), signal: AbortSignal.timeout(30_000),
  }));
  state.task_id = created.task_id;
  save(state);
}
if (Object.hasOwn(state, 'result')) {
  console.log(state.result);
} else {
  console.log('Task:', state.task_id);
  const deadline = Date.now() + 600_000;
  let delay = 2_000;
  while (true) {
    if (Date.now() >= deadline) throw new Error('Polling stopped. Run again with the same state file to resume the existing task.');
    const task = await read(await fetch(`${base}/api/v1/openapi/task/status/${state.task_id}`, {
      headers, signal: AbortSignal.timeout(30_000),
    }));
    if (task.status === 'completed') {
      state.result = task.result ?? {};
      save(state);
      console.log(state.result);
      break;
    }
    if (['failed', 'cancelled'].includes(task.status)) {
      state.terminal_status = task.status;
      state.error = task.error || task.message;
      save(state);
      throw new Error(state.error || state.terminal_status);
    }
    if (!['pending', 'running', 'finalizing'].includes(task.status)) throw new Error(`Unknown task status: ${task.status}`);
    await new Promise((resolve) => setTimeout(resolve, delay));
    delay = Math.min(delay * 1.5, 15_000);
  }
}

Next steps