Получить список документов crm.documentgenerator.document.list

Выберите инструмент для разработки с AI-агентом:

  • используйте Битрикс24 Вайбкод, чтобы создать приложение для Битрикс24 по описанию задачи без знания языков программирования. Агент напишет код и разместит приложение на сервере без ручной настройки хостинга
  • используйте MCP-сервер, чтобы разрабатывать интеграцию через REST API в своем проекте. Агент будет обращаться к официальной REST-документации

Scope: crm

Кто может выполнять метод: пользователь с правом "просмотра" документов генератора документов

Метод crm.documentgenerator.document.list возвращает список документов по фильтру.

Параметры метода

Обязательные параметры отмечены *

Название
тип

Описание

select
string[]

Список полей, которые должны быть заполнены у документов в выборке.

При выборке можно использовать:

  • '*' — для выборки всех стандартных полей документа
  • явный список полей, например ['id','title','number','entityId','createTime']

Список полей смотрите в разделе Тип document.

По умолчанию используется ['*']

filter
object

Объект формата:

{
    field_1: value_1,
    field_2: value_2,
    ...,
    field_n: value_n
}

где:

  • field_n — название поля для фильтрации
  • value_n — значение фильтра

К ключам field_n можно добавлять префиксы:

  • >= — больше либо равно
  • > — больше
  • <= — меньше либо равно
  • < — меньше
  • @ — IN, в значении передается массив
  • !@ — NOT IN, в значении передается массив
  • = — равно (по умолчанию)
  • != или ! — не равно

Список доступных полей для фильтрации смотрите в разделе Тип document.

order
object

Объект формата:

{
    field_1: value_1,
    field_2: value_2,
    ...,
    field_n: value_n
}

где:

  • field_n — название поля сортировки
  • value_n — направление сортировки: ASC или DESC

Список полей для сортировки смотрите в разделе Тип document.

Пример: {"id":"DESC","createTime":"ASC"}

start
integer

Параметр постраничной навигации.

Размер страницы фиксирован: 50 записей.

Формула для получения N-й страницы:
start = (N - 1) * 50

Подробнее в статье Особенности списочных методов

Примеры кода

Как использовать примеры в документации

Пример получения списка документов, где:

  • выбираются поля id, title, number, entityId, createTime
  • сортировка по id по убыванию
  • фильтр по entityTypeId = 2 и entityId = 101
  • стартовое смещение — 0
curl -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"select":["id","title","number","entityId","createTime"],"order":{"id":"desc"},"filter":{"entityTypeId":2,"entityId":101},"start":0}' \
https://**put_your_bitrix24_address**/rest/**put_your_user_id_here**/**put_your_webhook_here**/crm.documentgenerator.document.list
curl -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"select":["id","title","number","entityId","createTime"],"order":{"id":"desc"},"filter":{"entityTypeId":2,"entityId":101},"start":0,"auth":"**put_access_token_here**"}' \
https://**put_your_bitrix24_address**/rest/crm.documentgenerator.document.list
// This snippet is an ES module: top-level await requires type="module" or a bundler.
// $b24 is an already-initialized SDK instance (see the SDK "Get started" guide).
import { Text } from '@bitrix24/b24jssdk'
import type { B24Frame, ISODate } from '@bitrix24/b24jssdk'

declare const $b24: B24Frame

type DocumentItem = {
  id: string
  title: string
  number: string
  templateId: string
  entityTypeId: string
  entityId: string
  fileId: string
  imageId: string
  pdfId: string
  createTime: ISODate
  updateTime: ISODate
  createdBy: string | null
  updatedBy: string | null
  values: Record<string, unknown> | null
  downloadUrl: string
  imageUrl: string
  pdfUrl: string
  stampsEnabled: boolean
  downloadUrlMachine: string
  pdfUrlMachine: string
  imageUrlMachine: string
}

// Shape of the payload returned in result (match the "response handling" section of the page)
type DocumentListResult = {
  documents: DocumentItem[]
}

try {
  // crm.documentgenerator.document.list returns a single page (max 50 records). For the whole result set
  // use a list helper: $b24.actions.v2.callList.make() returns every record as one
  // array, $b24.actions.v2.fetchList.make() yields them in chunks (async generator).
  // NOTE: the list helpers do not accept `order` (it is excluded from their params, so
  // passing it is a TS error) — keep this call.make + `start` variant when sort matters.
  const response = await $b24.actions.v2.call.make<DocumentListResult>({
    method: 'crm.documentgenerator.document.list',
    params: {
      select: ['id', 'title', 'number', 'entityId', 'createTime'],
      order: { id: 'desc' },
      filter: { entityTypeId: 2, entityId: 101 },
      start: 0,
    },
    requestId: Text.getUuidRfc4122()
  })

  // The payload is available only on a successful response
  if (!response.isSuccess) {
    console.error(response.getErrorMessages().join('; '))
  } else {
    const result = response.getData()!.result
    console.info('Documents on this page:', result.documents.length, result.documents)
  }
} catch (error) {
  // Thrown on transport or SDK failures (AjaxError, SdkError, etc.)
  console.error(error)
}
<!-- Load the SDK (UMD build); it is exposed as the global B24Js -->
<script src="https://unpkg.com/@bitrix24/b24jssdk@1/dist/umd/index.min.js"></script>
<script>
  async function fetchDocumentList() {
    try {
      // Initialize the SDK inside a Bitrix24 frame
      const $b24 = await B24Js.initializeB24Frame()

      // crm.documentgenerator.document.list returns a single page (max 50 records). For the whole result set
      // use a list helper: $b24.actions.v2.callList.make() returns every record as one
      // array, $b24.actions.v2.fetchList.make() yields them in chunks (async generator).
      // NOTE: the list helpers do not accept `order` (it is excluded from their params, so
      // passing it is a TS error) — keep this call.make + `start` variant when sort matters.
      const response = await $b24.actions.v2.call.make({
        method: 'crm.documentgenerator.document.list',
        params: {
          select: ['id', 'title', 'number', 'entityId', 'createTime'],
          order: { id: 'desc' },
          filter: { entityTypeId: 2, entityId: 101 },
          start: 0,
        },
        requestId: B24Js.Text.getUuidRfc4122()
      })

      // The payload is available only on a successful response
      if (!response.isSuccess) {
        console.error(response.getErrorMessages().join('; '))
        return
      }

      const result = response.getData().result
      console.info('Documents on this page:', result.documents.length, result.documents)
    } catch (error) {
      // Thrown on transport or SDK failures (AjaxError, SdkError, etc.)
      console.error(error)
    }
  }

  document.addEventListener('DOMContentLoaded', fetchDocumentList)
</script>
from b24pysdk.errors import BitrixAPIError, BitrixSDKException

try:
    bitrix_response = client.crm.documentgenerator.document.list(
        select=[
            "id",
            "title",
            "number",
            "entityId",
            "createTime",
        ],
        order={
            "id": "desc",
        },
        filter={
            "entityTypeId": 2,
            "entityId": 101,
        },
        start=0,
    ).response
    result = bitrix_response.result
    print(result)
except BitrixAPIError as error:
    print(
        "Ошибка Bitrix API",
        f"error: {error.error}",
        f"error_description: {error.error_description}",
        sep="\n",
    )
except BitrixSDKException as error:
    print(f"Ошибка Bitrix SDK: {error.message}")
except Exception as error:
    print(f"Непредвиденная ошибка: {error}")

Пример as_list

from b24pysdk.errors import BitrixAPIError, BitrixSDKException

try:
    bitrix_response = client.crm.documentgenerator.document.list(
        select=[
            "id",
            "title",
            "number",
            "entityId",
            "createTime",
        ],
        order={
            "id": "desc",
        },
        filter={
            "entityTypeId": 2,
            "entityId": 101,
        },
    ).as_list().response
    result = bitrix_response.result
    for item in result:
        print(item)
except BitrixAPIError as error:
    print(
        "Ошибка Bitrix API",
        f"error: {error.error}",
        f"error_description: {error.error_description}",
        sep="\n",
    )
except BitrixSDKException as error:
    print(f"Ошибка Bitrix SDK: {error.message}")
except Exception as error:
    print(f"Непредвиденная ошибка: {error}")

Пример as_list_fast

from b24pysdk.errors import BitrixAPIError, BitrixSDKException

try:
    bitrix_response = client.crm.documentgenerator.document.list(
        select=[
            "id",
            "title",
            "number",
            "entityId",
            "createTime",
        ],
        order={
            "id": "desc",
        },
        filter={
            "entityTypeId": 2,
            "entityId": 101,
        },
    ).as_list_fast(descending=True).response
    result = bitrix_response.result
    for item in result:
        print(item)
except BitrixAPIError as error:
    print(
        "Ошибка Bitrix API",
        f"error: {error.error}",
        f"error_description: {error.error_description}",
        sep="\n",
    )
except BitrixSDKException as error:
    print(f"Ошибка Bitrix SDK: {error.message}")
except Exception as error:
    print(f"Непредвиденная ошибка: {error}")
try {
    $response = $b24Service
        ->core
        ->call(
            'crm.documentgenerator.document.list',
            [
                'select' => ['id', 'title', 'number', 'entityId', 'createTime'],
                'order' => ['id' => 'desc'],
                'filter' => ['entityTypeId' => 2, 'entityId' => 101],
                'start' => 0,
            ]
        );

    $result = $response
        ->getResponseData()
        ->getResult();

    echo '<pre>';
    print_r($result);
    echo '</pre>';

} catch (Throwable $e) {
    error_log($e->getMessage());
    echo 'Error getting documents list: ' . $e->getMessage();
}
BX24.callMethod(
    'crm.documentgenerator.document.list',
    {
        select: ['id', 'title', 'number', 'entityId', 'createTime'],
        order: { id: 'desc' },
        filter: { entityTypeId: 2, entityId: 101 },
    },
    (result) => {
        if (result.error()) {
            console.error(result.error());
            return;
        }

        console.info(result.data());

        if (result.more()) {
            result.next();
        }
    },
);
require_once('crest.php');

$result = CRest::call(
    'crm.documentgenerator.document.list',
    [
        'select' => ['id', 'title', 'number', 'entityId', 'createTime'],
        'order' => ['id' => 'desc'],
        'filter' => ['entityTypeId' => 2, 'entityId' => 101],
        'start' => 0,
    ]
);

echo '<PRE>';
print_r($result);
echo '</PRE>';
// client и ctx уже созданы — см. раздел «SDK для Go»
res, err := client.Core().Call(ctx, "crm.documentgenerator.document.list", b24.Params{
	"select": []string{"id", "title", "number", "entityId", "createTime"},
	"order": b24.Params{
		"id": "desc",
	},
	"filter": b24.Params{
		"entityTypeId": 2,
		"entityId":     101,
	},
	"start": 0,
}, b24.WithIdempotent())
if err != nil {
	return fmt.Errorf("crm.documentgenerator.document.list: %w", err)
}

// Метод заворачивает ответ в объект с ключом "documents".
raw, ok := b24.Unwrap(res.Result, "documents")
if !ok {
	return fmt.Errorf("в ответе нет ключа documents")
}

var items []struct {
	ID         b24.ID `json:"id"`
	Title      string `json:"title"`
	Number     string `json:"number"`
	TemplateID b24.ID `json:"templateId"`
	FileID     b24.ID `json:"fileId"`
	ImageID    b24.ID `json:"imageId"`
}
if err := json.Unmarshal(raw, &items); err != nil {
	return fmt.Errorf("разбор ответа: %w", err)
}
for _, it := range items {
	fmt.Println(it.ID)
}

Обработка ответа

HTTP-статус: 200

{
    "result": {
        "documents": [
            {
                "id": "61",
                "title": "Демонстрационная реализация товара 2026-001",
                "number": "2026-002",
                "templateId": "39",
                "fileId": "283",
                "imageId": "285",
                "pdfId": "287",
                "createTime": "2026-03-20T13:51:45+03:00",
                "updateTime": "2026-03-20T14:42:38+03:00",
                "values": {
                    "_creationMethod": "rest",
                    "stampsEnabled": true
                },
                "createdBy": "577",
                "updatedBy": "577",
                "downloadUrl": "https://bitrix.bitrix24.ru/bitrix/services/main/ajax.php?action=crm.documentgenerator.document.download&SITE_ID=s1&id=61",
                "pdfUrl": "https://bitrix.bitrix24.ru/bitrix/services/main/ajax.php?action=crm.documentgenerator.document.getPdf&SITE_ID=s1&id=61",
                "imageUrl": "https://bitrix.bitrix24.ru/bitrix/services/main/ajax.php?action=crm.documentgenerator.document.getImage&SITE_ID=s1&id=61",
                "stampsEnabled": true,
                "entityId": "101",
                "entityTypeId": "2",
                "downloadUrlMachine": "https://bitrix.bitrix24.ru/rest/crm.documentgenerator.document.download.json?auth=***&token=***",
                "pdfUrlMachine": "https://bitrix.bitrix24.ru/rest/crm.documentgenerator.document.getPdf.json?auth=***&token=***",
                "imageUrlMachine": "https://bitrix.bitrix24.ru/rest/crm.documentgenerator.document.getImage.json?auth=***&token=***"
            },
            {
                "id": "59",
                "title": "Демонстрационная реализация товара 2026-001",
                "number": "2026-001",
                "templateId": "39",
                "fileId": "271",
                "imageId": "273",
                "pdfId": "275",
                "createTime": "2026-03-20T13:28:26+03:00",
                "updateTime": "2026-03-20T13:28:26+03:00",
                "values": {
                    "_creationMethod": "rest",
                    "stampsEnabled": true
                },
                "createdBy": "577",
                "updatedBy": null,
                "downloadUrl": "https://bitrix.bitrix24.ru/bitrix/services/main/ajax.php?action=crm.documentgenerator.document.download&SITE_ID=s1&id=59",
                "pdfUrl": "https://bitrix.bitrix24.ru/bitrix/services/main/ajax.php?action=crm.documentgenerator.document.getPdf&SITE_ID=s1&id=59",
                "imageUrl": "https://bitrix.bitrix24.ru/bitrix/services/main/ajax.php?action=crm.documentgenerator.document.getImage&SITE_ID=s1&id=59",
                "stampsEnabled": true,
                "entityId": "101",
                "entityTypeId": "2",
                "downloadUrlMachine": "https://bitrix.bitrix24.ru/rest/crm.documentgenerator.document.download.json?auth=***&token=***",
                "pdfUrlMachine": "https://bitrix.bitrix24.ru/rest/crm.documentgenerator.document.getPdf.json?auth=***&token=***",
                "imageUrlMachine": "https://bitrix.bitrix24.ru/rest/crm.documentgenerator.document.getImage.json?auth=***&token=***"
            }
        ]
    },
    "total": 4,
    "time": {
        "start": 1774009414,
        "finish": 1774009414.09833,
        "duration": 0.09833002090454102,
        "processing": 0,
        "date_start": "2026-03-20T15:23:34+03:00",
        "date_finish": "2026-03-20T15:23:34+03:00",
        "operating_reset_at": 1774010014,
        "operating": 0
    }
}

Возвращаемые данные

Название
тип

Описание

result
object

Корневой объект ответа. Содержит структуру result

total
integer

Общее количество документов, подходящих под фильтр

next
integer

Смещение для следующей страницы. Возвращается, если есть следующая страница

time
time

Информация о времени выполнения запроса

Тип result

Название
тип

Описание

documents
object[]

Массив документов. Структура элемента описана в типе document

Тип document

Состав полей зависит от параметра select.

Название
тип

Описание

id
string

Идентификатор документа

title
string

Название документа

number
string

Номер документа

templateId
integer | string

Идентификатор шаблона документа

entityTypeId
integer | string

Идентификатор типа CRM-объекта

entityId
integer | string

Идентификатор CRM-объекта

fileId
integer | string

Идентификатор DOCX-файла документа

imageId
integer | string

Идентификатор изображения документа

pdfId
integer | string

Идентификатор PDF-файла документа

createTime
datetime

Дата создания документа

updateTime
datetime

Дата обновления документа

createdBy
integer | string | null

Идентификатор пользователя, создавшего документ

updatedBy
integer | string | null

Идентификатор пользователя, обновившего документ

values
object | null

Значения полей документа

downloadUrl
string

Ссылка на скачивание документа

imageUrl
string

Ссылка на изображение документа

pdfUrl
string

Ссылка на PDF-документ

downloadUrlMachine
string

Ссылка на скачивание документа для машинного доступа

pdfUrlMachine
string

Ссылка на PDF-документ для машинного доступа

imageUrlMachine
string

Ссылка на изображение документа для машинного доступа

stampsEnabled
boolean

Признак подстановки печати и подписи

Обработка ошибок

HTTP-статус: 400

{
    "error": "ACCESS_DENIED",
    "error_description": "Access denied"
}

Название
тип

Описание

error
string

Строковый код ошибки. Состоит из цифр, латинских букв и знака подчеркивания. Может прийти пустым — тогда причину показывает только error_description

error_description
string

Текст ошибки для разработчика. Не показывайте его конечному пользователю без обработки

Возможные коды ошибок

Код

Описание

Значение

100

Unknown field definition ENTITY_TYPE_ID (ENTITY_TYPE_ID) for \Bitrix\DocumentGenerator\Model\Document Entity

В параметр select передано поле entityTypeId, которое не является прямым полем модели документа. Используйте select: ['*']

ACCESS_DENIED

Access denied

Недостаточно прав для чтения документов по выбранному фильтру CRM-объектов

Пустое значение

You do not have permissions to view documents

Недостаточно прав для просмотра документов генератора документов

Пустое значение

Module documentgenerator is not installed

Модуль documentgenerator недоступен

Статусы и коды системных ошибок

HTTP-статус: 4xx, 5xx

Описанные ниже ошибки возвращает сам REST API, а не логика конкретного метода. Они могут прийти в ответ на любой метод.

Статус

Код
Текст ошибки

Описание

500

INTERNAL_SERVER_ERROR
Internal server error

Возникла внутренняя ошибка сервера. Повторите вызов, а если ошибка сохраняется, обратитесь к администратору сервера или в техническую поддержку Битрикс24

500

ERROR_UNEXPECTED_ANSWER
Server returned an unexpected response

Сервер вернул неожиданный ответ. Повторите вызов, а если ошибка сохраняется, обратитесь к администратору сервера или в техническую поддержку Битрикс24

503

QUERY_LIMIT_EXCEEDED
Too many requests

Превышен лимит на интенсивность запросов

429

OPERATION_TIME_LIMIT
Method is blocked due to operation time limit

Метод заблокирован из-за превышения лимита на ресурсоемкость запросов. Блокировка снимается автоматически, когда накопленное время выполнения метода перестает превышать лимит

401

NO_AUTH_FOUND
Wrong authorization data

В запросе нет авторизационных данных: не передан ни access-токен, ни код вебхука

401

INVALID_REQUEST
Https required

Методы вызываются только по протоколу HTTPS

401

OVERLOAD_LIMIT
REST API is blocked due to overload

REST API заблокирован из-за перегрузки. Это ручная индивидуальная блокировка. Чтобы ее снять, обратитесь в техническую поддержку Битрикс24

401

ACCESS_DENIED
REST is available only on commercial plans

REST API доступен только на коммерческих тарифах. У вебхука текст ошибки другой — REST is available only by subscription

401

INVALID_CREDENTIALS
Invalid request credentials

Не найден активный вебхук с указанным идентификатором пользователя и секретным кодом

404

ERROR_METHOD_NOT_FOUND
Method not found!

Метод с таким именем не найден. Имя написано с ошибкой, метода нет в REST API или он недоступен без нужного скоупа

401

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

Запрос требует более широких прав, чем есть у токена: у вебхука это выданные ему права, у приложения — скоуп. У приложения текст ошибки заканчивается на provided by the access token

401

expired_token
The access token provided has expired

Срок действия access-токена истек

401

user_access_error
The user does not have access to the application

Приложение установлено, но администратор Битрикс24 открыл доступ к нему только конкретным пользователям

403

PORTAL_DELETED
Portal was deleted

Публичная часть сайта закрыта. Чтобы открыть ее на коробочной установке, отключите опцию «Временное закрытие публичной части сайта». Путь к настройке: Рабочий стол > Настройки > Настройки продукта > Настройки модулей > Главный модуль > Временное закрытие публичной части сайта

Продолжите изучение