Blog

Tutorial

minimax-music-1.5 API Tutorial: curl and Python Requests

Nov 12, 2026 12 min read
Cover image: a broad amber light band slanting through a narrow slit on a warm charcoal background, accented with understated dark geometric blocks, composed with restraint and negative space.
On this page

What minimax-music-1.5 expects from a request

Before you write a single line of code, it helps to know what a music generation call actually contains. Unlike a text completion, a music request has two creative inputs that do different jobs, plus a handful of controls that shape the output.

At a high level, a minimax-music-1.5 request carries:

  • A style or prompt description — the musical direction: genre, mood, instrumentation, tempo feel, production character.
  • Lyrics — the words that will be sung, when the track is vocal. Instrumental requests leave this empty or omit it.
  • Structural controls — things like the intended duration of the generated track, which bound how long the model composes.
  • The model identifier — minimax-music-1.5 — so the gateway routes the job to the right backend.

The mental model to hold onto: the style input tells the model how it should sound, and the lyrics input tells it what gets sung. They are not interchangeable. If you stuff genre descriptors into the lyrics field, you get confused output; if you leave lyrics empty but ask for a vocal track, you get something the model has to invent. Decide up front which of the two modes you are in.

Two more expectations to internalize before coding:

  1. Music generation is not instant. A finished track takes real compute time, so the API is asynchronous by design. You submit a job, then retrieve the result. Any tutorial that shows a single blocking call is hiding the polling loop from you.
  2. The output is delivered by reference. You receive a URL to the generated audio rather than raw bytes inline. Plan to download or stream it separately.

Once you can articulate those three things — style vs. lyrics, async lifecycle, URL-based output — the actual payload becomes easy to read.

Getting set up with HiAPI

You need three things before your first call: an API key, the base endpoint, and a habit of not hardcoding the key.

The API key

Create a key in your HiAPI account dashboard. Treat it like a password: it authenticates every request and is scoped to your account's usage. Never commit it, never paste it into a public gist, and never ship it inside a mobile or browser bundle.

The base endpoint

All calls go to the HiAPI gateway, which exposes minimax-music-1.5 behind a single unified interface. You do not need separate credentials or SDKs for each model — the model name in the payload selects the backend. Check the API reference for the exact base URL and the current request path.

Keeping the key out of source

The pattern that scales from a scratch script to production is environment variables:

export HIAPI_API_KEY="your-key-here"

Then read it at runtime. In Python that is os.environ["HIAPI_API_KEY"]; in shell it is $HIAPI_API_KEY. If you use a .env file locally, add it to .gitignore before the first commit — not after. For deployed services, inject the key through your platform's secret manager rather than baking it into an image.

A quick sanity check before you build anything: confirm the key is visible to the process you are about to run (echo $HIAPI_API_KEY in the same shell). Most "authentication failed" reports trace back to a key exported in one terminal and a script run in another.

Your first working request with curl

Start with curl. It removes every layer of abstraction and shows you exactly what goes over the wire. The request below generates a short vocal track; adapt the field values to your own intent.

curl -X POST "$HIAPI_BASE_URL/minimax-music-1.5" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "minimax-music-1.5",
    "prompt": "warm indie folk, fingerpicked acoustic guitar, soft brushed drums, intimate close-mic vocal",
    "lyrics": "[verse]\nMorning light on the kitchen floor\n[chorus]\nWe are still here, we are still here",
    "duration": 30
  }'

Line by line:

  • -X POST — generation is a create operation, not a read.
  • Authorization: Bearer $HIAPI_API_KEY — the key from the previous section, expanded by the shell so it never appears in your history if you reference the variable.
  • Content-Type: application/json — the gateway expects JSON; omitting this header is a common cause of confusing 4xx responses.
  • model — pins the request to minimax-music-1.5.
  • prompt — the style description. Be concrete about instrumentation and mood rather than using a single adjective.
  • lyrics — the sung text, with light section tags like [verse] and [chorus] to hint at structure. The \n escapes are JSON newlines.
  • duration — bounds the length of the generated track in seconds.

What comes back is a job reference, not audio. Capture it:

curl -s -X POST "$HIAPI_BASE_URL/minimax-music-1.5" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d @payload.json | tee job.json

Reading the payload from a file with -d @payload.json keeps your shell history clean and makes the transition to Python trivial — the file is the request body. Inspect the response and note the job or task identifier plus any status field; you will need the identifier to fetch the result.

Porting the request to Python

The Python version should feel like a transcription of the curl call, not a rewrite. Use requests, read the key from the environment, and keep the payload as a dictionary so it stays readable.

import os
import json
import requests

API_KEY = os.environ["HIAPI_API_KEY"]
BASE_URL = os.environ["HIAPI_BASE_URL"]

payload = {
    "model": "minimax-music-1.5",
    "prompt": "warm indie folk, fingerpicked acoustic guitar, soft brushed drums, intimate close-mic vocal",
    "lyrics": "[verse]\nMorning light on the kitchen floor\n[chorus]\nWe are still here, we are still here",
    "duration": 30,
}

response = requests.post(
    f"{BASE_URL}/minimax-music-1.5",
    headers={
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
    },
    data=json.dumps(payload),
    timeout=60,
)
response.raise_for_status()
job = response.json()
print(json.dumps(job, indent=2))

A few porting notes that save surprises:

  • Use json.dumps with data=, or json=payload. Both work; json=payload lets requests set the content type for you. If you pass a dict to data= without serializing, the server receives a form-encoded body and rejects it.
  • Always set a timeout. Without one, a stalled connection hangs your process indefinitely. Remember this timeout covers the submission, not the generation — that is the next section's problem.
  • Call raise_for_status() before parsing. It turns a 4xx or 5xx into a clear exception instead of a mysterious KeyError when you reach for a field that is not there.
  • Keep the response object around. When debugging, printing response.status_code and response.text tells you far more than the parsed error alone.

The result of this script is the same job reference curl produced. Everything after submission — polling, retrying, downloading — is identical regardless of language, which is why it deserves its own section.

Handling the async task lifecycle

The single most common mistake with music generation is treating it like a chat completion: send, wait, read the track. The submission call returns quickly, but the audio does not exist yet. Your code has to close the loop.

The three states

Every job moves through a small state machine:

  1. Submitted — you have a job identifier and the work is queued or running.
  2. Finished — the audio is ready and the response carries a URL to it.
  3. Failed — generation aborted; the response explains why.

Your polling loop should distinguish all three. A status of submitted means keep waiting, not retry.

Poll, do not hammer

A naive loop that fires status checks as fast as the CPU allows will burn rate limit and tell you nothing new — a track takes tens of seconds to render, so hundreds of checks per minute are pure waste. Add backoff:

import time

def wait_for_job(job_id, base_url, api_key, interval=2.0, max_wait=300):
    deadline = time.time() + max_wait
    while time.time() < deadline:
        r = requests.get(
            f"{base_url}/jobs/{job_id}",
            headers={"Authorization": f"Bearer {api_key}"},
            timeout=30,
        )
        r.raise_for_status()
        data = r.json()
        status = data.get("status")
        if status == "finished":
            return data
        if status == "failed":
            raise RuntimeError(f"job failed: {data}")
        time.sleep(interval)
    raise TimeoutError(f"job {job_id} not finished after {max_wait}s")

Check the API reference for the exact polling path and status strings — treat the names above as illustrative and align them with the documented values.

Retry the right thing

Retries belong at two different levels, and mixing them up causes duplicate work. A transport retry — the HTTP call itself failed with a 5xx or a connection reset — is safe to repeat for the polling request. A generation retry is a new submission and costs you another render, so only do it when the job explicitly reports failure, and cap the count. Never retry a submission because polling was slow.

Finally, persist the job identifier the moment you receive it. If your process crashes between submission and completion, the identifier is the only way to recover the finished track without paying to generate it again.

Tuning lyrics, style, and duration inputs

Getting a usable track out of minimax-music-1.5 is mostly about writing the two text fields with intent. A few habits make the difference between generic output and something you would actually ship.

Write style prompts like a producer's brief

A single genre word gives the model too much freedom. Stack the concrete dimensions:

  • Genre and era — "late-90s trip hop" beats "electronic".
  • Instrumentation — name the lead instrument and the rhythm section.
  • Mood and energy — "melancholic but driving" sets a tension a single adjective cannot.
  • Production character — "lo-fi, tape saturation, wide stereo" steers the mix.

Keep it to one or two sentences. Long paragraph-style prompts tend to dilute rather than refine.

Structure lyrics with tags

Light section markers — [verse], [chorus], [bridge] — give the model a roadmap and usually produce cleaner song structure than an unmarked block of text. Keep lines short enough to sing; a twelve-word line rarely fits a melody. For instrumental tracks, omit lyrics entirely rather than sending an empty string with style text inside it.

Match duration to the material

Duration bounds the composition. A short duration with a full verse-chorus-verse lyric sheet forces compression and the result sounds rushed; a long duration with two lines of lyrics invites repetition. Decide the shape of the song first, then set duration to fit it. If you need a longer piece, extend the lyrics rather than stretching the time and hoping.

Iterate with small changes

When a track is close but wrong, change one input at a time — the instrumentation in the prompt, or the tempo word, or the lyric line that landed badly. Changing everything at once makes it impossible to learn which field caused the improvement. Keep your best payload in a file and branch from it.

Troubleshooting common errors

Most failures fall into a handful of recognizable buckets. Match the symptom, apply the fix, move on.

Authentication failures

Symptom: a 401 or 403 with a message about credentials.

  • Confirm the header is Authorization: Bearer <key> — the word Bearer and the space are required.
  • Verify the environment variable is actually set in the process that made the request. A key exported in one shell does not reach a cron job or a Docker container.
  • Check for stray whitespace or newlines copied along with the key.

Malformed payloads

Symptom: a 400 with a validation message.

  • Send Content-Type: application/json. A missing header makes the server misinterpret a perfectly good body.
  • If using requests, pass json=payload or data=json.dumps(payload). Passing a raw dict to data= form-encodes it.
  • Validate field names and types against the API reference: model must be exactly minimax-music-1.5, duration an integer, and the lyrics newlines properly escaped as \n inside JSON.
  • When in doubt, curl -d @payload.json isolates whether the body itself is valid before any Python is involved.

Timeouts and connection errors

Symptom: the request hangs, or raises a connection error.

  • Set an explicit timeout on every call. The submission timeout should be generous enough for queue latency but is not the render time.
  • Do not set your polling timeout equal to your overall max_wait; a single slow status check should not abort a job that is still running.
  • If submissions time out repeatedly while polling succeeds, your payload may be large — trim the lyrics.

Polling mistakes

Symptom: you keep polling and never see finished, or you poll the wrong resource.

  • Confirm you are using the job identifier from the submission response, not a request ID or correlation header.
  • Treat submitted/running as "keep waiting" rather than "retry submission". A duplicate submission generates a second track.
  • Add backoff. Aggressive polling invites rate limiting, which looks like a failure but is self-inflicted.
  • If a job reports failed, read the message before resubmitting — an invalid lyric tag or an out-of-range duration will fail identically every time.

When you are stuck, drop back to the raw curl call with -v to see the actual status line and headers. That single step resolves most ambiguity faster than any amount of Python debugging.

Related articles

View all articles →

Start building with persistent AI artifacts

Get your API key and call image, video and audio models through one task-based API.

Read the API docs