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

# Обновление данных Document AI: API Didit

> Исправьте поля, которые Didit извлёк из документа Document AI, или задайте статус проверки для сессии KYC или KYB в Didit.



Промпт API обновления данных Document AI
        Скопировать промпт в буфер обмена



      
      

\<pre>

\`Correct the extracted data of a Document AI document, or set its review status, on a Didit verification session through the API.

Endpoint:
PATCH https://verification.didit.me/v3/document-ai/{session_id}/documents/{document_uuid}/

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

Goal:
\- Fix a value Document AI misread, or approve or decline a document the workflow sent to review.

Request body (JSON, both fields optional):
\- extracted_data: a JSON object of field keys to new values. Merged key by key: sent keys replace the stored values (a null value clears one), keys I leave out keep their values. Do not send extracted_data itself as null (400); leave it out instead.
\- status: "Approved", "Declined", "In Review" or "Not Finished".

Behavior:
\- Works for user (KYC) and business (KYB) session IDs.
\- {document_uuid} is document_ai_documents[].items[].uuid from GET /v3/session/{session_id}/decision/, and the document must belong to that session.
\- The document status feeds the Document AI result of its workflow node in the decision. The session status is not recomputed.
\- Every successful call, even one that changes nothing, sends a data.updated webhook with trigger "manual_review".

Example call:
curl -X PATCH "https://verification.didit.me/v3/document-ai/11111111-2222-3333-4444-555555555555/documents/44444444-5555-6666-7777-888888888888/" \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"extracted_data": {"invoice_number": "INV-2026-0042"}, "status": "Approved"}'

What to read from the response:
\- extracted_data: all extracted fields after the merge.
\- status: the document's review status.
\- file_url: the storage path of the file, not a download link. Read the presigned file_url from the session decision to download it.

Failure modes:
\- 400: status is not one of the allowed values, or extracted_data is null (checked before the document is looked up).
\- 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 decisions: write, or a request from outside the key's IP allowlist.
\- 404: the session does not exist, was deleted, or is outside a scoped key's limits, or the document does not belong to the session.

Side effects: updates the document and sends a data.updated webhook.

For the full integration shape, see /integration/integration-prompt.`

\</pre>



      
      

Вставьте в

Ключи полей соответствуют тем, которые вы задали для документа в сценарии. О том, как настраиваются документы и поля, см. в разделе [Document AI](https://docs.didit.me/ru/core-technology/document-ai/overview.md), а о том, где результат появляется в решении по сессии, см. в разделе [отчёт Document AI](https://docs.didit.me/ru/core-technology/document-ai/report-document-ai.md).


## OpenAPI

````yaml ru/openapi-25.json PATCH /v3/document-ai/{sessionId}/documents/{documentUuid}/
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/document-ai/{sessionId}/documents/{documentUuid}/:
    patch:
      tags:
        - Sessions
      summary: Обновить документ Document AI
      description: >-
        Скорректируйте поля, извлечённые Document AI из одного загруженного
        документа, установите его статус проверки или выполните и то, и другое в
        сессии KYC или KYB. Поле `extracted_data` должно быть JSON-объектом и
        объединяется по ключам: отправленный ключ заменяет сохранённое значение
        (ключ, переданный со значением `null`, сохраняется как `null`), а
        опущенные ключи сохраняют свои значения. Статус документа передаётся в
        результат Document AI соответствующего узла сценария в решении по
        сессии; сам статус сессии повторно не пересчитывается. Каждый успешный
        вызов, даже если он ничего не изменяет, отправляет
        [webhook](https://docs.didit.me/ru/integration/webhooks) `data.updated`
        с триггером `manual_review`. Для API-ключа с ограниченной областью
        действия требуется `decisions: write`; см. [Document
        AI](https://docs.didit.me/ru/core-technology/document-ai/overview).
      operationId: patch_v3_document_ai_document
      parameters:
        - name: sessionId
          in: path
          required: true
          description: >-
            UUID сессии верификации (`session_id`, возвращённый `POST
            /v3/session/`). Принимает ID сессий как Проверки пользователей
            (KYC), так и Верификации бизнеса (KYB): сервер сопоставляет ID для
            обоих типов сессий. Должен быть корректным UUID; некорректное
            значение не соответствует маршруту и возвращает HTML `404`.
          schema:
            type: string
            format: uuid
            example: 11111111-2222-3333-4444-555555555555
        - name: documentUuid
          in: path
          required: true
          description: >-
            UUID документа Document AI (`document_ai_documents[].items[].uuid` в
            `GET /v3/session/{sessionId}/decision/`). Он должен принадлежать
            сессии, указанной в пути.
          schema:
            type: string
            format: uuid
            example: 44444444-5555-6666-7777-888888888888
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                extracted_data:
                  type: object
                  additionalProperties: true
                  description: >-
                    Ключи полей (ключи, которые вы настроили для документа) и их
                    исправленные значения. Должно быть объектом JSON;
                    объединяется по ключам с сохранёнными данными. Лучше
                    опустить поле, чем передавать `null`, что приведёт к ошибке
                    `400`.
                  example:
                    invoice_number: INV-2026-0042
                status:
                  type: string
                  enum:
                    - Approved
                    - Declined
                    - In Review
                    - Not Finished
                  description: Новый статус проверки документа.
                  example: Approved
            example:
              extracted_data:
                invoice_number: INV-2026-0042
              status: Approved
      responses:
        '200':
          description: Документ обновлён. Возвращает документ после объединения.
          content:
            application/json:
              schema:
                type: object
                required:
                  - uuid
                  - document_key
                  - original_filename
                  - file_url
                  - status
                  - extracted_data
                properties:
                  uuid:
                    type: string
                    format: uuid
                    description: Идентификатор документа.
                  document_key:
                    type: string
                    description: Настроенный документ, которому соответствует эта загрузка.
                  original_filename:
                    type: string
                    nullable: true
                    description: Имя файла, с которым был загружен документ.
                  file_url:
                    type: string
                    nullable: true
                    description: >-
                      Путь хранения загруженного файла. Это не ссылка на
                      скачивание: чтобы скачать файл, прочитайте предварительно
                      подписанный `file_url` из решения по сессии.
                  status:
                    type: string
                    enum:
                      - Not Finished
                      - Approved
                      - Declined
                      - In Review
                      - Resub Requested
                    description: Статус проверки документа.
                  extracted_data:
                    type: object
                    nullable: true
                    additionalProperties: true
                    description: >-
                      Все извлечённые поля после объединения, с ключами,
                      соответствующими ключам полей.
              example:
                uuid: 44444444-5555-6666-7777-888888888888
                document_key: invoice
                original_filename: invoice-2026-09.pdf
                file_url: >-
                  document_ai/11111111-2222-3333-4444-555555555555-66666666-7777-8888-9999-000000000000.pdf
                status: Approved
                extracted_data:
                  invoice_number: INV-2026-0042
                  total_amount: 1250
                  issue_date: '2026-09-01'
        '400':
          description: >-
            Ошибка валидации; проверка выполняется до поиска документа: `status`
            не входит в список допустимых значений или `extracted_data` передан
            как `null`.
          content:
            application/json:
              examples:
                Invalid status:
                  summary: status отсутствует в перечислении enum
                  value:
                    status:
                      - '"Rejected" is not a valid choice.'
                Null extracted_data:
                  summary: extracted_data имеет значение null
                  value:
                    extracted_data:
                      - This field may not be null.
        '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 decisions write:
                  summary: >-
                    У ключа с ограниченной областью действия отсутствует
                    разрешение decisions: write
                  value:
                    detail: This API key has no write access to decisions.
                IP not allowed:
                  summary: Запрос с IP-адреса вне списка разрешённых IP ключа
                  value:
                    detail: This API key can't be used from this IP address.
        '404':
          description: >-
            Сессия не существует, была удалена или находится за пределами
            ограничений ключа с ограниченным доступом, либо к ней не относится
            ни один текущий документ с этим UUID. Поиск сессии выполняется до
            проверки учетных данных, поэтому неизвестный `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.
                Unknown document:
                  summary: documentUuid не принадлежит сессии
                  value:
                    detail: Document AI document not found.
        '429':
          description: >-
            Превышен лимит запросов: 300 запросов на запись (POST, PATCH,
            DELETE) в минуту на один API-ключ. Подождите указанное в
            `Retry-After` количество секунд перед повторной попыткой; заголовки
            `X-RateLimit-*` показывают доступный лимит.
          content:
            application/json:
              schema:
                type: object
                properties:
                  detail:
                    type: string
                    description: Понятное сообщение об ошибке.
              examples:
                Rate limited:
                  summary: Бюджет на текущую минуту исчерпан
                  value:
                    detail: >-
                      Write request rate limit exceeded. You can make up to 300
                      requests per minute.
          headers:
            Retry-After:
              description: Количество секунд ожидания перед повторной попыткой.
              schema:
                type: integer
                minimum: 1
                example: 30
      security:
        - ApiKeyAuth: []
      x-codeSamples:
        - lang: curl
          label: curl
          source: >-
            curl -X PATCH
            'https://verification.didit.me/v3/document-ai/11111111-2222-3333-4444-555555555555/documents/44444444-5555-6666-7777-888888888888/'
            \
              -H 'x-api-key: YOUR_API_KEY' \
              -H 'Content-Type: application/json' \
              -d '{"extracted_data": {"invoice_number": "INV-2026-0042"}, "status": "Approved"}'
        - lang: python
          label: Python
          source: |-
            from didit import Didit

            # Reads DIDIT_API_KEY.
            client = Didit()

            result = client.sessions.update_document_ai_data(
                "11111111-2222-3333-4444-555555555555",
                "44444444-5555-6666-7777-888888888888",
                extracted_data={"invoice_number": "INV-2026-0042"},
                status="Approved",
            )
            print(result)
        - lang: javascript
          label: Node.js
          source: |-
            import Didit from "@didit-protocol/sdk-node";

            // Reads DIDIT_API_KEY.
            const didit = new Didit();

            const result = await didit.sessions.updateDocumentAiData(
              "11111111-2222-3333-4444-555555555555",
              "44444444-5555-6666-7777-888888888888",
              {
                extracted_data: { invoice_number: "INV-2026-0042" },
                status: "Approved",
              },
            );
            console.log(result);
        - lang: go
          label: Go
          source: "ctx := context.Background()\n// Reads DIDIT_API_KEY.\nclient := didit.NewClient()\n\nresult, err := client.Sessions.UpdateDocumentAiData(ctx, \"11111111-2222-3333-4444-555555555555\", \"44444444-5555-6666-7777-888888888888\", didit.SessionsUpdateDocumentAiDataParams{\n\tExtractedData: didit.Some(map[string]any{\"invoice_number\": \"INV-2026-0042\"}),\n\tStatus:        didit.Some(didit.SessionsUpdateDocumentAiDataParamsStatus(\"Approved\")),\n})\nif err != nil {\n\tlog.Fatal(err)\n}\nfmt.Printf(\"%+v\\n\", result)"
        - lang: java
          label: Java
          source: >-
            import java.util.Map;

            import me.didit.Didit;

            import me.didit.types.SessionsUpdateDocumentAiDataParams;


            // Reads DIDIT_API_KEY.

            Didit client = new Didit();


            var result =
            client.sessions().updateDocumentAiData("11111111-2222-3333-4444-555555555555",
            "44444444-5555-6666-7777-888888888888",
            SessionsUpdateDocumentAiDataParams.builder()
                    .extractedData(Map.of("invoice_number", "INV-2026-0042"))
                    .status(SessionsUpdateDocumentAiDataParams.Status.of("Approved"))
                    .build());
            System.out.println(result);
        - lang: php
          label: PHP
          source: >-
            <?php


            require 'vendor/autoload.php';


            use Didit\DiditClient;


            // Reads DIDIT_API_KEY.

            $didit = new DiditClient();


            $result =
            $didit->sessions->updateDocumentAiData('11111111-2222-3333-4444-555555555555',
            '44444444-5555-6666-7777-888888888888', [
                'extracted_data' => ['invoice_number' => 'INV-2026-0042'],
                'status' => 'Approved',
            ]);

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

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

            result = didit.sessions.update_document_ai_data(
              "11111111-2222-3333-4444-555555555555",
              "44444444-5555-6666-7777-888888888888",
              extracted_data: { invoice_number: "INV-2026-0042" },
              status: "Approved"
            )
            puts result.to_h
        - lang: csharp
          label: .NET
          source: >-
            using System;

            using System.Collections.Generic;

            using System.Text.Json;

            using Didit;


            // Reads DIDIT_API_KEY.

            using var client = new DiditClient();


            var result = await
            client.Sessions.UpdateDocumentAiDataAsync("11111111-2222-3333-4444-555555555555",
            "44444444-5555-6666-7777-888888888888", new
            SessionsUpdateDocumentAiDataParams

            {
                ExtractedData = new Dictionary<string, object> { ["invoice_number"] = "INV-2026-0042" },
                Status = new SessionsUpdateDocumentAiDataParamsStatus("Approved"),
            });

            Console.WriteLine(JsonSerializer.Serialize(result));
components:
  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.