### Error Handling Examples Source: https://docs.api.box/suno-api/quickstart Code examples demonstrating how to handle common API errors, such as content policy violations, insufficient credits, and rate limiting. ```APIDOC ## Error Handling Effective error handling is crucial for a seamless integration with the API. Below are examples for common error scenarios: ### Content Policy Violation (Code 400) This example shows how to catch and handle errors related to content policy violations, typically when copyrighted material is detected. ```javascript try { const taskId = await api.generateMusic('copyrighted lyrics'); } catch (error) { if (error.data.code === 400) { console.log('Please use only original content'); } } ``` ### Insufficient Credits (Code 429) Handle cases where the user account lacks sufficient credits to perform the requested operation. ```javascript try { const taskId = await api.generateMusic('original composition'); } catch (error) { if (error.data.code === 429) { console.log('Please add more credits to your account'); } } ``` ### Rate Limiting (Code 405) Implement retry logic with exponential backoff to manage rate limiting errors gracefully. ```javascript const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms)); async function generateWithRetry(prompt, options, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await api.generateMusic(prompt, options); } catch (error) { if (error.data.code === 405 && i < maxRetries - 1) { await delay(Math.pow(2, i) * 1000); // Exponential backoff continue; } throw error; } } } ``` ``` -------------------------------- ### POST /generate Source: https://docs.api.box/suno-api/quickstart Generates music based on a given prompt and optional parameters. ```APIDOC ## POST /generate ### Description Generates music based on a given prompt and optional parameters. ### Method POST ### Endpoint /api/v1/generate ### Parameters #### Request Body - **prompt** (string) - Required - The text prompt for music generation. - **customMode** (boolean) - Optional - Enables custom mode. - **instrumental** (boolean) - Optional - Generates an instrumental track. - **model** (string) - Optional - The music generation model to use (default: 'V3_5'). - **style** (string) - Optional - The musical style for the generation. - **title** (string) - Optional - The title of the generated music. - **negativeTags** (string) - Optional - Tags to exclude from the generation. - **callBackUrl** (string) - Optional - URL to receive notifications upon completion (default: 'https://your-app.com/callback'). - **vocalGender** (string) - Optional - The desired gender of the vocals. - **styleWeight** (number) - Optional - Weight for the style parameter. - **weirdnessConstraint** (number) - Optional - Constraint for the weirdness of the generation. - **audioWeight** (number) - Optional - Weight for the audio quality. ### Request Example ```json { "prompt": "Upbeat electronic dance music with a catchy melody", "style": "EDM", "title": "Dance Track 1" } ``` ### Response #### Success Response (200) - **taskId** (string) - The ID of the music generation task. #### Response Example ```json { "code": 200, "msg": "Success", "data": { "taskId": "task_abc123" } } ``` ``` -------------------------------- ### GET /api/v1/generate/record-info Source: https://docs.api.box/suno-api/quickstart Checks the status of a music generation task using the provided taskId. Returns the status and, upon completion, the audio track information. ```APIDOC ## GET /api/v1/generate/record-info ### Description Checks the status of a music generation task using the provided taskId. Returns the status and, upon completion, the audio track information. ### Method GET ### Endpoint https://api.api.box/api/v1/generate/record-info ### Parameters #### Query Parameters - **taskId** (string) - Required - The unique identifier for the music generation task. ### Response #### Success Response (200) - **data** (object) - Contains task information. - **status** (string) - The current status of the task (e.g., "SUCCESS", "PENDING", "FAILED"). - **response** (object) - If status is "SUCCESS", contains audio track details. - **data** (array) - Array of audio track objects. - **audio_url** (string) - The URL to the generated audio track. ### Response Example ```json { "data": { "status": "SUCCESS", "response": { "data": [ { "audio_url": "https://api.api.box/audio/generated/track1.mp3" } ] } } } ``` ``` -------------------------------- ### API Response Example (JSON) Source: https://docs.api.box/suno-api/get-music-video-details Demonstrates a successful API response structure, including task identifiers, callback URLs, timestamps, and media URLs. This example is valid when a task completes successfully. ```json { "code": 200, "msg": "success", "data": { "taskId": "taskId_774b9aa0422f", "musicId": "audioId_0295980ec02e", "callbackUrl": "https://api.example.com/callback", "musicIndex": 0, "completeTime": 1735661400000, "response": { "videoUrl": "https://example.com/videos/video_847715e66259.mp4" }, "successFlag": "SUCCESS", "createTime": 1735661400000, "errorCode": null, "errorMessage": null } } ``` -------------------------------- ### Support Information Source: https://docs.api.box/suno-api/quickstart Contact details and resources for obtaining assistance with the API. ```APIDOC ## Support If you require assistance or have questions regarding the API, please utilize the following resources: - **Email Support**: Reach out to our technical support team at [support@api.box](mailto:support@api.box). - **Documentation**: Refer to the detailed API documentation and examples for comprehensive guidance. - **API Status**: Monitor the [API status page](https://api.box/status) for real-time information on API health and performance. ``` -------------------------------- ### POST /lyrics Source: https://docs.api.box/suno-api/quickstart Generates lyrics based on a given prompt. ```APIDOC ## POST /lyrics ### Description Generates lyrics based on a given prompt. ### Method POST ### Endpoint /api/v1/lyrics ### Parameters #### Request Body - **prompt** (string) - Required - The text prompt for lyrics generation. - **callBackUrl** (string) - Optional - URL to receive notifications upon completion. ### Request Example ```json { "prompt": "A love song about stars and moon", "callBackUrl": "https://your-app.com/lyric-callback" } ``` ### Response #### Success Response (200) - **taskId** (string) - The ID of the lyrics generation task. #### Response Example ```json { "code": 200, "msg": "Success", "data": { "taskId": "task_ghi789" } } ``` ``` -------------------------------- ### Boost Music Style API Source: https://docs.api.box/suno-api/quickstart Enhance style descriptions with V4_5 conversational prompts. ```APIDOC ## POST /suno-api/boost-music-style ### Description Enhance music style descriptions using V4_5 conversational prompts. ### Method POST ### Endpoint /suno-api/boost-music-style ### Parameters #### Request Body - **style_description** (string) - Required - The initial music style description. - **enhancement_prompt** (string) - Required - A conversational prompt to enhance the style. ### Request Example ```json { "style_description": "upbeat pop", "enhancement_prompt": "Make it sound more like 80s synth-pop with a driving beat." } ``` ### Response #### Success Response (200) - **enhanced_style** (string) - The enhanced music style description. #### Response Example ```json { "enhanced_style": "80s synth-pop with a driving beat, upbeat pop elements" } ``` ``` -------------------------------- ### Upload & Extend Audio API Source: https://docs.api.box/suno-api/quickstart Upload audio files and seamlessly extend them. ```APIDOC ## POST /suno-api/upload-and-extend-audio ### Description Upload audio files and seamlessly extend them. ### Method POST ### Endpoint /suno-api/upload-and-extend-audio ### Parameters #### Request Body - **audio_file** (file) - Required - The audio file to upload. - **duration_seconds** (integer) - Required - The desired duration in seconds to extend the track by. ### Request Example ``` (Form data with audio_file and duration_seconds) ``` ### Response #### Success Response (200) - **audio_url** (string) - The URL of the extended audio. #### Response Example ```json { "audio_url": "https://api.box/audio/extended_song.mp3" } ``` ``` -------------------------------- ### POST /generate/extend Source: https://docs.api.box/suno-api/quickstart Extends an existing music track with new content. ```APIDOC ## POST /generate/extend ### Description Extends an existing music track with new content. ### Method POST ### Endpoint /api/v1/generate/extend ### Parameters #### Request Body - **audioId** (string) - Required - The ID of the audio track to extend. - **defaultParamFlag** (boolean) - Optional - Use default parameters. - **model** (string) - Optional - The music generation model to use (default: 'V3_5'). - **prompt** (string) - Optional - The text prompt for extending the music. - **style** (string) - Optional - The musical style for the extension. - **title** (string) - Optional - The title of the extended music. - **continueAt** (number) - Optional - The timestamp (in seconds) to continue from. - **callBackUrl** (string) - Optional - URL to receive notifications upon completion (default: 'https://your-app.com/callback'). - **vocalGender** (string) - Optional - The desired gender of the vocals. - **styleWeight** (number) - Optional - Weight for the style parameter. - **weirdnessConstraint** (number) - Optional - Constraint for the weirdness of the generation. - **audioWeight** (number) - Optional - Weight for the audio quality. ### Request Example ```json { "audioId": "audio_xyz789", "prompt": "Continue with a guitar solo", "continueAt": 60 } ``` ### Response #### Success Response (200) - **taskId** (string) - The ID of the music extension task. #### Response Example ```json { "code": 200, "msg": "Success", "data": { "taskId": "task_def456" } } ``` ``` -------------------------------- ### API Request Example (JSON) Source: https://docs.api.box/suno-api/add-vocals This example demonstrates a typical JSON request payload for the API, including parameters for prompt, title, negative tags, style, vocal gender, and model selection. It also includes URLs for audio upload and callback notifications. ```json { "prompt": "A calm and relaxing piano track with soothing vocals", "title": "Relaxing Piano with Vocals", "negativeTags": "Heavy Metal, Aggressive Vocals", "style": "Jazz", "vocalGender": "m", "styleWeight": 0.61, "weirdnessConstraint": 0.72, "audioWeight": 0.65, "uploadUrl": "https://example.com/instrumental.mp3", "callBackUrl": "https://api.example.com/callback", "model": "V4_5PLUS" } ``` -------------------------------- ### Upload & Cover Audio API Source: https://docs.api.box/suno-api/quickstart Transform uploaded audio into new styles. ```APIDOC ## POST /suno-api/upload-and-cover-audio ### Description Upload audio files and transform them into new styles. ### Method POST ### Endpoint /suno-api/upload-and-cover-audio ### Parameters #### Request Body - **audio_file** (file) - Required - The audio file to upload. - **style** (string) - Required - The desired style to transform the audio into. ### Request Example ``` (Form data with audio_file and style) ``` ### Response #### Success Response (200) - **audio_url** (string) - The URL of the transformed audio. #### Response Example ```json { "audio_url": "https://api.box/audio/transformed_song.mp3" } ``` ``` -------------------------------- ### POST /generate/add-vocals Source: https://docs.api.box/suno-api/quickstart Adds vocals to an existing audio track. ```APIDOC ## POST /generate/add-vocals ### Description Adds vocals to an existing audio track. ### Method POST ### Endpoint /api/v1/generate/add-vocals ### Parameters #### Request Body - **uploadUrl** (string) - Required - The URL of the audio file to add vocals to. - **prompt** (string) - Required - The text prompt for vocal generation. - **style** (string) - Required - The vocal style. - **title** (string) - Required - The title of the final track. - **negativeTags** (string) - Required - Tags to exclude from vocal generation. - **model** (string) - Optional - The model to use for adding vocals (default: 'V4_5PLUS'). - **callBackUrl** (string) - Optional - URL to receive notifications upon completion (default: 'https://your-app.com/callback'). - **vocalGender** (string) - Optional - The desired gender of the vocals. - **styleWeight** (number) - Optional - Weight for the style parameter. - **weirdnessConstraint** (number) - Optional - Constraint for the weirdness of the generation. - **audioWeight** (number) - Optional - Weight for the audio quality. ### Request Example ```json { "uploadUrl": "https://your-storage.com/audio.wav", "prompt": "Singing about lost love", "style": "Ballad", "title": "Sad Song", "negativeTags": "auto-tune" } ``` ### Response #### Success Response (200) - **taskId** (string) - The ID of the add vocals task. #### Response Example ```json { "code": 200, "msg": "Success", "data": { "taskId": "task_jkl012" } } ``` ``` -------------------------------- ### Add Vocals API Source: https://docs.api.box/suno-api/quickstart Generate vocal tracks for instrumental music. ```APIDOC ## POST /suno-api/add-vocals ### Description Generate vocal tracks for instrumental music using AI. ### Method POST ### Endpoint /suno-api/add-vocals ### Parameters #### Request Body - **instrumental_url** (string) - Required - The URL of the instrumental music track. - **lyrics** (string) - Required - The lyrics to be sung. - **vocal_style** (string) - Optional - The desired style of the vocals. ### Request Example ```json { "instrumental_url": "https://api.box/audio/instrumental_track.mp3", "lyrics": "La la la, this is a song", "vocal_style": "female, pop" } ``` ### Response #### Success Response (200) - **audio_url** (string) - The URL of the new audio track with generated vocals. #### Response Example ```json { "audio_url": "https://api.box/audio/song_with_vocals.mp3" } ``` ``` -------------------------------- ### Add Instrumental API Source: https://docs.api.box/suno-api/quickstart Add instrumental elements to existing audio tracks. ```APIDOC ## POST /suno-api/add-instrumental ### Description Add instrumental elements to existing audio tracks. ### Method POST ### Endpoint /suno-api/add-instrumental ### Parameters #### Request Body - **audio_url** (string) - Required - The URL of the existing audio track. - **instrumental_prompt** (string) - Required - A description of the instrumental to add. ### Request Example ```json { "audio_url": "https://api.box/audio/vocals_only.mp3", "instrumental_prompt": "A gentle piano melody" } ``` ### Response #### Success Response (200) - **audio_url** (string) - The URL of the new audio track with added instrumentals. #### Response Example ```json { "audio_url": "https://api.box/audio/song_with_instrumental.mp3" } ``` ``` -------------------------------- ### WAV Conversion API Source: https://docs.api.box/suno-api/quickstart Convert audio to high-quality WAV format. ```APIDOC ## POST /suno-api/convert-to-wav-format ### Description Convert audio files to high-quality WAV format. ### Method POST ### Endpoint /suno-api/convert-to-wav-format ### Parameters #### Request Body - **audio_file** (file) - Required - The audio file to convert. ### Request Example ``` (Form data with audio_file) ``` ### Response #### Success Response (200) - **wav_url** (string) - The URL of the converted WAV audio file. #### Response Example ```json { "wav_url": "https://api.box/audio/converted_audio.wav" } ``` ``` -------------------------------- ### Best Practices Source: https://docs.api.box/suno-api/quickstart Guidelines and recommendations for optimizing your use of the API, including prompt engineering, model selection, performance, and content policies. ```APIDOC ## Best Practices To ensure optimal results and efficient usage of the API, adhere to the following best practices: ### Prompt Engineering - **Specificity**: Clearly define the desired genre, mood, and instruments. - **Descriptive Language**: Use vivid adjectives to refine the musical style. - **Tempo and Energy**: Include details about the intended tempo and energy level. - **Style References**: Mention musical eras or specific artists to guide the style. ### Model Selection - **V3_5**: Ideal for generating structured songs with discernible verse-chorus patterns. - **V4**: Recommended when the quality of vocals is the primary concern. - **V4_5**: Suitable for faster generation processes and intelligent prompt interpretation. - **V4_5PLUS**: Offers the highest quality output and supports the generation of longer tracks. ### Performance Optimization - **Callbacks**: Utilize callbacks instead of frequent polling for real-time updates. - **Non-Custom Mode**: Start with non-custom mode for simpler requirements. - **Error Handling**: Implement robust error handling to manage generation failures gracefully. - **Caching**: Cache generated content, as files typically expire after 14-15 days. ### Content Guidelines - **Originality**: Avoid using copyrighted materials in your prompts. - **Unique Content**: Ensure lyrics and music descriptions are original. - **Policy Compliance**: Be mindful of content policies, particularly concerning lyrical themes. - **Filter Avoidance**: Test prompt variations to prevent triggering sensitive word filters. ``` -------------------------------- ### Successful API Response Example (JSON) Source: https://docs.api.box/suno-api/get-timestamped-lyrics This snippet demonstrates a successful API response for lyric alignment. It includes details such as word, success status, start and end times, alignment parameter, waveform data, accuracy score, and streaming status. This structure is useful for applications that process and display lyrics synchronized with audio. ```json { "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 } } ``` -------------------------------- ### Key Parameters Source: https://docs.api.box/suno-api/quickstart Detailed explanation of key parameters used in music generation requests, including prompts, styles, and titles. ```APIDOC ## Key Parameters ### Parameters #### Request Body - **prompt** (string) - Required - Text description of the desired music. Specificity regarding genre, mood, and instruments is recommended. Character limits vary by mode and model (500 to 5000 characters). - **style** (string) - Optional - Music style specification (required in custom mode). Examples: Jazz, Classical, Electronic, Pop, Rock, Hip-hop. Character limits vary by model (200 to 1000 characters). - **title** (string) - Optional - Title for the generated music track (required in custom mode). Maximum length: 80 characters. ``` -------------------------------- ### Get Timestamped Lyrics API Source: https://docs.api.box/suno-api/quickstart Retrieve timestamped synchronized lyrics for a given audio. ```APIDOC ## POST /suno-api/get-timestamped-lyrics ### Description Retrieve timestamped synchronized lyrics for a given audio track. ### Method POST ### Endpoint /suno-api/get-timestamped-lyrics ### Parameters #### Request Body - **audio_url** (string) - Required - The URL of the audio track. ### Request Example ```json { "audio_url": "https://api.box/audio/song_with_lyrics.mp3" } ``` ### Response #### Success Response (200) - **lyrics** (array) - An array of objects, each containing text and start/end timestamps. - **text** (string) - The lyric phrase. - **start_timestamp** (float) - The start time in seconds. - **end_timestamp** (float) - The end time in seconds. #### Response Example ```json { "lyrics": [ {"text": "Verse 1", "start_timestamp": 0.5, "end_timestamp": 1.2}, {"text": "It was a dark and stormy night", "start_timestamp": 1.5, "end_timestamp": 3.0} ] } ``` ``` -------------------------------- ### Python API Callback Handler Source: https://docs.api.box/suno-api/generate-music-callbacks A simple Python Flask example to handle API callback requests. It returns a JSON response with a status and HTTP code, indicating successful receipt of the callback. This snippet is part of a web framework setup. ```python return jsonify({'status': 'received'}), 200 if __name__ == '__main__': app.run(host='0.0.0.0', port=3000) ``` ``` -------------------------------- ### Core Features Source: https://docs.api.box/suno-api/quickstart Overview of the core functionalities offered by the API, including music generation, editing, and media conversion. -------------------------------- ### Receive Music Extension Callbacks (Node.js & Python) Source: https://docs.api.box/suno-api/extend-music-callbacks These examples show how to set up a server endpoint to receive and process callback notifications from a music extension service. They handle different callback types and status codes, providing basic logging and demonstrating how to access the returned music data. Ensure you have the necessary frameworks (Express for Node.js, Flask for Python) installed. ```javascript const express = require('express'); const app = express(); app.use(express.json()); app.post('/extend-callback', (req, res) => { const { code, msg, data } = req.body; console.log('Received music extension callback:', { taskId: data.task_id, callbackType: data.callbackType, status: code, message: msg }); if (code === 200) { // Task successful const { callbackType, data: musicData } = data; switch (callbackType) { case 'text': console.log('Text generation completed'); break; case 'first': console.log('First extended music track generated'); if (musicData.length > 0) { console.log(`Extended music title: ${musicData[0].title}`); console.log(`Audio link: ${musicData[0].audio_url}`); console.log(`Duration: ${musicData[0].duration} seconds`); } break; case 'complete': console.log('All extended music tracks generated'); console.log(`Total ${musicData.length} extended tracks:`); musicData.forEach((track, index) => { console.log(`Track ${index + 1}: ${track.title} - ${track.audio_url}`); }); // Process extended music // Can download music, save locally, etc. break; } } else { // Task failed console.log('Music extension failed:', msg); // Handle failure cases... if (code === 400) { console.log('Invalid source audio or parameter error'); } else if (code === 429) { console.log('Insufficient credits'); } else if (code === 500) { console.log('Server internal error'); } } // Return 200 status code to confirm callback received res.status(200).json({ status: 'received' }); }); app.listen(3000, () => { console.log('Extension callback server running on port 3000'); }); ``` ```python from flask import Flask, request, jsonify import requests app = Flask(__name__) @app.route('/extend-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') callback_type = callback_data.get('callbackType') music_data = callback_data.get('data', []) print(f"Received music extension callback: {task_id}, Type: {callback_type}, Status: {code}") if code == 200: # Task successful if callback_type == 'text': print("Text generation completed") elif callback_type == 'first': print("First extended music track generated") if music_data: track = music_data[0] print(f"Extended music title: {track.get('title')}") print(f"Audio link: {track.get('audio_url')}") print(f"Duration: {track.get('duration')} seconds") elif callback_type == 'complete': print("All extended music tracks generated") print(f"Total {len(music_data)} extended tracks:") for i, track in enumerate(music_data): print(f"Track {i + 1}: {track.get('title')} - {track.get('audio_url')}") # Download extended music example try: audio_url = track.get('audio_url') if audio_url: response = requests.get(audio_url) if response.status_code == 200: filename = f"extended_music_{task_id}_{i + 1}.mp3" with open(filename, "wb") as f: f.write(response.content) print(f"Extended music saved as {filename}") except Exception as e: print(f"Music download failed: {e}") else: # Task failed print(f"Music extension failed: {msg}") # Handle failure cases... if code == 400: print("Invalid source audio or parameter error") elif code == 429: print("Insufficient credits") elif code == 500: print("Server internal error") return jsonify({'status': 'received'}) if __name__ == '__main__': app.run(port=5000) ``` -------------------------------- ### Get Remaining Credits (OpenAPI) Source: https://docs.api.box/suno-api/get-remaining-credits This OpenAPI specification defines the GET /api/v1/generate/credit endpoint for retrieving account credit balance. It requires Bearer Token authentication and returns a JSON object with status code, message, and the number of available credits. ```yaml paths: path: /api/v1/generate/credit method: get servers: - url: https://api.api.box description: API Server request: security: - title: BearerAuth parameters: query: {} header: Authorization: type: http scheme: bearer description: >- # 🔑 API Authentication All endpoints require authentication using Bearer Token. ## Get API Key 1. Visit the [API Key Management Page](https://api.box/api-key) to obtain your API Key ## Usage Add to request headers: ``` Authorization: Bearer YOUR_API_KEY ``` > **⚠️ Note:** > - Keep your API Key secure and do not share it with others > - If you suspect your API Key has been compromised, reset it immediately from the management page cookie: {} parameters: {} body: {} response: '200': application/json: schemaArray: - type: object properties: code: allOf: - type: integer description: >- # Status Codes - ✅ 200 - Request successful - ⚠️ 400 - Invalid parameters - ⚠️ 401 - Unauthorized access - ⚠️ 404 - Invalid request method or path - ⚠️ 405 - Rate limit exceeded - ⚠️ 413 - Theme or prompt too long - ⚠️ 429 - Insufficient credits - ⚠️ 430 - Your call frequency is too high. Please try again later. - ⚠️ 455 - System maintenance - ❌ 500 - Server error example: 200 enum: - 200 - 400 - 401 - 404 - 405 - 413 - 429 - 430 - 455 - 500 msg: allOf: - type: string description: Error message when code != 200 example: success data: allOf: - type: integer description: >- The number of credits currently available in your account. - Each API operation consumes a specific number of credits depending on the feature. - Additional credits can be purchased from your account dashboard. example: 100 refIdentifier: '#/components/schemas/ApiResponse' examples: example: value: code: 200 msg: success data: 100 description: Request successful '500': _mintlify/placeholder: schemaArray: - type: any description: Server error examples: {} description: Server error deprecated: false type: path components: schemas: {} ``` -------------------------------- ### Create Music Video API Source: https://docs.api.box/suno-api/quickstart Convert audio tracks to visualized music videos. ```APIDOC ## POST /suno-api/create-music-video ### Description Convert audio tracks to visualized music videos. ### Method POST ### Endpoint /suno-api/create-music-video ### Parameters #### Request Body - **audio_url** (string) - Required - The URL of the audio track. - **prompt** (string) - Optional - A description for the video visuals. ### Request Example ```json { "audio_url": "https://api.box/audio/my_song.mp3", "prompt": "Abstract colorful animations syncing to the music" } ``` ### Response #### Success Response (200) - **video_url** (string) - The URL of the generated music video. #### Response Example ```json { "video_url": "https://api.box/videos/my_music_video.mp4" } ``` ``` -------------------------------- ### Generation Modes Source: https://docs.api.box/suno-api/quickstart Details on the generation modes available, including simple and advanced options, and parameters controlling their behavior. ```APIDOC ## Generation Modes ### Parameters #### Query Parameters - **customMode** (boolean) - Required - Controls parameter complexity. `false` for simple mode (prompt only), `true` for advanced mode (requires style and title). - **instrumental** (boolean) - Required - Determines if the music should be instrumental. `true` for instrumental only, `false` for music with vocals/lyrics. ``` -------------------------------- ### GET /api/v1/generate/credit Source: https://docs.api.box/suno-api/get-remaining-credits Retrieves the current balance of available credits for your account. This endpoint returns the number of credits remaining and a status message. ```APIDOC ## GET /api/v1/generate/credit ### Description Retrieve the current balance of available credits for your account. ### Method GET ### Endpoint /api/v1/generate/credit ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **code** (integer) - Status code indicating the result of the request (e.g., 200 for success, 4xx for client errors, 5xx for server errors). - **msg** (string) - A message describing the result of the request. "success" for successful requests. - **data** (integer) - The number of credits currently available in your account. #### Response Example ```json { "code": 200, "msg": "success", "data": 100 } ``` #### Error Response (4xx/5xx) - **code** (integer) - Status code indicating the error. - **msg** (string) - An error message describing the issue. #### Error Response Example ```json { "code": 401, "msg": "Unauthorized access" } ``` ``` -------------------------------- ### API Request Example (JSON) Source: https://docs.api.box/suno-api/generate-music An example of a complete API request payload in JSON format, demonstrating the usage of various parameters for music generation. ```json { "prompt": "A calm and relaxing piano track with soft melodies", "style": "Classical", "title": "Peaceful Piano Meditation", "customMode": true, "instrumental": true, "model": "V3_5", "negativeTags": "Heavy Metal, Upbeat Drums", "callBackUrl": "https://api.example.com/callback", "vocalGender": "m", "styleWeight": 0.65, "weirdnessConstraint": 0.65, "audioWeight": 0.65 } ``` -------------------------------- ### Python Suno API Client for Music Generation and Management Source: https://docs.api.box/suno-api/quickstart This Python code defines a client for the Suno API, enabling users to generate music with specified parameters, wait for task completion, check task status, extend existing music tracks, and retrieve remaining credit information. It handles API requests, response parsing, and error management. Dependencies include the 'requests' library for HTTP calls and 'time' for managing wait times. ```python import requests import time class SunoAPI: def __init__(self, api_key, base_url='https://suno-api.io'): self.api_key = api_key self.base_url = base_url self.headers = {'Authorization': f'Bearer {self.api_key}'} def generate_music(self, prompt, customMode=False, instrumental=False, model='V4_5', style='', title='', tags='', duration=10, continueAt=0): data = { 'prompt': prompt, 'customMode': customMode, 'instrumental': instrumental, 'model': model, 'style': style, 'title': title, 'tags': tags, 'duration': duration, 'continueAt': continueAt } response = requests.post(f'{self.base_url}/generate/create', headers=self.headers, json=data) result = response.json() if result['code'] != 200: raise Exception(f"Add instrumental failed: {result['msg']}") return result['data']['taskId'] def extend_music(self, audio_id, defaultParamFlag=False, prompt='', style='', title='', tags='', duration=10, continueAt=0, model='V4_5'): data = { 'audioId': audio_id, 'defaultParamFlag': defaultParamFlag, 'prompt': prompt, 'style': style, 'title': title, 'tags': tags, 'duration': duration, 'continueAt': continueAt, 'model': model } response = requests.post(f'{self.base_url}/generate/extend', headers=self.headers, json=data) result = response.json() if result['code'] != 200: raise Exception(f"Add instrumental failed: {result['msg']}") 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) if status['status'] == 'SUCCESS': return status['response'] elif 'FAILED' in status['status'] or status['status'] == 'SENSITIVE_WORD_ERROR': error_msg = status.get('errorMessage', status['status']) raise Exception(f"Generation failed: {error_msg}") time.sleep(10) # Wait 10 seconds raise Exception('Generation timeout') def get_task_status(self, task_id): response = requests.get(f'{self.base_url}/generate/record-info?taskId={task_id}', headers={'Authorization': f'Bearer {self.api_key}'}) return response.json()['data'] def get_remaining_credits(self): response = requests.get(f'{self.base_url}/generate/credit', headers={'Authorization': f'Bearer {self.api_key}'}) return response.json()['data']['credits'] # Usage example def main(): api = SunoAPI('YOUR_API_KEY') try: # Check remaining credits credits = api.get_remaining_credits() print(f'Remaining credits: {credits}') # 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 guitar, 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 generation successful!') print('Generated tracks:') for i, track in enumerate(result['data']): print(f"Track {i + 1}:") print(f" Title: {track['title']}") print(f" Audio URL: {track['audio_url']}") print(f" Duration: {track['duration']} seconds") print(f" Tags: {track['tags']}") # Extend the first track first_track = result['data'][0] print('\nExtending 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 extension successful!') print(f"Extended track URL: {extend_result['data'][0]['audio_url']}") except Exception as error: print(f'Error: {error}') if __name__ == '__main__': main() ``` -------------------------------- ### API Response Example (JSON) Source: https://docs.api.box/suno-api/add-vocals This JSON example illustrates a successful API response (status code 200). It includes a success message and a task ID for tracking the status of the generated audio task. ```json { "code": 200, "msg": "success", "data": { "taskId": "5c79****be8e" } } ``` -------------------------------- ### Extend Music API Source: https://docs.api.box/suno-api/quickstart Seamlessly extend existing music tracks using AI. ```APIDOC ## POST /suno-api/extend-music ### Description Seamlessly extend existing music tracks with AI-generated content. ### Method POST ### Endpoint /suno-api/extend-music ### Parameters #### Request Body - **music_id** (string) - Required - The ID of the music track to extend. - **duration_seconds** (integer) - Required - The desired duration in seconds to extend the track by. ### Request Example ```json { "music_id": "music_abcdef12345", "duration_seconds": 30 } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the extended music job. - **status** (string) - The current status of the music extension job. #### Response Example ```json { "id": "job_67890fghij", "status": "pending" } ``` ``` -------------------------------- ### API Response Structure Example Source: https://docs.api.box/suno-api/get-lyrics-generation-details This example demonstrates a successful API response for a 'LYRICS' task. It includes task ID, parameters, and the generated lyrical content. The structure includes fields like 'code', 'msg', 'data', 'status', 'type', 'errorCode', and 'errorMessage'. ```json { "code": 200, "msg": "success", "data": { "taskId": "11dc****8b0f", "param": "{\"prompt\": \"A song about peaceful night in the city\"}", "response": { "taskId": "11dc****8b0f", "data": [ { "text": "[Verse]\n我穿越城市黑暗夜\n心中燃烧梦想的烈火", "title": "钢铁侠", "status": "complete", "errorMessage": "" } ], "status": "SUCCESS", "type": "LYRICS", "errorCode": null, "errorMessage": null } } } ```