### Example API Request Parameters Source: https://docs.kie.ai/suno-api/replace-section This example demonstrates the parameters used for a music generation or replacement task. It includes identifiers, creative inputs, and configuration for lyrics and callbacks. ```json { "taskId": "2fac****9f72", "audioId": "e231****-****-****-****-****8cadc7dc", "prompt": "A calm and relaxing piano track.", "tags": "Jazz", "title": "Relaxing Piano", "negativeTags": "Rock", "infillStartS": 10.5, "infillEndS": 20.75, "fullLyrics": "[Verse 1]\nOriginal lyrics here\n[Chorus]\nModified lyrics for this section\n[Verse 2]\nMore original lyrics", "callBackUrl": "https://example.com/callback" } ``` -------------------------------- ### Suno API Music Generation Example Source: https://docs.kie.ai/suno-api/quickstart A complete usage example demonstrating how to generate music with lyrics, wait for completion, and then extend the generated track. It includes error handling for the entire process. ```python def main(): api = SunoAPI('YOUR_API_KEY') try: # Generate music with lyrics print('Starting music generation...') task_id = api.generate_music( 'A nostalgic folk song about childhood memories', customMode=True, instrumental=False, model='V4_5', style='Folk, Acoustic, Nostalgic', title='Childhood Dreams' ) # Wait for completion print(f'Task ID: {task_id}. Waiting for completion...') result = api.wait_for_completion(task_id) print('Music generated successfully!') print('Generated tracks:') for i, track in enumerate(result['sunoData']): print(f"Track {i + 1}:") print(f" Title: {track['title']}") print(f" Audio URL: {track['audioUrl']}") print(f" Duration: {track['duration']}s") print(f" Tags: {track['tags']}") # Extend the first track first_track = result['sunoData'][0] print('\nExtending the first track...') extend_task_id = api.extend_music( first_track['id'], defaultParamFlag=True, prompt='Continue with a hopeful chorus', style='Folk, Uplifting', title='Childhood Dreams Extended', continueAt=60, model='V4_5' ) extend_result = api.wait_for_completion(extend_task_id) print('Music extended successfully!') print(f"Extended track URL: {extend_result['sunoData'][0]['audioUrl']}") except Exception as error: print(f'Error: {error}') if __name__ == '__main__': main() ``` -------------------------------- ### Webhook Verification Guide Source: https://docs.kie.ai/suno-api/upload-and-extend-audio Ensure callback security by implementing signature verification. ```APIDOC ## Webhook Verification ### Description This guide explains how to verify the authenticity of incoming webhook callbacks to ensure they originate from the Suno API and have not been tampered with. ### Method POST (for callbacks) ### Endpoint Your registered callback URL ### Security Callbacks are signed using a shared secret. You can obtain your secret from your API settings. The signature is typically included in a request header (e.g., `X-Signature`). ### Verification Steps 1. **Retrieve the raw request body**. 2. **Retrieve the signature** from the designated header (e.g., `X-Signature`). 3. **Compute the expected signature**: Use your shared secret and the raw request body to compute the signature using the same algorithm (e.g., HMAC-SHA256) as the API. 4. **Compare signatures**: Compare the computed signature with the signature received in the header. If they match, the callback is authentic. ### Example (Conceptual - using HMAC-SHA256) ```python import hmac import hashlib secret = "YOUR_SHARED_SECRET" def verify_signature(raw_body, signature): expected_signature = hmac.new(secret.encode('utf-8'), raw_body.encode('utf-8'), hashlib.sha256).hexdigest() return hmac.compare_digest(expected_signature, signature) # In your callback handler: # signature = request.headers.get('X-Signature') # raw_body = request.data # if verify_signature(raw_body, signature): # # Process the callback # else: # # Reject the callback ``` ### Error Handling - If signature verification fails, reject the request with a `400 Bad Request` or `401 Unauthorized` status code. ``` -------------------------------- ### Run Flask Application Source: https://docs.kie.ai/suno-api/upload-and-cover-audio-callbacks Starts the Flask development server on all available network interfaces, listening on port 3000. ```python if __name__ == '__main__': app.run(host='0.0.0.0', port=3000) ``` -------------------------------- ### JSON Request Body Example Source: https://docs.kie.ai/suno-api/generate-persona Example payload for the generate-persona request. ```json { "taskId": "5c79****be8e", "audioId": "e231****-****-****-****-****8cadc7dc", "name": "Electronic Pop Singer", "description": "A modern electronic music style pop singer, skilled in dynamic rhythms and synthesizer tones" } ``` -------------------------------- ### Success Callback Example Source: https://docs.kie.ai/suno-api/generate-music-callbacks This JSON structure represents a successful music generation task completion. It includes details about the generated audio files, prompts, and metadata. ```json { "code": 200, "msg": "All generated successfully.", "data": { "callbackType": "complete", "task_id": "2fac****9f72", "data": [ { "id": "e231****-****-****-****-****8cadc7dc", "audio_url": "https://example.cn/****.mp3", "stream_audio_url": "https://example.cn/****", "image_url": "https://example.cn/****.jpeg", "prompt": "[Verse] Night city lights shining bright", "model_name": "chirp-v3-5", "title": "Iron Man", "tags": "electrifying, rock", "createTime": "2025-01-01 00:00:00", "duration": 198.44 }, { "id": "e231****-****-****-****-****8cadc7dc", "audio_url": "https://example.cn/****.mp3", "stream_audio_url": "https://example.cn/****", "image_url": "https://example.cn/****.jpeg", "prompt": "[Verse] Night city lights shining bright", "model_name": "chirp-v3-5", "title": "Iron Man", "tags": "electrifying, rock", "createTime": "2025-01-01 00:00:00", "duration": 228.28 } ] } } ``` -------------------------------- ### Complete Success Callback Example Source: https://docs.kie.ai/suno-api/upload-and-extend-audio-callbacks This JSON payload represents a successful completion of all audio generation tracks. It includes details about the generated audio, source, and metadata. ```json { "code": 200, "msg": "All generated successfully.", "data": { "callbackType": "complete", "task_id": "2fac****9f72", "data": [ { "id": "e231****-****-****-****-****8cadc7dc", "audio_url": "https://example.cn/****.mp3", "source_audio_url": "https://example.cn/****.mp3", "stream_audio_url": "https://example.cn/****", "source_stream_audio_url": "https://example.cn/****", "image_url": "https://example.cn/****.jpeg", "source_image_url": "https://example.cn/****.jpeg", "prompt": "[Verse] Night city lights shining bright", "model_name": "chirp-v3-5", "title": "Iron Man", "tags": "electrifying, rock", "createTime": "2025-01-01 00:00:00", "duration": 198.44 } ] } } ``` -------------------------------- ### First Track Complete Callback Example Source: https://docs.kie.ai/suno-api/extend-music-callbacks This JSON payload indicates that the first audio track has been successfully generated. It contains details about the task and the first generated audio data. ```json { "code": 200, "msg": "First track generated successfully.", "data": { "callbackType": "first", "task_id": "2fac****9f72", "data": [ { "id": "e231****-****-****-****-****8cadc7dc", "audio_url": "https://example.cn/****.mp3", "stream_audio_url": "https://example.cn/****", "image_url": "https://example.cn/****.jpeg", "prompt": "[Verse] Night city lights shining bright", "model_name": "chirp-v3-5", "title": "Iron Man", "tags": "electrifying, rock", "createTime": "2025-01-01 00:00:00", "duration": 198.44 } ] } } ``` -------------------------------- ### Implement Replace Section Callback Source: https://docs.kie.ai/suno-api/replace-section-callbacks Examples for handling asynchronous callback notifications from the Suno API across different backend frameworks. ```javascript const express = require('express'); const app = express(); app.use(express.json()); app.post('/replace-section-callback', (req, res) => { const { code, msg, data } = req.body; console.log('Replace section callback received:', { code, msg, taskId: data.task_id, callbackType: data.callbackType }); if (code === 200 && data.callbackType === 'complete') { // Handle successful replacement console.log('Replacement completed successfully'); data.data.forEach((music, index) => { console.log(`Music ${index + 1}:`, { id: music.id, title: music.title, duration: music.duration, audioUrl: music.audio_url }); }); } else { // Handle failure console.log('Replacement failed:', msg); } // Always respond with success to acknowledge receipt res.json({ code: 200, msg: 'success' }); }); app.listen(3000, () => { console.log('Callback server running on port 3000'); }); ``` ```python from flask import Flask, request, jsonify import logging app = Flask(__name__) logging.basicConfig(level=logging.INFO) @app.route('/replace-section-callback', methods=['POST']) def replace_section_callback(): data = request.json code = data.get('code') msg = data.get('msg') callback_data = data.get('data', {}) logging.info(f"Replace section callback received: code={code}, msg={msg}") if code == 200 and callback_data.get('callbackType') == 'complete': # Handle successful replacement logging.info("Replacement completed successfully") music_data = callback_data.get('data', []) for i, music in enumerate(music_data): logging.info(f"Music {i + 1}: {music.get('title')} - {music.get('duration')}s") else: # Handle failure logging.error(f"Replacement failed: {msg}") # Always respond with success return jsonify({"code": 200, "msg": "success"}) if __name__ == '__main__': app.run(host='0.0.0.0', port=3000) ``` ```php 400, 'msg' => 'Invalid JSON']); exit; } $code = $data['code'] ?? null; $msg = $data['msg'] ?? ''; $callbackData = $data['data'] ?? []; error_log("Replace section callback received: code=$code, msg=$msg"); if ($code === 200 && ($callbackData['callbackType'] ?? '') === 'complete') { // Handle successful replacement error_log("Replacement completed successfully"); $musicData = $callbackData['data'] ?? []; foreach ($musicData as $index => $music) { $title = $music['title'] ?? 'Unknown'; $duration = $music['duration'] ?? 0; error_log("Music " . ($index + 1) . ": $title - {$duration}s"); } } else { // Handle failure error_log("Replacement failed: $msg"); } // Always respond with success echo json_encode(['code' => 200, 'msg' => 'success']); ?> ``` -------------------------------- ### Text Generation Complete Callback Example Source: https://docs.kie.ai/suno-api/extend-music-callbacks This JSON indicates that text generation has been completed. The 'data' array is empty as no audio data is produced at this stage. ```json { "code": 200, "msg": "Text generation completed.", "data": { "callbackType": "text", "task_id": "2fac****9f72", "data": [] } } ``` -------------------------------- ### Run Flask App Locally (Python) Source: https://docs.kie.ai/suno-api/separate-vocals-callbacks Starts a Flask development server on all available network interfaces, listening on port 3000. This is typically used for local testing. ```python if __name__ == '__main__': app.run(host='0.0.0.0', port=3000) ``` -------------------------------- ### GET /audio-alignment Source: https://docs.kie.ai/suno-api/get-timestamped-lyrics Retrieves the alignment data for lyrics, including start and end times for words, waveform visualization data, and alignment accuracy scores. ```APIDOC ## GET /audio-alignment ### Description Retrieves the alignment data for lyrics, including start and end times for words, waveform visualization data, and alignment accuracy scores. ### Method GET ### Endpoint /audio-alignment ### Response #### Success Response (200) - **alignedWords** (array) - List of objects containing word, success status, startS, endS, and palign. - **waveformData** (array) - Waveform data, used for audio visualization. - **hootCer** (number) - Lyrics alignment accuracy score. - **isStreamed** (boolean) - Whether it's streaming audio. #### Response Example { "code": 200, "msg": "success", "data": { "alignedWords": [ { "word": "[Verse]\nWaggin'", "success": true, "startS": 1.36, "endS": 1.79, "palign": 0 } ], "waveformData": [0, 1, 0.5, 0.75], "hootCer": 0.3803191489361702, "isStreamed": false } } ``` -------------------------------- ### Get Music Details Source: https://docs.kie.ai/suno-api/upload-and-extend-audio Poll task status using the Get Music Details endpoint. ```APIDOC ## GET /api/music/details ### Description This endpoint allows you to poll the status of a music generation or extension task. ### Method GET ### Endpoint /api/music/details ### Parameters #### Query Parameters - **taskId** (string) - Required - The unique identifier for the music task. ### Request Example ``` /api/music/details?taskId=task_abc123 ``` ### Response #### Success Response (200) - **status** (string) - The current status of the task (e.g., 'processing', 'completed', 'failed'). - **progress** (number) - The completion progress of the task (0-100). - **audioUrl** (string) - The URL of the generated audio if the task is completed. #### Response Example ```json { "status": "completed", "progress": 100, "audioUrl": "https://storage.example.com/generated_music.mp3" } ``` ### Error Handling - **404 Not Found**: Task ID not found. - **500 Internal Server Error**: Server encountered an error processing the request. ``` -------------------------------- ### API Error Response Example Source: https://docs.kie.ai/suno-api/generate-lyrics This example shows the structure of an error response from the API when a request fails, typically indicated by a non-200 status code. ```json { "code": 500, "msg": "Server Error - An unexpected error occurred while processing the request", "data": null } ``` -------------------------------- ### Receive WAV Conversion Callbacks in Node.js Source: https://docs.kie.ai/suno-api/convert-to-wav-callbacks Use this Node.js Express server to receive WAV conversion status updates. It logs the task status and provides the WAV file URL upon successful completion. Ensure you have Express installed (`npm install express`). ```javascript const express = require('express'); const app = express(); app.use(express.json()); app.post('/suno-wav-callback', (req, res) => { const { code, msg, data } = req.body; console.log('Received WAV conversion callback:', { taskId: data.task_id, status: code, message: msg }); if (code === 200) { // Task completed successfully console.log('WAV conversion completed'); console.log(`WAV file URL: ${data.audioWavUrl}`); // Process generated WAV file // Can download file, save locally, etc. } else { // Task failed console.log('WAV conversion failed:', msg); // Handle failure cases... } // Return 200 status code to confirm callback received res.status(200).json({ status: 'received' }); }); app.listen(3000, () => { console.log('Callback server running on port 3000'); }); ``` -------------------------------- ### Generate Music with Python Source: https://docs.kie.ai/suno-api/quickstart This Python snippet demonstrates how to generate music using the Suno API. It includes options for custom mode, instrumental tracks, and specifying models. Ensure the API key and callback URL are correctly set. ```python import requests import time class SunoAPI: def __init__(self, api_key): self.api_key = api_key self.base_url = 'https://api.kie.ai/api/v1' self.headers = { 'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json' } def generate_music(self, prompt, **options): data = { 'prompt': prompt, 'customMode': options.get('customMode', False), 'instrumental': options.get('instrumental', False), 'model': options.get('model', 'V3_5'), 'callBackUrl': options.get('callBackUrl', 'https://your-app.com/callback') } if options.get('style'): data['style'] = options['style'] if options.get('title'): data['title'] = options['title'] if options.get('negativeTags'): data['negativeTags'] = options['negativeTags'] response = requests.post(f'{self.base_url}/generate', headers=self.headers, json=data) result = response.json() if not response.ok or result.get('code') != 200: raise Exception(f"Generation failed: {result.get('msg', 'Unknown error')}") return result['data']['taskId'] def extend_music(self, audio_id, **options): data = { 'audioId': audio_id, 'defaultParamFlag': options.get('defaultParamFlag', False), 'model': options.get('model', 'V3_5'), 'callBackUrl': options.get('callBackUrl', 'https://your-app.com/callback') } if options.get('prompt'): data['prompt'] = options['prompt'] if options.get('style'): data['style'] = options['style'] if options.get('title'): data['title'] = options['title'] if options.get('continueAt'): data['continueAt'] = options['continueAt'] response = requests.post(f'{self.base_url}/generate/extend', headers=self.headers, json=data) result = response.json() if not response.ok or result.get('code') != 200: raise Exception(f"Extension failed: {result.get('msg', 'Unknown error')}") return result['data']['taskId'] def generate_lyrics(self, prompt, callback_url): data = { 'prompt': prompt, 'callBackUrl': callback_url } response = requests.post(f'{self.base_url}/lyrics', headers=self.headers, json=data) result = response.json() if not response.ok or result.get('code') != 200: raise Exception(f"Lyrics generation failed: {result.get('msg', 'Unknown error')}") return result['data']['taskId'] def wait_for_completion(self, task_id, max_wait_time=600): start_time = time.time() while time.time() - start_time < max_wait_time: status = self.get_task_status(task_id) ``` -------------------------------- ### Error Response Example Source: https://docs.kie.ai/suno-api/upload-and-cover-audio Standard structure for API error responses. ```json { "code": 500, "msg": "Server Error - An unexpected error occurred\n while processing\n the request", "data": null } ``` -------------------------------- ### Node.js: Receive Suno Audio Cover Callbacks Source: https://docs.kie.ai/suno-api/upload-and-cover-audio-callbacks Set up an Express.js server to listen for POST requests on a callback endpoint. Handles success and error codes, logs callback details, and initiates file downloads for generated audio and images. ```javascript const express = require('express'); const fs = require('fs'); const https = require('https'); const app = express(); app.use(express.json()); app.post('/suno-cover-callback', (req, res) => { const { code, msg, data } = req.body; console.log('Received Suno audio cover callback:', { taskId: data.task_id, callbackType: data.callbackType, status: code, message: msg }); if (code === 200) { // Task progressed or completed successfully const { callbackType, task_id, data: tracks } = data; console.log(`Callback type: ${callbackType}`); console.log(`Number of tracks: ${tracks.length}`); switch (callbackType) { case 'text': console.log('Text generation completed, waiting for audio...'); break; case 'first': console.log('First track completed, processing remaining tracks...'); downloadTracks(tracks, task_id); break; case 'complete': console.log('All tracks completed successfully!'); downloadTracks(tracks, task_id); break; } } else { // Task failed console.log('Suno audio cover failed:', msg); // Handle specific error types if (code === 400) { console.log('Validation error - check for copyrighted content'); } else if (code === 408) { console.log('Rate limited - please wait before retrying'); } else if (code === 413) { console.log('Content conflict - uploaded audio matches existing work'); } else if (code === 501) { console.log('Generation failed - may need to adjust parameters'); } else if (code === 531) { console.log('Server error with credit refund - safe to retry'); } } // Return 200 status code to confirm callback received res.status(200).json({ status: 'received' }); }); // Function to download tracks function downloadTracks(tracks, taskId) { tracks.forEach((track, index) => { const { id, audio_url, source_audio_url, image_url, source_image_url, title, duration } = track; console.log(`Track ${index + 1}: ${title} (${duration}s)`); // Download generated audio file if (audio_url) { downloadFile(audio_url, `suno_cover_${taskId}_${id}.mp3`) .then(() => console.log(`Generated audio downloaded: ${id}`)) .catch(err => console.error(`Generated audio download failed for ${id}:`, err)); } // Download source audio file if (source_audio_url) { downloadFile(source_audio_url, `suno_source_${taskId}_${id}.mp3`) .then(() => console.log(`Source audio downloaded: ${id}`)) .catch(err => console.error(`Source audio download failed for ${id}:`, err)); } // Download generated cover image if (image_url) { downloadFile(image_url, `suno_cover_img_${taskId}_${id}.jpeg`) .then(() => console.log(`Generated cover downloaded: ${id}`)) .catch(err => console.error(`Generated cover download failed for ${id}:`, err)); } // Download source cover image if (source_image_url) { downloadFile(source_image_url, `suno_source_img_${taskId}_${id}.jpeg`) .then(() => console.log(`Source cover downloaded: ${id}`)) .catch(err => console.error(`Source cover download failed for ${id}:`, err)); } }); } // Helper function to download files function downloadFile(url, filename) { return new Promise((resolve, reject) => { const file = fs.createWriteStream(filename); https.get(url, (response) => { if (response.statusCode === 200) { response.pipe(file); file.on('finish', () => { file.close(); resolve(); }); } else { reject(new Error(`HTTP ${response.statusCode}`)); } }).on('error', reject); }); } app.listen(3000, () => { console.log('Callback server running on port 3000'); }); ``` -------------------------------- ### Handle Suno API Callback in Python Source: https://docs.kie.ai/suno-api/cover-suno-callbacks A basic Flask-style entry point for processing API callbacks and handling download errors. ```python except Exception as e: print(f"Download failed {url}: {e}") if __name__ == '__main__': app.run(host='0.0.0.0', port=3000) ``` -------------------------------- ### GET /task-status Source: https://docs.kie.ai/suno-api/get-music-video-details Retrieves the status and result details of a specific music generation task. ```APIDOC ## GET /task-status ### Description Retrieves the current status, completion time, and generated video URL for a music generation task. ### Method GET ### Response #### Success Response (200) - **code** (integer) - Response status code - **msg** (string) - Success message - **data** (object) - Task details object - **taskId** (string) - Unique task identifier - **musicId** (string) - Unique music identifier - **callbackUrl** (string) - Callback URL - **musicIndex** (integer) - Music index 0 or 1 - **completeTime** (string) - Completion callback time - **response** (object) - Completion callback result - **videoUrl** (string) - Video URL - **successFlag** (string) - PENDING, SUCCESS, CREATE_TASK_FAILED, or GENERATE_MP4_FAILED - **createTime** (string) - Creation time - **errorCode** (integer) - Error code - **errorMessage** (string) - Error message #### Response Example { "code": 200, "msg": "success", "data": { "taskId": "988e****c8d3", "musicId": "e231****-****-****-****-****8cadc7dc", "callbackUrl": "https://api.example.com/callback", "musicIndex": 0, "completeTime": "2025-01-01 00:10:00", "response": { "videoUrl": "https://example.com/s/04e6****e727.mp4" }, "successFlag": "SUCCESS", "createTime": "2025-01-01 00:00:00", "errorCode": null, "errorMessage": null } } ``` -------------------------------- ### PHP Callback Response Example Source: https://docs.kie.ai/suno-api/generate-midi-callbacks This PHP snippet demonstrates how to save incoming callback data to a JSON file and log the process. Ensure your callback URL is publicly accessible and responds within 15 seconds. ```php 'received']); ?> ``` -------------------------------- ### Define Error Response Schema Source: https://docs.kie.ai/suno-api/convert-to-wav Example of a 500 internal server error response structure. ```json { "code": 500, "msg": "Server Error - An unexpected error occurred\nwhile processing the request", "data": null } ``` -------------------------------- ### Receive WAV Conversion Callbacks in Python Source: https://docs.kie.ai/suno-api/convert-to-wav-callbacks This Python Flask application handles WAV conversion callbacks. It logs the callback details, processes successful completions by downloading the WAV file, and returns a confirmation. Requires Flask and Requests (`pip install Flask requests`). ```python from flask import Flask, request, jsonify import requests app = Flask(__name__) @app.route('/suno-wav-callback', methods=['POST']) def handle_callback(): data = request.json code = data.get('code') msg = data.get('msg') callback_data = data.get('data', {}) task_id = callback_data.get('task_id') audio_wav_url = callback_data.get('audioWavUrl') print(f"Received WAV conversion callback: {task_id}, status: {code}, message: {msg}") if code == 200: # Task completed successfully print("WAV conversion completed") print(f"WAV file URL: {audio_wav_url}") # Process generated WAV file # Can download file, save locally, etc. if audio_wav_url: try: # Download WAV file example response = requests.get(audio_wav_url) if response.status_code == 200: with open(f"wav_file_{task_id}.wav", "wb") as f: f.write(response.content) print(f"WAV file saved as wav_file_{task_id}.wav") except Exception as e: print(f"WAV file download failed: {e}") else: # Task failed print(f"WAV conversion failed: {msg}") # Handle failure cases... # Return 200 status code to confirm callback received return jsonify({'status': 'received'}), 200 if __name__ == '__main__': app.run(host='0.0.0.0', port=3000) ``` -------------------------------- ### GET /task/status Source: https://docs.kie.ai/suno-api/quickstart Retrieves the current status and result data of a specific music generation task. ```APIDOC ## GET /task/status ### Description Checks the status of a previously initiated music generation task using the task ID. ### Response #### Success Response (200) - **code** (integer) - Status code - **msg** (string) - Status message - **data** (object) - Task details including status and generated audio metadata #### Response Example { "code": 200, "msg": "success", "data": { "taskId": "5c79****be8e", "status": "SUCCESS", "response": { "sunoData": [ { "id": "e231****-****-****-****-****8cadc7dc", "audioUrl": "https://example.cn/****.mp3", "streamAudioUrl": "https://example.cn/****", "imageUrl": "https://example.cn/****.jpeg", "prompt": "A calm and relaxing piano track", "title": "Peaceful Piano", "tags": "calm, relaxing, piano", "duration": 198.44, "createTime": "2025-01-01 00:00:00" } ] } } } ``` -------------------------------- ### POST /callback Source: https://docs.kie.ai/suno-api/add-instrumental Endpoint for receiving asynchronous callbacks after audio generation tasks are completed. ```APIDOC ## POST /callback ### Description Receives the status and results of an audio generation task once processing is finished. ### Method POST ### Response #### Success Response (200) - **code** (integer) - Status code (200) - **msg** (string) - Return message - **data** (object) - Callback data object - **callbackType** (string) - Callback type: text, first, or complete - **task_id** (string) - Task ID - **data** (array) - List of generated audio objects - **id** (string) - Audio unique identifier - **audio_url** (string) - Audio file URL - **stream_audio_url** (string) - Streaming audio URL - **image_url** (string) - Cover image URL - **prompt** (string) - Generation prompt/lyrics - **model_name** (string) - Model name used - **title** (string) - Music title - **tags** (string) - Music tags - **createTime** (string) - Creation time (date-time) - **duration** (number) - Audio duration in seconds #### Response Example { "code": 200, "msg": "All generated successfully", "data": { "callbackType": "complete", "task_id": "task_12345", "data": [ { "id": "audio_001", "audio_url": "https://example.com/audio.mp3", "stream_audio_url": "https://example.com/stream.mp3", "image_url": "https://example.com/cover.jpg", "prompt": "A happy song", "model_name": "suno-v3", "title": "Happy Day", "tags": "pop, upbeat", "createTime": "2023-10-27T10:00:00Z", "duration": 180 } ] } } ``` -------------------------------- ### GET /tasks/{taskId} Source: https://docs.kie.ai/suno-api/get-midi-details Retrieves the status and detailed results of a specific MIDI generation task. ```APIDOC ## GET /tasks/{taskId} ### Description Retrieves the status and detailed results of a specific MIDI generation task, including instrument notes and success flags. ### Method GET ### Endpoint /tasks/{taskId} ### Parameters #### Path Parameters - **taskId** (string) - Required - The unique identifier of the task. ### Response #### Success Response (200) - **code** (integer) - Response status code - **msg** (string) - Status message - **data** (object) - Task result data containing taskId, recordTaskId, audioId, callbackUrl, completeTime, midiData, successFlag, createTime, errorCode, and errorMessage. #### Response Example { "code": 200, "msg": "success", "data": { "taskId": "5c79****be8e", "recordTaskId": -1, "audioId": "e231****-****-****-****-****8cadc7dc", "callbackUrl": "https://example.callback", "completeTime": 1760335255000, "midiData": { "state": "complete", "instruments": [ { "name": "Drums", "notes": [ { "pitch": 73, "start": 0.036458333333333336, "end": 0.18229166666666666, "velocity": 1 } ] } ] }, "successFlag": 1, "createTime": 1760335251000, "errorCode": null, "errorMessage": null } } ``` -------------------------------- ### Get Music Details Source: https://docs.kie.ai/suno-api/add-instrumental Retrieve details and results for a music generation task using its Task ID. ```APIDOC ## GET /api/music/task/{taskId} ### Description Retrieves the status and results of a music generation task. ### Method GET ### Endpoint /api/music/task/{taskId} ### Parameters #### Path Parameters - **taskId** (string) - Required - The ID of the task to retrieve details for. ### Response #### Success Response (200) - **data** (object) - Contains task details. - **taskId** (string) - The ID of the task. #### Response Example ```json { "data": { "taskId": "5c79****be8e" } } ``` #### Error Response (500) - **code** (integer) - Response status code. - **msg** (string) - Response message, error description when failed. - **data** (object) - Empty object. #### Response Example ```json { "code": 500, "msg": "Server Error - An unexpected error occurred while processing the request", "data": null } ``` ``` -------------------------------- ### Process Vocal Separation Callback (PHP) Source: https://docs.kie.ai/suno-api/separate-vocals-callbacks Handles the callback for vocal separation, logging details and downloading audio stems. Requires a 'downloadAudioFile' function and file system access. ```php getMessage()); } } } $dir = "vocal_separation_$taskId"; if (!is_dir($dir)) { mkdir($dir, 0777, true); } downloadAudioFile($vocalInfo['vocal_url'] ?? '', "$dir/vocal.mp3"); if (!empty($vocalInfo['instrumental_url'])) { downloadAudioFile($vocalInfo['instrumental_url'], "$dir/instrumental.mp3"); } if (!empty($vocalInfo['backing_vocals_url'])) { $stemFiles = [ 'backing_vocals' => $vocalInfo['backing_vocals_url'] ?? '', 'drums' => $vocalInfo['drums_url'] ?? '', 'bass' => $vocalInfo['bass_url'] ?? '', 'guitar' => $vocalInfo['guitar_url'] ?? '', 'keyboard' => $vocalInfo['keyboard_url'] ?? '', 'percussion' => $vocalInfo['percussion_url'] ?? '', 'strings' => $vocalInfo['strings_url'] ?? '', ``` -------------------------------- ### GET /api/v1/generate/record-info Source: https://docs.kie.ai/suno-api/get-music-details Retrieve detailed information about a music generation task, including its status, parameters, and generated tracks. ```APIDOC ## GET /api/v1/generate/record-info ### Description Retrieve detailed information about a music generation task. This endpoint allows you to check the status of a music generation task and access the results, including generated tracks. ### Method GET ### Endpoint /api/v1/generate/record-info ### Parameters #### Query Parameters - **taskId** (string) - Required - Unique identifier of the music generation task to retrieve. This can be either a taskId from a "Generate Music" task or an "Extend Music" task. ### Responses #### Success Response (200) - **code** (integer) - Response status code. Possible values include 200, 401, 404, 422, 451, 455, 500. - **msg** (string) - Error message when code is not 200. - **data** (object) - Contains task details. - **taskId** (string) - Task ID. - **parentMusicId** (string) - Parent music ID (only valid when extending music). - **param** (string) - Parameter information for task generation. - **response** (object) - Generation response details. - **taskId** (string) - Task ID. - **sunoData** (array) - Array of generated music data. - **id** (string) - ID of the generated music track. #### Error Response (401, 404, 422, 451, 455, 500) - **code** (integer) - Error status code. - **msg** (string) - Error message describing the issue. ### Status Descriptions - `PENDING`: Task is waiting to be processed - `TEXT_SUCCESS`: Lyrics/text generation completed successfully - `FIRST_SUCCESS`: First track generation completed - `SUCCESS`: All tracks generated successfully - `CREATE_TASK_FAILED`: Failed to create task - `GENERATE_AUDIO_FAILED`: Failed to generate audio - `CALLBACK_EXCEPTION`: Error during callback process - `SENSITIVE_WORD_ERROR`: Content filtered due to sensitive words ### Developer Notes - For instrumental tracks (`instrumental=true`), no lyrics data will be included. - Maximum query rate: 3 requests per second per task. - Response includes direct URLs to audio files, images, and streaming endpoints. ```