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

# 4o image api generate 4 o image callbacks

# 4o Image Generation Callbacks

> When the 4o Image task is completed, the system will send the result to your provided callback URL via POST request

When you submit an image generation task to the 4o Image API, you can use the `callBackUrl` parameter to set a callback URL. The system will automatically push the results to your specified address when the task is completed.

## 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:

* 4o image generation task completed successfully
* 4o image generation task failed
* Errors occurred during task processing

### Callback Method

* **HTTP Method**: POST
* **Content Type**: application/json
* **Timeout Setting**: 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 Success Callback theme={null} theme={null}
  {
    "code": 200,
    "msg": "success",
    "data": {
      "taskId": "task12345",
      "info": {
        "result_urls": [
          "https://example.com/result/image1.png"
        ]
      }
    }
  }
  ```

  ```json Failure Callback theme={null} theme={null}
  {
    "code": 400,
    "msg": "Your content was flagged by OpenAI as violating content policies",
    "data": {
      "taskId": "task12345",
      "info": null
    }
  }
  ```
</CodeGroup>

## Status Code Description

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

  | Status Code | Description                                                                                                                                                                               |
  | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  | 200         | Success - Image generation completed successfully                                                                                                                                         |
  | 400         | Bad Request - Image content in filesUrl violates content policy, image size exceeds maximum limit, unable to process provided image file, content flagged by OpenAI as violating policies |
  | 451         | Download Failed - Unable to download image from the provided filesUrl                                                                                                                     |
  | 500         | Server Error - Please try again later, failed to get user token, failed to generate image, GPT 4O failed to edit the picture                                                              |
</ParamField>

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

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

<ParamField path="data.info" type="object">
  Image generation result information, returned on success
</ParamField>

<ParamField path="data.info.result_urls" type="array">
  List of generated image URLs, returned on success with accessible download links
</ParamField>

## Callback Reception Examples

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

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

    app.use(express.json());

    app.post('/4o-image-callback', (req, res) => {
      const { code, msg, data } = req.body;
      
      console.log('Received 4o image generation callback:', {
        taskId: data.taskId,
        status: code,
        message: msg
      });
      
      if (code === 200) {
        // Task completed successfully
        console.log('4o image generation completed');
        const resultUrls = data.info?.result_urls || [];
        
        console.log(`Generated ${resultUrls.length} images:`);
        resultUrls.forEach((url, index) => {
          console.log(`Image ${index + 1}: ${url}`);
        });
        
        // Process generated images
        // Can download images, save locally, etc.
        
      } else {
        // Task failed
        console.log('4o image generation failed:', msg);
        
        // Handle failure cases...
        if (code === 400) {
          console.log('Content policy violation or parameter error');
        } else if (code === 451) {
          console.log('Image download failed');
        } 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('Callback server running on port 3000');
    });
    ```
  </Tab>

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

    app = Flask(__name__)

    @app.route('/4o-image-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')
        info = callback_data.get('info')
        
        print(f"Received 4o image generation callback: {task_id}, status: {code}, message: {msg}")
        
        if code == 200:
            # Task completed successfully
            print("4o image generation completed")
            result_urls = info.get('result_urls', []) if info else []
            
            print(f"Generated {len(result_urls)} images:")
            for i, url in enumerate(result_urls):
                print(f"Image {i + 1}: {url}")
                
                # Download image example
                try:
                    response = requests.get(url)
                    if response.status_code == 200:
                        filename = f"4o_image_{task_id}_{i + 1}.png"
                        with open(filename, "wb") as f:
                            f.write(response.content)
                        print(f"Image saved as {filename}")
                except Exception as e:
                    print(f"Image download failed: {e}")
                    
        else:
            # Task failed
            print(f"4o image generation failed: {msg}")
            
            # Handle failure cases...
            if code == 400:
                print("Content policy violation or parameter error")
            elif code == 451:
                print("Image download failed")
            elif code == 500:
                print("Server internal error")
        
        # 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)
    ```
  </Tab>

  <Tab title="PHP">
    ```php theme={null} 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'] ?? '';
    $info = $callbackData['info'] ?? null;

    error_log("Received 4o image generation callback: $taskId, status: $code, message: $msg");

    if ($code === 200) {
        // Task completed successfully
        error_log("4o image generation completed");
        $resultUrls = $info['result_urls'] ?? [];
        
        error_log("Generated " . count($resultUrls) . " images:");
        foreach ($resultUrls as $index => $url) {
            error_log("Image " . ($index + 1) . ": $url");
            
            // Download image example
            try {
                $imageContent = file_get_contents($url);
                if ($imageContent !== false) {
                    $filename = "4o_image_{$taskId}_" . ($index + 1) . ".png";
                    file_put_contents($filename, $imageContent);
                    error_log("Image saved as $filename");
                }
            } catch (Exception $e) {
                error_log("Image download failed: " . $e->getMessage());
            }
        }
        
    } else {
        // Task failed
        error_log("4o image generation failed: $msg");
        
        // Handle failure cases...
        if ($code === 400) {
            error_log("Content policy violation or parameter error");
        } elseif ($code === 451) {
            error_log("Image download failed");
        } elseif ($code === 500) {
            error_log("Server internal error");
        }
    }

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

## Best Practices

<Tip>
  ### Callback URL Configuration Recommendations

  1. **Use HTTPS**: Ensure your callback URL uses HTTPS protocol for secure data transmission
  2. **Verify Source**: Verify the legitimacy of the request source in callback processing
  3. **Idempotent Processing**: The same taskId may receive multiple callbacks, ensure processing logic is idempotent
  4. **Quick Response**: Callback processing should return a 200 status code as quickly as possible to avoid timeout
  5. **Asynchronous Processing**: Complex business logic should be processed asynchronously to avoid blocking callback response
  6. **Image Processing**: Image download and processing should be done in asynchronous tasks to avoid blocking callback response
</Tip>

<Warning>
  ### Important Reminders

  * Callback URL must be a publicly accessible address
  * Server must respond within 15 seconds, otherwise it will be considered a timeout
  * If 3 consecutive retries fail, the system will stop sending callbacks
  * Please ensure the stability of callback processing logic to avoid callback failures due to exceptions
  * Generated image URLs may have time limits, recommend downloading and saving promptly
  * Pay attention to content policy compliance to avoid generation failures due to policy violations
</Warning>

## Troubleshooting

If you do not receive callback notifications, please check the following:

<AccordionGroup>
  <Accordion title="Network Connection Issues">
    * Confirm that the callback URL is accessible from the public network
    * Check firewall settings to ensure inbound requests are not blocked
    * Verify that domain name resolution is correct
  </Accordion>

  <Accordion title="Server Response Issues">
    * Ensure the server returns HTTP 200 status code within 15 seconds
    * Check server logs for error messages
    * Verify that the interface path and HTTP method are correct
  </Accordion>

  <Accordion title="Content Format Issues">
    * Confirm that the received POST request body is in JSON format
    * Check that Content-Type is application/json
    * Verify that JSON parsing is correct
  </Accordion>

  <Accordion title="Image Processing Issues">
    * Confirm that image URLs are accessible
    * Check image download permissions and network connections
    * Verify image save paths and permissions
    * Note whether image content complies with content policies
  </Accordion>
</AccordionGroup>

## Alternative Solution

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

<Card title="Poll Query Results" icon="radar" href="/4o-image-api/get-4-o-image-details">
  Use the get 4o image details endpoint to regularly query task status. We recommend querying every 30 seconds.
</Card>

***

> To find navigation and other pages in this documentation, fetch the llms.txt file at: [https://docs.apikley.ru/llms.txt](https://docs.apikley.ru/llms.txt)

> Rate limits and quotas are enforced by Apikley and may differ from upstream providers.
