Download the voting report vote.AttachedVote.download

Choose a tool for developing with an AI agent:

  • use Alaio Vibecode to build an app for Bitrix24 from a task description without knowing any programming language. The agent writes the code and deploys the app to a server, with no manual hosting setup
  • use the MCP server to develop a REST API integration in your own project. The agent refers to the official REST documentation

Scope: vote

Who can execute the method: user with read access permission for voting

The method vote.AttachedVote.download generates and provides a downloadable report for the vote in the specified format.

Method Features

Attention! This method is an exception to the general rule of working with the REST API. Unlike other methods, it returns not a JSON object, but the actual content of the file with HTTP headers that initiate the download in the browser.

Due to this, the standard function BX24.callMethod() cannot process the response and will throw an error. To work with this method, a direct HTTP request must be made, as shown in the JS code example.

Method Parameters

There are three options for calling the method.

1. By the ID of the attached vote

Required parameters are marked with *

Name
type

Description

attachId*
integer

The ID of the attached vote, which can be obtained using the methods vote.AttachedVote.get or vote.AttachedVote.getMany

2. By the entity with the vote

Required parameters are marked with *

Name
type

Description

moduleId*
string

The module ID, possible values:

  • Im for a vote in chat,
  • blog for a vote in the feed

entityType*
string

The object type, possible values:

  • Bitrix\\Vote\\Attachment\\ImMessageConnector for a vote in chat,
  • Bitrix\\Vote\\Attachment\\BlogPostConnector for a vote in the feed

entityId*
integer

The ID of the entity, possible values:

  • id of the chat message with the vote, which can be obtained using the method vote.Integration.Im.send,
  • id of the post with the vote in the feed, which can be obtained using the method log.blogpost.get

3. By the signed ID

Required parameters are marked with *

Name
type

Description

signedAttachId*
string

The signed ID of the attachment, which can be obtained using the method vote.AttachedVote.get, response parameter signedAttachId

Code Examples

How to Use Examples in Documentation

curl -X POST \
        -L \
        -o **put_file_name**.xls \
        -H "Content-Type: application/json" \
        -d '{"attachId":**put_attach_id**}' \
        "https://**put_your_bitrix24_address**/rest/**put_your_user_id_here**/**put_your_webhook_here**/vote.AttachedVote.download"
        
curl -X POST \
        -L \
        -o **put_file_name**.xls \
        -H "Content-Type: application/json" \
        -d '{"attachId":**put_attach_id**, "auth": "**put_access_token_here**"}' \
        "https://**put_your_bitrix24_address**/rest/vote.AttachedVote.download"
        
function downloadVoteReportById(attachId)
        {
            // 1. Get authorization data from the BX24 library
            const auth = BX24.getAuth();
            if (!auth)
            {
                return;
            }
        
            // 2. Form the URL for the direct request to the REST API
            const restUrl = new URL(`https://${auth.domain}/rest/vote.AttachedVote.download`);
            restUrl.searchParams.append('auth', auth.access_token);
            restUrl.searchParams.append('attachId', attachId);
        
            console.log(`Download request: ${restUrl}`);
        
            // 3. Execute the request and process the response as a binary file (blob)
            fetch(restUrl)
                .then(response => {
                    if (!response.ok)
                    {
                        // If the request failed, try to process the standard JSON error from Bitrix24
                        return response.json().catch(() => {
                            // If the response body is not JSON, throw a general network error
                            throw new Error(`Network error: ${response.status} ${response.statusText}`);
                        }).then(errorData => {
                            // If able to parse the JSON error
                            throw new Error(`API error: ${errorData.error_description || 'Unknown error'}`);
                        });
                    }
                    // On success, get the data as a binary object
                    return response.blob();
                })
                .then(blob => {
                    // 4. Create an "invisible" link and initiate the download in the browser
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.style.display = 'none';
                    a.href = url;
                    
                    // Set the file name that the user will see
                    a.download = `vote_report_${attachId}.${fileType}`;
                    
                    document.body.appendChild(a);
                    a.click();
                    
                    // Clean up temporary data
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                })
                .catch(error => {
                    console.error('Error downloading the report:', error);
                    alert(`Failed to download the report: ${error.message}`);
                });
        }
        
<?php
        // This file usually contains constants for connection or autoloader settings
        require_once('src/crest.php');
        
        /**
        * Function to download the report using a direct HTTP request,
        * since the method vote.AttachedVote.download returns not JSON, but the content of the file.
        *
        * @param array $params - Parameters for the REST method (e.g., ['attachId' => 1])
        */
        function downloadVoteReport(array $params, string $saveToFile): bool
        {
            // 1. Get authorization settings. 
            // CRest::getAppSettings() will return either data for OAuth or for webhook.
            // In crest.php, change the access modifier to public for this method
            $authData = CRest::getAppSettings();
        
            if (empty($authData)) {
                echo "Error: failed to get authorization settings. Check crest.php/settings.php.\n";
                return false;
            }
        
            // 2. Define the URL for the request
            if (!empty($authData['is_web_hook']) && $authData['is_web_hook'] === 'Y') {
                // Case with webhook
                $url = $authData['client_endpoint'] . 'vote.AttachedVote.download';
                $queryParams = $params;
            } else {
                // Case with OAuth application
                $url = $authData['client_endpoint'] . 'vote.AttachedVote.download';
                $params['auth'] = $authData['access_token'];
                $queryParams = $params;
            }
        
            $url .= '?' . http_build_query($queryParams);
            echo "Request URL: " . $url . "\n";
        
            // 3. Execute the request using cURL
            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL => $url,
                CURLOPT_HEADER => false,        // Do not include headers in the response
                CURLOPT_RETURNTRANSFER => true, // Return the response as a string, not output to the browser
                CURLOPT_USERAGENT => 'CRest based downloader',
                CURLOPT_FOLLOWLOCATION => true, // Follow redirects
            ]);
        
            $response = curl_exec($curl);
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            $error = curl_error($curl);
            curl_close($curl);
        
            // 4. Check the result and save the file
            if ($error) {
                echo "cURL error: " . $error . "\n";
                return false;
            }
        
            if ($httpCode >= 400) {
                echo "Server returned HTTP error " . $httpCode . ".\n";
                // Attempt to decode the error if it's in JSON format
                $errorData = json_decode($response, true);
                if ($errorData && isset($errorData['error_description'])) {
                    echo "Error description: " . $errorData['error_description'] . "\n";
                } else {
                    echo "Response body: " . $response . "\n";
                }
                return false;
            }
            
            // If all is well, save the response to a file
            if (file_put_contents($saveToFile, $response)) {
                echo "File successfully saved to: " . $saveToFile . "\n";
                return true;
            } else {
                echo "Failed to save file to: " . $saveToFile . "\n";
                return false;
            }
        }
        
        
        // --- Example usage ---
        
        $attachId = 1;
        $fileType = 'xls';
        $fileName = "vote_report_{$attachId}.{$fileType}";
        
        $result = downloadVoteReport(
            [
                'attachId' => $attachId,
            ],
            $fileName
        );
        
        if ($result) {
            echo "Task completed.\n";
        } else {
            echo "Errors occurred during execution.\n";
        }
        

Response Handling

HTTP status: 200 OK

In case of successful execution, the server returns not a JSON object, but the actual content of the file with HTTP headers that initiate the download in the browser Content-Disposition: attachment.

Error Handling

HTTP status: 4xx

{
            "error": "ATTACH_NOT_FOUND",
            "error_description": "Attach not found"
        }
        

Name
type

Description

error
string

String error code. It consists of digits, Latin letters, and underscores. It may arrive empty — in that case only error_description shows the reason

error_description
string

Error message for the developer. Do not show it to the end user without processing

Possible Error Codes

Code

Description

ATTACH_NOT_FOUND

Vote not found

ATTACH_READ_ACCESS_DENIED

No permission to participate in the vote

Statuses and System Error Codes

HTTP Status: 4xx, 5xx

The errors described below are returned by the REST API itself, not by the logic of a specific method. They can arrive in response to any method.

Status

Code
Error Message

Description

500

INTERNAL_SERVER_ERROR
Internal server error

An internal server error has occurred. Retry the call, and if the error persists, contact the server administrator or Bitrix24 technical support

500

ERROR_UNEXPECTED_ANSWER
Server returned an unexpected response

The server returned an unexpected response. Retry the call, and if the error persists, contact the server administrator or Bitrix24 technical support

503

QUERY_LIMIT_EXCEEDED
Too many requests

The request intensity limit has been exceeded

429

OPERATION_TIME_LIMIT
Method is blocked due to operation time limit

The method is blocked because the request resource intensity limit has been exceeded. The block is lifted automatically once the accumulated execution time of the method no longer exceeds the limit

401

NO_AUTH_FOUND
Wrong authorization data

The request contains no authorization data: neither an access token nor a webhook code was passed

401

INVALID_REQUEST
Https required

Methods are called over the HTTPS protocol only

401

OVERLOAD_LIMIT
REST API is blocked due to overload

The REST API is blocked due to overload. This is a manual individual block. To have it lifted, contact Bitrix24 technical support

401

ACCESS_DENIED
REST is available only on commercial plans

REST API access is not active for this account. In Bitrix24 Cloud, check the current plan or trial status: Vibe+ plans include REST API access, while Essentials plans do not. A webhook receives a different error message — REST is available only by subscription

401

INVALID_CREDENTIALS
Invalid request credentials

No active webhook with the specified user identifier and secret code was found

404

ERROR_METHOD_NOT_FOUND
Method not found!

No method with this name was found. The name is misspelled, the method does not exist in the REST API, or it is unavailable without the required scope

401

insufficient_scope
The request requires higher privileges than provided by the webhook token

The request requires broader permissions than the token has: for a webhook these are the permissions granted to it, for an application it is the scope. For an application, the error message ends with provided by the access token

401

expired_token
The access token provided has expired

The access token has expired

401

user_access_error
The user does not have access to the application

The application is installed, but the Bitrix24 administrator has granted access to it only to specific users

403

PORTAL_DELETED
Portal was deleted

The public part of the site is closed. To open it on an on-premise installation, disable the "Temporary closure of the public part of the site" option. Path to the setting: Desktop > Settings > Product Settings > Module Settings > Main Module > Temporary closure of the public part of the site

Continue Learning