Mozart Developers

Generate a song with Python

To generate a song with Python, send a prompt to the Mozart REST API with POST /v1/songs, wait on the job with POST /v1/jobs/wait, then download each song with POST /v1/songs/{song_id}/download. Each request costs 25 credits and makes 2 songs, with vocals and lyrics written from your prompt.

The script below does all three steps with the requests library, checks the price first and saves both songs as MP3 files. In our test on 29 November 2026 it had two finished songs in 185.8 seconds.

Get API keyRead the API reference

The REST API needs an API plan (Starter, Build, Scale or Growth), from $20 a month, or prepaid API credits, and spends API credits.

Updated November 29, 2026

On this page

What do I need before I start?

You need three things: a Mozart API key, Python 3.10 or later, and the requests library from PyPI.

  1. Make a key on the Developer page of the Mozart web app. The setup guide shows how.
  2. Put the key in an environment variable, so it never sits in your code.
  3. Install requests.
Terminal
export MOZART_API_KEY=mzk_...
pip install requests

What does the full Python script look like?

Save this as song.py and run python3 song.py. It checks the price, starts one song request, waits for the job and writes song-1.mp3 and song-2.mp3 next to the script. It uses uuid from the standard library for idempotency keys.

Python
"""Generate two songs with the Mozart REST API and save them as MP3 files."""

import os
import sys
import time
import uuid

import requests

API = os.environ.get("MOZART_API_BASE", "https://api.mozartai.com")
SESSION = requests.Session()
SESSION.headers["Authorization"] = f"Bearer {os.environ['MOZART_API_KEY']}"

SONG = {
    "prompt": "Warm indie folk song about writing code late at night, "
    "acoustic guitar, brushed drums, hopeful chorus",
}

START = time.monotonic()


def log(step: str, detail: str = "") -> None:
    print(f"[{time.monotonic() - START:6.1f}s] {step} {detail}".rstrip())


class MozartError(Exception):
    def __init__(self, status: int, error: dict):
        self.status = status
        self.code = error.get("code", "UNKNOWN")
        self.details = error.get("details", {})
        super().__init__(f"{status} {self.code}: {error.get('message', '')}")


def call(path: str, body: dict, idempotency_key: str | None = None) -> dict:
    headers = {"Idempotency-Key": idempotency_key} if idempotency_key else {}
    for attempt in range(2):
        res = SESSION.post(f"{API}{path}", json=body, headers=headers, timeout=60)
        if res.ok:
            return res.json()
        error = res.json().get("error", {})
        if error.get("code") == "PUBLIC_API_RATE_LIMITED" and attempt == 0:
            # Same key on the retry, so the job is never started twice.
            time.sleep(error.get("details", {}).get("retry_after_seconds", 5))
            continue
        raise MozartError(res.status_code, error)
    raise RuntimeError("unreachable")


def wait(job_id: str, until: str) -> dict:
    while True:
        body = call("/v1/jobs/wait", {"job_ids": [job_id], "until": until, "wait_seconds": 25})
        if body["all_settled"]:
            return body["jobs"][0]


def main() -> None:
    # 1. Price check. dry_run starts nothing and spends nothing.
    quote = call("/v1/songs", {**SONG, "dry_run": True}, str(uuid.uuid4()))
    log("price", f"{quote['estimate']['credits_required']} credits")

    # 2. Start the job. Keep the key: a retry with it returns this same job.
    key = str(uuid.uuid4())
    job = call("/v1/songs", SONG, key)["job"]
    log("job started", job["id"])

    # 3. Wait until the songs can stream, then until the files are final.
    job = wait(job["id"], "playable")
    log("playable", f"status={job['status']}")
    job = wait(job["id"], "complete")
    log("complete", f"status={job['status']}")
    if job["status"] != "succeeded":
        err = job["error"] or {}
        sys.exit(f"job {job['status']}: {err.get('code')} {err.get('next_step')}")

    # 4. Download both songs. Each link expires at url_expires_at.
    for n, song_id in enumerate(job["song_ids"], start=1):
        link = call(f"/v1/songs/{song_id}/download", {"format": "mp3"})
        audio = requests.get(link["url"], timeout=120)
        audio.raise_for_status()
        path = f"song-{n}.mp3"
        with open(path, "wb") as f:
            f.write(audio.content)
        seconds = next(
            (o["duration_seconds"] for o in job["outputs"] if o["song_id"] == song_id), None
        )
        log("saved", f"{song_id} -> {path} ({seconds} s, {len(audio.content) / 1e6:.1f} MB)")


if __name__ == "__main__":
    try:
        main()
    except MozartError as e:
        if e.code == "INSUFFICIENT_CREDITS":
            sys.exit(f"Not enough credits: this needs {e.details.get('credits_required')}.")
        sys.exit(str(e))

What did the script print in our test?

We ran this exact script once on 29 November 2026, with the default model and no length set. It printed:

Text
[   0.5s] price 25 credits
[   1.8s] job started 3299bd4e589864e7d7786721d33e81d14466ad91d6de7940105929b1b78e5bb4
[ 185.8s] playable status=succeeded
[ 186.1s] complete status=succeeded
[ 198.4s] saved 7d3d6211-c93b-43a1-9a9c-ad8e16f5f31a -> song-1.mp3 (206.8 s, 4.9 MB)
[ 201.6s] saved e93d7f0f-66f5-4957-9f81-cf2b4a6886dd -> song-2.mp3 (190 s, 4.5 MB)
StepSeconds from start
Price check returned0.5
Job started1.8
Job playable185.8
Job complete186.1
First MP3 saved198.4
Both MP3s saved201.6

The two songs were 206.8 seconds and 190 seconds long. The playable wait came back with the job already succeeded, so the complete wait returned at once. Your times will differ with load and prompt, so keep the loop rather than a fixed sleep.

How does each step work?

  1. Price check. The script sends the song body with "dry_run": true. The answer has estimate.credits_required, estimate.balance and estimate.balance_after. Nothing starts and no credits are spent.
  2. Start the job. POST /v1/songs answers 202 at once with job.id, project_id and two song_ids. The Idempotency-Key header is required.
  3. Wait. POST /v1/jobs/wait takes up to 20 job_ids and holds each call for up to 25 seconds. Loop until all_settled is true. A job ends as succeeded, failed or cancelled.
  4. Download. POST /v1/songs/{song_id}/download returns a short-lived url, its url_expires_at and content_type. Fetch the file before the link expires.

Which options does POST /v1/songs take?

Only prompt is required. These fields come from the API reference.

FieldTypeWhat it does
promptstringStyle, mood, instruments and subject. Hans 2.0 rewrites a prompt over 1,000 characters to fit.
lyricsstringWords to sing, with optional section labels in square brackets.
instrumentalbooleantrue makes both songs with no vocals. Not allowed with lyrics.
titlestringThe title of both songs. Left out, titles are written from the prompt.
modelstringhans-2, the default.
project_idstringThe project for the songs. Left out, the key's current project is used.
dry_runbooleantrue returns the price and balance and starts nothing.

The default model picks each song's length itself, so leave duration_seconds out; a model that picks its own length refuses that field with GENERATION_INPUT_NOT_SUPPORTED_BY_MODEL.

Which errors should the script handle?

Every error has the same body: error.type, error.code, error.message, error.request_id and error.details. The script raises MozartError with the code and details, retries PUBLIC_API_RATE_LIMITED once with the same key, and stops on everything else.

CodeHTTP statusWhat to do
PUBLIC_API_KEY_INVALID401Check MOZART_API_KEY, or make a new key
PUBLIC_API_CREDITS_REQUIRED402The REST API needs an API plan or API credits on the account
INSUFFICIENT_CREDITS402Stop. details.credits_required is what the request needs; add credits, then send a new request with a new key
PUBLIC_API_INPUT_INVALID400A field is missing or wrong; details.parameter names it
PUBLIC_API_IDEMPOTENCY_KEY_REUSED409The key was used with a different body; use a new key for a new request
PUBLIC_API_RATE_LIMITED429Wait details.retry_after_seconds, then retry once with the same key
PUBLIC_API_CONCURRENCY_LIMIT_REACHED429Too many jobs are running; wait for one to finish
PUBLIC_API_DAILY_LIMIT_REACHED429Try again after details.resets_at
PUBLIC_API_PROJECT_SONG_LIMIT_REACHED429The project is full; call again without project_id

A job that fails after it starts has status: "failed" and job.error with code, message and next_step, and its credits go back to your balance (credits_refunded). Full list: API error codes.

What limits should I plan for?

  • Two songs per request. Every POST /v1/songs call makes 2 songs. You can't ask for one.
  • Links expire. Download links stop working at url_expires_at. Save the files you want to keep, and ask for a new link after that.
  • Download links are counted. Each call to the download endpoint makes a new link and counts toward a daily cap, so reuse a link until it expires.
  • Write requests are rate limited. Up to 60 write requests a minute per key. See rate limits and daily caps.
  • One wait call holds briefly. POST /v1/jobs/wait returns after 25 seconds at most, so always loop on all_settled.

What can I do with the song next?

The same key and the same song_id work with the other endpoints:

Frequently asked questions

Which Python library do I need?

Only requests (pip install requests), on Python 3.10 or later. The API is plain JSON over HTTPS, so the standard library's urllib.request works too if you can't install packages; send the same headers and JSON bodies. There is no SDK to install.

How long does a song take?

In our test on 29 November 2026, the job settled 185.8 seconds after the script started, and both MP3 files were on disk at 201.6 seconds. The price check took 0.5 seconds and the job started at 1.8 seconds. Call POST /v1/jobs/wait in a loop; each call holds for up to 25 seconds.

How do I make an instrumental?

Add "instrumental": true to the POST /v1/songs body. Both songs come back with no vocals. Don't send lyrics in the same request; the two fields can't be combined.

How do I use my own lyrics?

Send them in the lyrics field, up to 3,000 characters, with optional section labels in square brackets, such as Verse and Chorus. Leave out both lyrics and instrumental and Mozart writes lyrics from your prompt.

How do I avoid paying twice on a retry?

Send an Idempotency-Key header on every POST /v1/songs call and reuse the same key when you retry that request. A repeat with the same key returns the first job and spends nothing. Use a new key only for a new request.

How do I get a WAV instead of an MP3?

Send {"format": "wav"} to POST /v1/songs/{song_id}/download. The endpoint also takes flac and m4a; mp3 is the default. Each call returns a new link that expires at url_expires_at.

How much does one request cost?

Each POST /v1/songs call costs 25 credits and makes 2 songs. Send the same body with "dry_run": true to see estimate.credits_required and your balance first; a dry run starts no job and spends no credits. See API pricing.

Can I call the API from a web or mobile app?

Call it from your own server and pass the download links to the app. Keep MOZART_API_KEY on the server, never in browser or app code.

Run the script with your own key

Get API keyRead the API reference

Make a key, export it as MOZART_API_KEY and run song.py.