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

# Добавление изображений в сессию через API

> Прикрепите к завершённой KYC-сессии в Didit дополнительное изображение или PDF к результату верификации личности или подтверждения адреса.

Промпт API: добавление изображений в сессию
Скопировать промпт в буфер обмена

<pre>
  \`Attach an extra image or PDF to a finished Didit User Verification (KYC) session through the API.

  Endpoint:
  PATCH [https://verification.didit.me/v3/session/\{session\_id}/add-images/](https://verification.didit.me/v3/session/\{session_id}/add-images/)

  Authentication:
  Send my Didit API key in the x-api-key header. A scoped key needs sessions: write.

  Goal:

  * Add evidence collected outside the verification flow (for example the back of an ID document, or a supporting letter) to the session's ID verification or Proof of Address result, so reviewers see it with the rest of the session.

  Request (multipart/form-data):

  * file (required): JPG, JPEG, PNG, WEBP, TIFF or PDF, at most 15 MB as uploaded. Didit compresses it and rejects it if it is still over 2 MB (2,097,152 bytes) after compression.
  * model\_type (required): "kyc" for the ID verification, "poa" for the Proof of Address.
  * file\_password (optional): the password of an encrypted PDF.

  Behavior:

  * The session must be Approved, Declined, In Review or Kyc Expired, and must have the result named by model\_type. Business (KYB) sessions are not supported.
  * When the step ran more than once, the file goes to the most recent result.
  * Each call adds one file and keeps the existing ones.
  * The file then appears in extra\_files of id\_verifications\[] or poa\_verifications\[] in GET /v3/session/{session_id}/decision/.
  * A FILE\_ADDED entry is added to the session's activity log. No webhook is sent and the session status does not change.
  * Rate limit: 10 requests per minute per API key.

  Example call:
  curl -X PATCH "[https://verification.didit.me/v3/session/11111111-2222-3333-4444-555555555555/add-images/](https://verification.didit.me/v3/session/11111111-2222-3333-4444-555555555555/add-images/)" \
  -H "x-api-key: YOUR\_API\_KEY" \
  -F "file=@back-of-id.jpg" \
  -F "model\_type=kyc"

  What to read from the response:

  * extra\_files: short-lived presigned links to every extra file of that result, including the new one. A scoped key without media: read receives them as null.

  Failure modes:

  * 400: file or model\_type missing, unsupported format, file too large before or after compression, encrypted PDF without the right file\_password.
  * 401: the API key has expired.
  * 403: missing key (a wrong, revoked or expired key gets 401), a key of another application, a scoped key without sessions: write, or a request from outside the key's IP allowlist.
  * 404: the session does not exist, was deleted, is outside a scoped key's limits, is not in a reviewable status, or has no result of that model\_type.
  * 429: more than 10 calls in a minute. Wait for Retry-After seconds.

  Side effects: stores the file with the session and adds an activity entry.

  For the full integration shape, see /integration/integration-prompt.\`
</pre>

Вставьте в

Предварительно подписанные ссылки в `extra_files` истекают. Если файлы понадобятся позже, получите новые ссылки из [решения по сессии](https://docs.didit.me/ru/sessions-api/retrieve-session.md). Чтобы исправить данные, извлечённые из документа, используйте [Обновление данных сессии](https://docs.didit.me/ru/sessions-api/update-data.md).


## OpenAPI

````yaml ru/openapi-25.json PATCH /v3/session/{sessionId}/add-images/
openapi: 3.0.0
info:
  version: 3.0.0
  title: Didit Verification API
  description: >-
    API верификации личности. Аутентификация выполняется с помощью заголовка
    x-api-key.
servers:
  - url: https://verification.didit.me
security: []
tags: []
paths:
  /v3/session/{sessionId}/add-images/:
    patch:
      tags:
        - Sessions
      summary: Добавить изображение к сессии
      description: >-
        Прикрепить одно дополнительное изображение или PDF-файл к результату
        верификации личности (`model_type=kyc`) или подтверждения адреса
        (`model_type=poa`) завершённой сессии проверки пользователей (KYC),
        например подтверждающие материалы, собранные вне сценария. Сессия должна
        находиться в статусе `Approved`, `Declined`, `In Review` или `Kyc
        Expired` и содержать результат, указанный в `model_type`; сессии
        верификации бизнеса (KYB) не поддерживаются. Каждый вызов добавляет один
        файл (к самому последнему результату, если шаг выполнялся более одного
        раза), сохраняет существующие файлы и записывает событие `FILE_ADDED` в
        журнал активности сессии; загрузка не отправляет webhook и не меняет
        статус сессии. Файл сжимается при загрузке и возвращается в поле
        `extra_files` решения по сессии. Этот endpoint ограничен 10 запросами в
        минуту на один API-ключ. Для API-ключа с ограниченной областью видимости
        требуется разрешение `sessions: write`, а без разрешения `media: read`
        ссылки в `extra_files` возвращаются как `null`.
      operationId: patch_v3_session_add_images
      parameters:
        - name: sessionId
          in: path
          required: true
          description: >-
            UUID сессии Проверки пользователей (KYC), в которую добавляется файл
            (`session_id`, возвращаемый методом `POST /v3/session/`).
            Идентификатор сессии Верификации бизнеса (KYB) вернёт `404`.
          schema:
            type: string
            format: uuid
            example: 11111111-2222-3333-4444-555555555555
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required:
                - file
                - model_type
              properties:
                file:
                  type: string
                  format: binary
                  description: >-
                    Изображение или PDF. Допустимые расширения: `jpg`, `jpeg`,
                    `png`, `webp`, `tiff`, `pdf`. Не более 15 MB при загрузке;
                    затем файл сжимается и отклоняется с кодом `400`, если он
                    всё ещё превышает 2 MB (2,097,152 байт). Пустые файлы
                    отклоняются.
                model_type:
                  type: string
                  enum:
                    - kyc
                    - poa
                  description: >-
                    `kyc` добавляет файл к результату верификации личности, а
                    `poa` к результату подтверждения адреса.
                  example: kyc
                file_password:
                  type: string
                  description: >-
                    Пароль от зашифрованного PDF-файла. Без него или при
                    неверном пароле зашифрованный PDF возвращает `400`.
            example:
              file: (binary)
              model_type: kyc
      responses:
        '200':
          description: >-
            Файл добавлен. Возвращает все дополнительные файлы этого результата,
            включая новый.
          content:
            application/json:
              schema:
                type: object
                required:
                  - extra_files
                properties:
                  extra_files:
                    type: array
                    description: >-
                      Временные предварительно подписанные ссылки на все
                      дополнительные файлы результата, определённого параметром
                      `model_type`, от старых к новым. Каждая ссылка имеет
                      значение `null` для API-ключа с ограниченной областью
                      действия без права `media: read`. Свежие ссылки можно
                      прочитать позже из решения по сессии.
                    items:
                      type: string
                      format: uri
                      nullable: true
              example:
                extra_files:
                  - >-
                    https://media.example.com/session/11111111-2222-3333-4444-555555555555/kyc-extra-files/66666666-7777-8888-9999-000000000000.jpg?expires=1789383731&signature=abc123
        '400':
          description: >-
            Ошибка валидации. Ошибки полей возвращаются в виде `{"<field>":
            ["<message>"]}`; ошибки зашифрованного PDF возвращаются в виде
            `{"detail": "..."}`.
          content:
            application/json:
              examples:
                Missing file:
                  summary: В форме отсутствует часть с файлом
                  value:
                    file:
                      - No file was submitted.
                Missing model_type:
                  summary: model_type пропущен
                  value:
                    model_type:
                      - This field is required.
                Invalid model_type:
                  summary: model_type не равен ни kyc, ни poa
                  value:
                    model_type:
                      - '"passport" is not a valid choice.'
                File too large:
                  summary: Размер загружаемого файла превышает 15 МБ
                  value:
                    file:
                      - File size should not exceed 15 MB
                Too large after compression:
                  summary: Размер по-прежнему превышает 2 МБ после сжатия
                  value:
                    file:
                      - File size is too big. Max allowed size is 2097152 bytes.
                Encrypted PDF:
                  summary: Зашифрованный PDF без file_password
                  value:
                    detail: >-
                      The PDF is encrypted. Please upload a decrypted PDF or a
                      photo instead.
                Wrong PDF password:
                  summary: file_password не открывает PDF
                  value:
                    detail: >-
                      The PDF password is incorrect. Please provide the correct
                      password.
        '401':
          description: >-
            Срок действия API-ключа с ограниченной областью действия истёк. Это
            единственный случай, возвращающий `401`: отсутствующий,
            недействительный или отозванный ключ возвращает `403`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  detail:
                    type: string
                    description: Понятное сообщение об ошибке.
              examples:
                Expired key:
                  summary: Срок действия ключа истёк
                  value:
                    detail: This API key has expired.
        '403':
          description: >-
            Ошибка аутентификации или авторизации. Отсутствующий ключ возвращает
            `403`, как и ключ другого приложения, ключ с ограниченной областью
            действия без необходимого для этого endpoint разрешения, а также
            запрос не из разрешённого списка IP-адресов ключа; неверный,
            отозванный или истекший ключ возвращает `401`. Различайте их по полю
            `detail`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  detail:
                    type: string
                    description: Понятное сообщение об ошибке.
              examples:
                Missing or invalid credentials:
                  summary: >-
                    Заголовок x-api-key отсутствует, либо ключ не прошёл
                    валидацию
                  value:
                    detail: >-
                      Authentication credentials were not provided or are
                      invalid.
                Other application:
                  summary: >-
                    Действительный ключ, принадлежащий приложению, отличному от
                    приложения сессии
                  value:
                    detail: You do not have permission to perform this action.
                Scoped key without sessions write:
                  summary: >-
                    У ключа с ограниченной областью действия отсутствует
                    разрешение sessions: write
                  value:
                    detail: This API key has no write access to sessions.
                IP not allowed:
                  summary: Запрос с IP-адреса вне списка разрешённых IP ключа
                  value:
                    detail: This API key can't be used from this IP address.
        '404':
          description: >-
            Сессия не существует, была удалена или находится за пределами
            ограничений ключа с ограниченным доступом; это KYB-сессия или она не
            находится в статусе `Approved`, `Declined`, `In Review` или `Kyc
            Expired`; либо у нее нет результата для запрошенного `model_type`
            (проверяется до валидации файла). Поиск сессии выполняется до
            проверки учетных данных, поэтому неизвестный `sessionId` возвращает
            `404` даже без действительного ключа.
          content:
            application/json:
              schema:
                type: object
                properties:
                  detail:
                    type: string
                    description: Понятное сообщение об ошибке.
              examples:
                Unknown session:
                  summary: Сессия с этим ID не существует или была удалена
                  value:
                    detail: Not found.
                Outside key limits:
                  summary: >-
                    Сессия находится за пределами ограничений ключа с
                    ограниченным доступом по сценариям или доступу только к
                    одобренным сессиям
                  value:
                    detail: Session not found.
                Not eligible:
                  summary: Сессия ещё не завершена, либо передан ID сессии KYB
                  value:
                    detail: No Session matches the given query.
                No ID verification:
                  summary: model_type=kyc для сессии без верификации личности
                  value:
                    detail: The session does not have KYC data.
                No Proof of Address:
                  summary: model_type=poa для сессии без подтверждения адреса
                  value:
                    detail: The session does not have POA data.
        '429':
          description: >-
            Превышен лимит запросов: 10 запросов на добавление изображений в
            минуту на один API-ключ (отклоненные запросы также учитываются).
            Также действует общий лимит в 300 запросов на запись в минуту.
            Подождите указанное в `Retry-After` количество секунд перед
            повторной попыткой; заголовки `X-RateLimit-*` показывают доступный
            лимит.
          content:
            application/json:
              schema:
                type: object
                properties:
                  detail:
                    type: string
                    description: Понятное сообщение об ошибке.
              examples:
                Rate limited:
                  summary: Бюджет на текущую минуту исчерпан
                  value:
                    detail: >-
                      Session add-images rate limit exceeded. You can make up to
                      10 requests per minute.
          headers:
            Retry-After:
              description: Количество секунд ожидания перед повторной попыткой.
              schema:
                type: integer
                minimum: 1
                example: 30
        '503':
          $ref: '#/components/responses/DocumentProcessingBusy'
      security:
        - ApiKeyAuth: []
      x-codeSamples:
        - lang: curl
          label: curl
          source: >-
            curl -X PATCH
            'https://verification.didit.me/v3/session/11111111-2222-3333-4444-555555555555/add-images/'
            \
              -H 'x-api-key: YOUR_API_KEY' \
              -F 'file=@./back-of-id.jpg' \
              -F 'model_type=kyc'
        - lang: python
          label: Python
          source: |-
            from didit import Didit

            # Reads DIDIT_API_KEY.
            client = Didit()

            result = client.sessions.add_images(
                "11111111-2222-3333-4444-555555555555",
                file=open("image.jpg", "rb"),
                model_type="kyc",
            )
            print(result)
        - lang: javascript
          label: Node.js
          source: >-
            import Didit, { fileFromPath } from "@didit-protocol/sdk-node";


            // Reads DIDIT_API_KEY.

            const didit = new Didit();


            const result = await
            didit.sessions.addImages("11111111-2222-3333-4444-555555555555", {
              file: await fileFromPath("image.jpg"),
              model_type: "kyc",
            });

            console.log(result);
        - lang: go
          label: Go
          source: "ctx := context.Background()\n// Reads DIDIT_API_KEY.\nclient := didit.NewClient()\n\nresult, err := client.Sessions.AddImages(ctx, \"11111111-2222-3333-4444-555555555555\", didit.SessionsAddImagesParams{\n\tFile:      didit.FileFromPath(\"image.jpg\"),\n\tModelType: \"kyc\",\n})\nif err != nil {\n\tlog.Fatal(err)\n}\nfmt.Printf(\"%+v\\n\", result)"
        - lang: java
          label: Java
          source: >-
            import java.nio.file.Path;

            import me.didit.Didit;

            import me.didit.types.SessionsAddImagesParams;


            // Reads DIDIT_API_KEY.

            Didit client = new Didit();


            var result =
            client.sessions().addImages("11111111-2222-3333-4444-555555555555",
            SessionsAddImagesParams.builder()
                    .file(Path.of("image.jpg"))
                    .modelType(SessionsAddImagesParams.ModelType.of("kyc"))
                    .build());
            System.out.println(result);
        - lang: php
          label: PHP
          source: >-
            <?php


            require 'vendor/autoload.php';


            use Didit\DiditClient;

            use Didit\File;


            // Reads DIDIT_API_KEY.

            $didit = new DiditClient();


            $result =
            $didit->sessions->addImages('11111111-2222-3333-4444-555555555555',
            [
                'file' => File::fromPath('image.jpg'),
                'model_type' => 'kyc',
            ]);

            print_r($result->toArray());
        - lang: ruby
          label: Ruby
          source: |-
            require "didit"

            # Reads DIDIT_API_KEY.
            didit = Didit::Client.new

            result = didit.sessions.add_images(
              "11111111-2222-3333-4444-555555555555",
              file: Pathname("image.jpg"),
              model_type: "kyc"
            )
            puts result.to_h
        - lang: csharp
          label: .NET
          source: >-
            using System;

            using System.Text.Json;

            using Didit;


            // Reads DIDIT_API_KEY.

            using var client = new DiditClient();


            var result = await
            client.Sessions.AddImagesAsync("11111111-2222-3333-4444-555555555555",
            new SessionsAddImagesParams

            {
                File = FileUpload.FromPath("image.jpg"),
                ModelType = "kyc",
            });

            Console.WriteLine(JsonSerializer.Serialize(result));
components:
  responses:
    DocumentProcessingBusy:
      description: >-
        В данный момент обрабатывается слишком много документов, поэтому эта
        загрузка не была обработана: ничего не сохранено, и попытка не была
        использована. Отправьте тот же файл повторно через количество секунд,
        указанное в `Retry-After`. Выполняйте ветвление по `code`, а не по
        тексту сообщения.
      headers:
        Retry-After:
          description: >-
            Количество секунд ожидания перед повторной отправкой того же
            запроса.
          schema:
            type: integer
            example: 10
      content:
        application/json:
          schema:
            type: object
            required:
              - detail
              - code
            properties:
              detail:
                type: string
              code:
                type: string
                enum:
                  - document_processing_busy
          example:
            detail: We are busy processing documents. Please try again in a moment.
            code: document_processing_busy
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: x-api-key
      description: >-
        API-ключ вашего приложения из раздела «Разработчикам» -> «API-ключи» в
        Business Console. Основной ключ имеет полный доступ. Именованный ключ
        может иметь ограниченную область действия: без доступа, чтение или
        запись для каждого ресурса, ограничение определенными сценариями или
        одобренными сессиями, списком IP-адресов и сроком действия. 401
        означает, что ключ неверен, отозван или его срок действия истек; 403
        означает, что ключ не был передан, у ключа нет доступа к этому ресурсу
        или действию, либо запрос поступил с адреса вне его списка IP-адресов;
        404 на маршруте сессии означает, что сессия не входит в сценарии или
        статусы ключа. Ключ без доступа к медиа получает URL изображений, видео
        и PDF как null, а ключ без прав на запись сессий получает ссылки на
        сессии и токены как null. См. https://docs.didit.me/console/api-keys.

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.