> ## Documentation Index
> Fetch the complete documentation index at: https://docs.api.box/llms.txt
> Use this file to discover all available pages before exploring further.

# Lyrics Generation Callbacks

> When lyrics generation tasks are completed, the system will send results to your provided callback URL via POST request

When you submit a task to the lyrics generation API, you can use the `callBackUrl` parameter to set a callback URL. When the task is completed, the system will automatically push the results to your specified address.

## Callback Mechanism Overview

<Info>
  The callback mechanism eliminates the need to poll the API for task status. The system will proactively push task completion results to your server.
</Info>

### Callback Timing

The system will send callback notifications in the following situations:

* Lyrics generation completed (`complete` stage)
* Lyrics generation task failed
* Error occurred during task processing

<Note>
  Unlike music generation, lyrics generation has only one callback stage: `complete` (generation finished)
</Note>

### Callback Method

* **HTTP Method**: POST
* **Content Type**: application/json
* **Timeout**: 15 seconds

## Callback Request Format

When the task is completed, the system will send a POST request to your `callBackUrl` in the following format:

<CodeGroup>
  ```json Lyrics Generation Complete Callback theme={null}
  {
    "code": 200,
    "msg": "All generated successfully.",
    "data": {
      "callbackType": "complete",
      "taskId": "11dc****8b0f",
      "data": [
        {
          "text": "[Verse]\nI cross the city's darkest night\nWith burning dreams inside my heart",
          "title": "Iron Man",
          "status": "complete",
          "errorMessage": ""
        },
        {
          "text": "[Verse]\nThe wind is calling out my name\nSteel armor gleaming in the light",
          "title": "Iron Man",
          "status": "complete",
          "errorMessage": ""
        }
      ]
    }
  }
  ```

  ```json Lyrics Generation Failed Callback theme={null}
  {
    "code": 400,
    "msg": "Failed to generate lyrics, containing sensitive content",
    "data": {
      "callbackType": "failed",
      "taskId": "11dc****8b0f",
      "data": null
    }
  }
  ```
</CodeGroup>

## Status Code Description

<ParamField path="code" type="integer" required>
  Callback status code indicating task processing result:

  | Status Code | Description                                                |
  | ----------- | ---------------------------------------------------------- |
  | 200         | Success - Lyrics generation completed                      |
  | 400         | Bad Request - Parameter error or content violation         |
  | 401         | Unauthorized - Invalid API key                             |
  | 413         | Content Too Long - Prompt exceeds limit                    |
  | 429         | Insufficient Credits - Account credit balance insufficient |
  | 500         | Server Error - Please retry later                          |
</ParamField>

<ParamField path="msg" type="string" required>
  Status message providing detailed status description
</ParamField>

<ParamField path="data.callbackType" type="string" required>
  Callback type, fixed as `complete` for lyrics generation
</ParamField>

<ParamField path="data.taskId" type="string" required>
  Task ID, consistent with the taskId returned when you submitted the task
</ParamField>

<ParamField path="data.data" type="array" required>
  Generated lyrics list
</ParamField>

<ParamField path="data.data[].text" type="string">
  Lyrics content with verse/chorus structure
</ParamField>

<ParamField path="data.data[].title" type="string">
  Lyrics title
</ParamField>

<ParamField path="data.data[].status" type="string">
  Generation status: `complete` or `failed`
</ParamField>

<ParamField path="data.data[].errorMessage" type="string">
  Error message, valid when status is `failed`
</ParamField>

## Callback Reception Examples

Here are example codes for receiving callbacks in various popular programming languages:

<Tabs>
  <Tab title="Node.js">
    ```javascript theme={null}
    const express = require('express');
    const app = express();

    app.use(express.json());

    app.post('/lyrics-callback', (req, res) => {
      const { code, msg, data } = req.body;
      
      console.log('Received lyrics generation callback:', {
        taskId: data.taskId,
        callbackType: data.callbackType,
        status: code,
        message: msg
      });
      
      if (code === 200 && data.callbackType === 'complete') {
        // Lyrics generation successful
        console.log(`Generated ${data.data.length} lyrics variants:`);
        
        data.data.forEach((lyrics, index) => {
          if (lyrics.status === 'complete') {
            console.log(`\nLyrics ${index + 1}:`);
            console.log(`Title: ${lyrics.title}`);
            console.log(`Content:\n${lyrics.text}`);
            
            // Process lyrics data
            // Can save to database, format for display, etc.
            saveLyricsToDatabase(lyrics);
          } else {
            console.log(`Lyrics ${index + 1} failed: ${lyrics.errorMessage}`);
          }
        });
        
      } else {
        // Task failed
        console.log('Lyrics generation failed:', msg);
        
        // Handle failure cases...
        if (code === 400) {
          console.log('Parameter error or content violation');
        } 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' });
    });

    function saveLyricsToDatabase(lyrics) {
      // Example function to save lyrics to database
      console.log(`Saving lyrics: ${lyrics.title}`);
      // Your database logic here
    }

    app.listen(3000, () => {
      console.log('Lyrics callback server running on port 3000');
    });
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    from flask import Flask, request, jsonify
    import json

    app = Flask(__name__)

    @app.route('/lyrics-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('taskId')
        callback_type = callback_data.get('callbackType')
        lyrics_data = callback_data.get('data', [])
        
        print(f"Received lyrics generation callback: {task_id}, Type: {callback_type}, Status: {code}")
        
        if code == 200 and callback_type == 'complete':
            # Lyrics generation successful
            print(f"Generated {len(lyrics_data)} lyrics variants:")
            
            for i, lyrics in enumerate(lyrics_data):
                if lyrics.get('status') == 'complete':
                    print(f"\nLyrics {i + 1}:")
                    print(f"Title: {lyrics.get('title')}")
                    print(f"Content:\n{lyrics.get('text')}")
                    
                    # Process lyrics data
                    # Can save to file, database, etc.
                    save_lyrics_to_file(lyrics, task_id, i + 1)
                else:
                    print(f"Lyrics {i + 1} failed: {lyrics.get('errorMessage')}")
                    
        else:
            # Task failed
            print(f"Lyrics generation failed: {msg}")
            
            # Handle failure cases...
            if code == 400:
                print("Parameter error or content violation")
            elif code == 429:
                print("Insufficient credits")
            elif code == 500:
                print("Server internal error")
        
        # Return 200 status code to confirm callback received
        return jsonify({'status': 'received'}), 200

    def save_lyrics_to_file(lyrics, task_id, index):
        """Save lyrics to a text file"""
        try:
            filename = f"lyrics_{task_id}_{index}.txt"
            with open(filename, "w", encoding="utf-8") as f:
                f.write(f"Title: {lyrics.get('title')}\n\n")
                f.write(lyrics.get('text'))
            print(f"Lyrics saved as {filename}")
        except Exception as e:
            print(f"Failed to save lyrics: {e}")

    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=3000)
    ```
  </Tab>

  <Tab title="PHP">
    ```php theme={null}
    <?php
    header('Content-Type: application/json');

    // Get POST data
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

    $code = $data['code'] ?? null;
    $msg = $data['msg'] ?? '';
    $callbackData = $data['data'] ?? [];
    $taskId = $callbackData['taskId'] ?? '';
    $callbackType = $callbackData['callbackType'] ?? '';
    $lyricsData = $callbackData['data'] ?? [];

    error_log("Received lyrics generation callback: $taskId, Type: $callbackType, Status: $code");

    if ($code === 200 && $callbackType === 'complete') {
        // Lyrics generation successful
        error_log("Generated " . count($lyricsData) . " lyrics variants:");
        
        foreach ($lyricsData as $index => $lyrics) {
            if (($lyrics['status'] ?? '') === 'complete') {
                $title = $lyrics['title'] ?? '';
                $text = $lyrics['text'] ?? '';
                
                error_log("Lyrics " . ($index + 1) . ":");
                error_log("Title: $title");
                error_log("Content: $text");
                
                // Process lyrics data
                // Can save to file, database, etc.
                saveLyricsToFile($lyrics, $taskId, $index + 1);
            } else {
                $errorMsg = $lyrics['errorMessage'] ?? '';
                error_log("Lyrics " . ($index + 1) . " failed: $errorMsg");
            }
        }
        
    } else {
        // Task failed
        error_log("Lyrics generation failed: $msg");
        
        // Handle failure cases...
        if ($code === 400) {
            error_log("Parameter error or content violation");
        } elseif ($code === 429) {
            error_log("Insufficient credits");
        } elseif ($code === 500) {
            error_log("Server internal error");
        }
    }

    function saveLyricsToFile($lyrics, $taskId, $index) {
        try {
            $title = $lyrics['title'] ?? '';
            $text = $lyrics['text'] ?? '';
            $filename = "lyrics_{$taskId}_{$index}.txt";
            
            $content = "Title: $title\n\n$text";
            file_put_contents($filename, $content);
            error_log("Lyrics saved as $filename");
        } catch (Exception $e) {
            error_log("Failed to save lyrics: " . $e->getMessage());
        }
    }

    // Return 200 status code to confirm callback received
    http_response_code(200);
    echo json_encode(['status' => 'received']);
    ?>
    ```
  </Tab>
</Tabs>

## Best Practices

<Tip>
  ### Lyrics Processing Recommendations

  1. **Content Filtering**: Implement content filtering to ensure lyrics meet your platform's guidelines
  2. **Format Preservation**: Maintain the verse/chorus structure when processing lyrics
  3. **Version Management**: Keep track of different lyrics variants for the same prompt
  4. **Metadata Storage**: Store lyrics along with relevant metadata (title, theme, style)
  5. **Text Processing**: Consider text processing for formatting, spell checking, or translation
  6. **Copyright Compliance**: Ensure generated lyrics comply with copyright regulations
</Tip>

<Warning>
  ### Lyrics-Specific Considerations

  * Lyrics may contain creative variations that require human review
  * Generated content should be checked for appropriateness before publication
  * Multiple variants allow for selection of the best option
  * Lyrics generation is typically faster than music generation
  * Content moderation is important for user-generated lyrics prompts
</Warning>

## Troubleshooting

Common issues specific to lyrics generation callbacks:

<AccordionGroup>
  <Accordion title="Content Quality Issues">
    * Review the prompt for clarity and specificity
    * Check if the generated lyrics match the intended theme
    * Verify that lyrics follow a logical song structure
    * Consider regenerating if quality doesn't meet expectations
  </Accordion>

  <Accordion title="Language and Style Problems">
    * Ensure the prompt clearly specifies the desired language
    * Check for style consistency across verses and choruses
    * Verify that the tone matches the intended mood
    * Consider more specific prompts for better style control
  </Accordion>

  <Accordion title="Content Moderation">
    * Implement content filtering for generated lyrics
    * Check for potentially inappropriate content
    * Verify compliance with platform guidelines
    * Consider human review for sensitive topics
  </Accordion>
</AccordionGroup>

## Alternative Solutions

If you cannot use the callback mechanism, you can also use polling:

<Card title="Poll Lyrics Results" icon="radar" href="/suno-api/get-lyrics-generation-details">
  Use the Get Lyrics Generation Details interface to regularly query task status. Recommend querying every 15 seconds for lyrics.
</Card>
