# Suno (`suno`)

> Audio model `suno` by Suno on the Unitool API. Generations are asynchronous: `POST https://api.unitool.ai/v1/generations` creates one; then wait in the same request (`Prefer: wait`), poll `GET /v1/generations/{id}` or receive a webhook. This file is enough to write an integration.

The same model as JSON (modes, `input_schema`, prices): `GET /v1/models/suno`. Docs index: https://unitool.ai/llms.txt.

## Facts

- id: `suno`
- name: Suno
- type: audio
- vendor: Suno
- price from: 14 balance tokens per generation
- modes: `create`. Without a mode in the request the first one (`create`) is used

## Calling the API

- Base URL `https://api.unitool.ai/v1`. Every request carries `Authorization: Bearer $UNITOOL_API_KEY` (`x-api-key: $UNITOOL_API_KEY` works too) and, with a body, `Content-Type: application/json`.
- Keys are created in the account (https://unitool.ai/settings?p=api), never through the API. `ut_live_...` spends the balance. `ut_test_...` runs the same checks and returns a fixed answer; nothing is charged.
- Prices and charges are in balance tokens (the account's currency), not model tokens. `GET /v1/balance` answers `{"object":"balance","unit":"tokens","available_tokens":1500,"held_tokens":40}`: `available_tokens` is free to spend, `held_tokens` is reserved by running requests.
- Every answer has an `x-request-id` header (`req_...`). The receipt of a charged request is `GET /v1/requests/{id}`.
- New fields may appear in answers: skip what you do not know.

## Create a generation

`POST https://api.unitool.ai/v1/generations` with a JSON body:

| Field | Type | Notes |
|---|---|---|
| `model` | string, required | `"suno"`, or with the mode: `"suno:create"` |
| `mode` | string | One of `create`, when not given in `model` |
| `input` | object, required | The fields of the mode, listed under "Modes" below. Enum values are accepted as strings and as numbers. A field the mode does not list is `400 invalid_parameter` |
| `max_cost_tokens` | number | Price ceiling. A higher price answers `402 price_exceeds_limit`; nothing is charged |
| `metadata` | object | Up to 16 string values of up to 500 characters; returned in the generation object and in webhook events |
| `webhook_url` | string | An https address that receives this generation's event, see "Webhook" |
| `webhook_events` | array | Which of `generation.succeeded`, `generation.failed` go to `webhook_url`; both by default. A 400 without `webhook_url` |

Any other top-level field is `400 invalid_parameter`. Headers:

- `Idempotency-Key`, 8 to 128 printable ASCII characters: a retry with the same key and the same body returns the same generation with `Idempotent-Replayed: true` and charges nothing again; the same key with another body is `422 idempotency_key_reused`. Keys never expire. Without the header every request is a new paid generation, so always send it and retry with the same key.
- `Prefer: wait=N` (or `?wait=N` in the URL), N up to 60: hold the answer until the generation ends or N seconds pass.

The answer is `202 Accepted` with `Location: /v1/generations/{id}` and `Retry-After: 5` while the generation has not ended, or `200 OK` with the finished object when it ended within the wait:

```json
{
  "id": "gen_6f1c0e9a2b7d4c3e8f5a1b2c3d4e5f60",
  "object": "generation",
  "model": "suno",
  "mode": "create",
  "status": "queued",
  "progress": 0,
  "cost": {
    "estimated_tokens": 14,
    "charged_tokens": 0,
    "refunded_tokens": 0,
    "settled": false
  },
  "outputs": [],
  "error": null,
  "metadata": {
    "order_id": "A-1042"
  },
  "created_at": "2026-11-29T12:00:00.000Z",
  "completed_at": null,
  "expires_at": null
}
```

## Result

`GET /v1/generations/{id}` answers `200` with the same object (with `Retry-After: 5` while it has not ended; `Prefer: wait=N` works here too). Statuses: `queued` → `running` → `succeeded`, `failed` or `canceled`; stop polling on the last three.

```json
{
  "id": "gen_6f1c0e9a2b7d4c3e8f5a1b2c3d4e5f60",
  "object": "generation",
  "model": "suno",
  "mode": "create",
  "status": "succeeded",
  "progress": 1,
  "cost": {
    "estimated_tokens": 14,
    "charged_tokens": 14,
    "refunded_tokens": 0,
    "settled": true
  },
  "outputs": [
    {
      "index": 0,
      "type": "audio",
      "file_ref": "attachment:482913",
      "url": "https://api.unitool.ai/v1/files/q83vEjRkT1mXc0yLw2hN5aZp7dUoB9sGfI4tKeYxWrQ6/file.mp3",
      "content_type": "audio/mpeg",
      "size": 482304,
      "expires_at": "2026-12-06T12:00:41.000Z"
    }
  ],
  "error": null,
  "metadata": {
    "order_id": "A-1042"
  },
  "created_at": "2026-11-29T12:00:00.000Z",
  "completed_at": "2026-11-29T12:00:41.000Z",
  "expires_at": "2026-12-06T12:00:41.000Z"
}
```

- `outputs[].url`: a signed link, valid for 1 hour, downloaded without a key (`GET`, `HEAD`, `Range`). Every `GET /v1/generations/{id}` issues fresh links; an expired one answers `404 file_link_expired`.
- The files are kept for 7 days, until `expires_at`. After that `outputs` is empty and `outputs_expired: true` is set. Download what you need.
- `outputs[].file_ref` passes this result to another generation as a file input; it does not expire with the link.
- `width` and `height` come with images and video, `duration_sec` with video and audio, `size` (bytes) when known.
- `outputs_filtered: N`: the model returned N variants fewer than ordered; the ordered price is charged.
- `cost.charged_tokens` minus `cost.refunded_tokens` is what the generation cost.

A failed generation is still a `200` on `GET`, with the reason in `error`:

```json
{
  "id": "gen_6f1c0e9a2b7d4c3e8f5a1b2c3d4e5f60",
  "object": "generation",
  "model": "suno",
  "mode": "create",
  "status": "failed",
  "progress": 0,
  "cost": {
    "estimated_tokens": 14,
    "charged_tokens": 14,
    "refunded_tokens": 14,
    "settled": true
  },
  "outputs": [],
  "error": {
    "code": "model_error",
    "message": "The model failed to produce a result.",
    "refund": "full"
  },
  "metadata": {
    "order_id": "A-1042"
  },
  "created_at": "2026-11-29T12:00:00.000Z",
  "completed_at": "2026-11-29T12:00:41.000Z",
  "expires_at": null
}
```

- `error.code`: `content_rejected` (moderation), `invalid_input` (the model refused the parameters or a file), `model_error`, `timeout`, `insufficient_balance` (the balance was short when the generation started), `internal_error` (the result was produced but could not be saved).
- `error.refund`: `full` (the tokens came back), `not_charged`, or `pending` (still charged, support decides; only with `internal_error`).

Also: `POST /v1/generations/{id}/cancel` (before the generation starts, else `409 not_cancellable`; answers the object), `DELETE /v1/generations/{id}` (removes the files of a finished generation; answers `{"id":"gen_...","object":"generation.deleted","deleted":true}`), `GET /v1/generations?limit=20&cursor=...&model=...&status=...` (newest first; answers `{"object":"list","data":[{"id","object","model","mode","status","metadata","created_at"}],"has_more":true,"next_cursor":"..."}`, pass `next_cursor` as `cursor`).

## Modes

The exact price of a request without running it: `POST /v1/quotes` with the same body answers `{"object":"quote","model","mode","price":{"tokens":60,...},"available_tokens":1500,"held_tokens":40,"can_afford":true,"normalized_input":{...}}`. Quotes are free. `available_tokens` is what can be spent now (as in `GET /v1/balance`), and `can_afford` compares it with the price.

How to read the "Rules" of a price: the first entry of `matrix` that matches sets the price (`when`: the request's values; `when_set` / `when_unset`: fields that are filled / empty). `price` is per generation; `rate` is multiplied by the value of the `per` parameter plus the `plus` fields (with `plus_mode: "max"` the `plus` part counts as at least the `per` value). A name ending in `_duration_sec` is the measured length in seconds of the file in the field without that ending, not a parameter to send. `addons` add `add` tokens or multiply by `multiply` when their `when` matches; `per_item` adds per list item, `per_text` per 1000 characters beyond `free_chars`. More: https://unitool.ai/en/developers/pricing.md#reading-the-price-rules

### Mode `create` (Create)

- price: 14 balance tokens per generation, whatever the parameters

```bash
curl https://api.unitool.ai/v1/generations \
  -H "Authorization: Bearer $UNITOOL_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Prefer: wait=60" \
  -d '{"model":"suno","mode":"create","input":{"prompt":"A red fox running through fresh snow at sunrise","model":"V6","instrumental":false}}'
```

| `input` field | Type | Required | Values | Default | Notes |
|---|---|---|---|---|---|
| `prompt` | string | yes |  |  |  |
| `model` | string | no | `V6`, `V6_MINI`, `V6_WILD` | `"V6"` | V6 follows the brief most precisely (default). V6_MINI is faster and a little simpler, for drafts. V6_WILD blends genres and strays from the brief on purpose. Same price. |
| `lyrics` | string | no |  |  | Exact words to sing, up to 5000 characters, any language. Put section tags on their own lines: [Intro] [Verse] [Pre-Chorus] [Chorus] [Bridge] [Outro]. With lyrics the prompt is only the musical style (up to 1000 characters). Omit to let Suno write the words from the prompt (then the prompt is limited to 500 characters). |
| `instrumental` | boolean | no |  | `false` | true = no vocals, for background music. The prompt is then the musical style (up to 1000 characters). Do not combine with lyrics. |
| `title` | string | no |  |  | Track title, up to 80 characters. Only with lyrics or instrumental=true. |
| `duration` | number 10–360 | no |  |  | Target length in whole seconds, 10-360. Only with lyrics or instrumental=true; without it Suno picks the length itself. |
| `vocal_gender` | string | no | `f`, `m` |  | Singer voice: f or m. Only with lyrics; without lyrics say "female vocals" in the prompt instead. |
| `negative_tags` | string | no |  |  | Comma-separated styles or sounds to avoid, up to 200 characters. Only with lyrics or instrumental=true. |

## Client

Create, wait, poll and download in Python (`pip install requests`), mode `create`:

```python
import json, mimetypes, os, time, uuid, requests

API = "https://api.unitool.ai/v1"
KEY = {"Authorization": f"Bearer {os.environ['UNITOOL_API_KEY']}"}

def call(method, path, headers=None, retries=3, **kwargs):
    for attempt in range(retries + 1):
        reply = requests.request(method, API + path, headers={**KEY, **(headers or {})}, timeout=90, **kwargs)
        if reply.status_code in (429, 500, 502, 503, 504) and attempt < retries:
            time.sleep(float(reply.headers.get("Retry-After", 2 ** attempt)))
            continue
        if reply.status_code >= 400:
            error = reply.json()["error"]
            raise RuntimeError(f"{reply.status_code} {error['code']}: {error['message']} ({error['request_id']})")
        return reply

body = json.loads(r'''{
  "model": "suno",
  "mode": "create",
  "input": {
    "prompt": "A red fox running through fresh snow at sunrise",
    "model": "V6",
    "instrumental": false
  }
}''')
# One key per order: a retry with the same key and body returns the same generation and charges nothing again.
order = {"Idempotency-Key": str(uuid.uuid4()), "Prefer": "wait=60"}
generation = call("POST", "/generations", headers=order, json=body).json()
while generation["status"] in ("queued", "running"):
    time.sleep(5)
    generation = call("GET", f"/generations/{generation['id']}").json()

if generation["status"] == "succeeded":
    for output in generation["outputs"]:  # the links live 1 hour, the files 7 days: download now
        name = f"{generation['id']}-{output['index']}{mimetypes.guess_extension(output['content_type']) or ''}"
        open(name, "wb").write(requests.get(output["url"], timeout=300).content)
elif generation["status"] == "failed":
    print(generation["error"]["code"], generation["error"]["message"], "refund:", generation["error"]["refund"])
```

## Webhook

Instead of polling, pass `"webhook_url": "https://your.host/path"` in the create request (https, default port, a public host name, not an IP address; a bad address is `400 invalid_parameter` before anything is created or charged), or register an endpoint for all generations in the account (Settings → API → Webhooks). When the generation ends, this is POSTed to the address:

```json
{
  "type": "generation.succeeded",
  "timestamp": "2026-11-29T12:00:41.000Z",
  "data": {
    "id": "gen_6f1c0e9a2b7d4c3e8f5a1b2c3d4e5f60",
    "object": "generation",
    "model": "suno",
    "mode": "create",
    "status": "succeeded",
    "progress": 1,
    "cost": {
      "estimated_tokens": 14,
      "charged_tokens": 14,
      "refunded_tokens": 0,
      "settled": true
    },
    "outputs": [
      {
        "index": 0,
        "type": "audio",
        "file_ref": "attachment:482913",
        "url": "https://api.unitool.ai/v1/files/q83vEjRkT1mXc0yLw2hN5aZp7dUoB9sGfI4tKeYxWrQ6/file.mp3",
        "content_type": "audio/mpeg",
        "size": 482304,
        "expires_at": "2026-12-06T12:00:41.000Z"
      }
    ],
    "error": null,
    "metadata": {
      "order_id": "A-1042"
    },
    "created_at": "2026-11-29T12:00:00.000Z",
    "completed_at": "2026-11-29T12:00:41.000Z",
    "expires_at": "2026-12-06T12:00:41.000Z"
  }
}
```

- `type`: `generation.succeeded` or `generation.failed` (`generation.canceled` goes to registered endpoints only). `data` is the object `GET /v1/generations/{id}` returns; match it by `data.id` or `data.metadata`.
- Headers: `webhook-id` (`msg_...`, the same on every retry: drop duplicates by it), `webhook-timestamp` (Unix seconds), `webhook-signature` (`v1,<base64 HMAC-SHA256>`; two values separated by a space while a secret is rotated).
- Signature ([Standard Webhooks](https://www.standardwebhooks.com/)): HMAC-SHA256 of `{webhook-id}.{webhook-timestamp}.{raw body}`, the key being the base64-decoded part of the secret after `whsec_`. For `webhook_url` the secret is the account secret (Settings → API → Webhooks, "Show the account secret"); a registered endpoint has its own. The API never returns a secret.
- Answer 2xx within 10 seconds and do the work afterwards. A failed delivery to a `webhook_url` is retried in 5 s, 30 s, 2 min and 10 min (5 attempts). Delivery is at least once and unordered.
- Links in the event live 1 hour from the event. An event can be lost: for important orders also poll the generations whose event did not arrive.

```python
import base64, hashlib, hmac, time

def verify(raw_body: bytes, headers, secret: str) -> bool:
    """secret: whsec_... (the account secret for webhook_url, the endpoint's own for a registered endpoint)."""
    msg_id, ts = headers["webhook-id"], headers["webhook-timestamp"]
    if abs(time.time() - int(ts)) > 300:
        return False
    key = base64.b64decode(secret.removeprefix("whsec_"))
    expected = hmac.new(key, f"{msg_id}.{ts}.".encode() + raw_body, hashlib.sha256).digest()
    return any(hmac.compare_digest(base64.b64decode(part.split(",", 1)[1]), expected)
               for part in headers["webhook-signature"].split(" ") if "," in part)
```

## Errors and retries

A refused request answers with a non-2xx status and one shape:

```json
{
  "error": {
    "type": "invalid_request_error",
    "code": "invalid_parameter",
    "message": "Text for a person; it may change.",
    "param": "max_tokens",
    "request_id": "req_01KB7Q3X9ZP4M6T2VHC8RN5WDE",
    "doc_url": "https://unitool.ai/en/developers/errors#invalid_parameter"
  }
}
```

Branch on `error.code`, it is stable. `error.param` names the field at fault or is `null`; some codes add `error.details`. Retry only 429, 500, 502, 503 and 504.

| HTTP | `error.code` | What to do |
|---|---|---|
| 400 | `invalid_parameter`, `missing_parameter` | Fix the field named in `error.param` (for example `input.duration`). Do not retry |
| 400 | `use_chat_endpoint` | The id is a text model: call `/v1/chat/completions` |
| 401 | `invalid_api_key`, `api_key_revoked` | Fix the key. Do not retry |
| 402 | `insufficient_balance`, `price_exceeds_limit`, `key_spend_limit_reached` | Top up, raise `max_cost_tokens`, or wait for the key's limit to reset. Nothing was charged |
| 403 | `insufficient_scope`, `payment_required`, `api_access_not_enabled`, `account_suspended`, `ip_not_allowed` | The key or the account may not do this. Do not retry |
| 404 | `model_not_found`, `generation_not_found` | No such model, mode or generation |
| 409 | `not_cancellable`, `generation_not_finished` | The generation has started (cancel) or has not ended (delete) |
| 410 | `model_retired` | The model left the API; `error.details.replacement` names the successor when there is one |
| 422 | `idempotency_key_reused` | The `Idempotency-Key` was used with another body: use a new key |
| 429 | `webhook_daily_limit` | Over 2000 per-request webhooks today: register an endpoint or poll. Do not retry today |
| 429 | `rate_limit_exceeded`, `concurrency_limit_exceeded`, `balance_held` | Wait `Retry-After` seconds, then retry |
| 500 | `internal_error` | Retry with backoff, 2 or 3 attempts |
| 503 | `overloaded`, `model_unavailable`, `service_paused` | Wait `Retry-After` seconds, then retry (or use another model) |

Retry creation only with the same `Idempotency-Key`. More generations than the account runs at once are not refused: they wait in `queued`.

Every code: https://unitool.ai/en/developers/errors.md. Limits and headers: https://unitool.ai/en/developers/rate-limits.md.

## More

- Generations (uploads, retention, delete, cancel): https://unitool.ai/en/developers/generations.md
- Webhooks (endpoints, retries, secret rotation): https://unitool.ai/en/developers/webhooks.md
- The same model in the OpenAI format (`/v1/images/generations`, `/v1/images/edits`, `/v1/audio/speech`): https://unitool.ai/en/developers/images-audio.md
- Prices: https://unitool.ai/en/developers/pricing.md
- Everything in one file: https://unitool.ai/llms-full.txt
