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

# Получение результатов видео xAI

> Используйте GET /grok/v1/videos/{request_id}, чтобы опрашивать статус генерации видео xAI и получить финальный URL видео после завершения обработки.

Используйте этот endpoint после того, как у вас уже есть `request_id`. Он сообщает, выполняется ли задание xAI, и возвращает финальные метаданные видео, когда они будут готовы.

## Сначала проверьте эти поля

* `request_id`, если задача была принята, но результат пока не готов
* `status` для состояния задания xAI; продолжайте опрос, пока оно не достигнет `done`
* `progress` для процента завершения, если это поле возвращается
* `video.url`, когда рендеринг завершён

## Цикл опроса

<Steps>
  <Step title="Сначала создайте или отредактируйте видео">
    Начните с [Создание видео xAI](./video-generation) или [Создание редактирования видео xAI](./video-edit), затем скопируйте возвращённый `request_id`.
  </Step>

  <Step title="Продолжайте опрос, пока status не станет done">
    Если ответ только повторяет `request_id`, подождите несколько секунд и выполните опрос снова. Как только появится `status`, используйте его как условие остановки.
  </Step>

  <Step title="Сохраните готовый файл">
    Сразу скачайте или скопируйте финальный `video.url`, потому что xAI указывает, что сгенерированные URL являются временными.
  </Step>
</Steps>


## OpenAPI

````yaml api/openapi/video/xai/get-get-video-generation-results.openapi.json GET /grok/v1/videos/{request_id}
openapi: 3.1.0
info:
  title: Get Video Generation Results API
  version: 1.0.0
  description: >-
    Query an xAI Grok video job created through CometAPI and read the final
    temporary video URL when the job is complete.
servers:
  - url: https://api.cometapi.com
security:
  - bearerAuth: []
paths:
  /grok/v1/videos/{request_id}:
    get:
      summary: Query an xAI video job
      description: >-
        Use the request_id from the generation or edit endpoint to poll status
        until the job completes. xAI documents the final video URL as temporary.
      operationId: get_video_generation_results
      parameters:
        - name: request_id
          in: path
          required: true
          description: Deferred request id returned by the create or edit endpoint.
          schema:
            type: string
      responses:
        '200':
          description: Current xAI video task state.
          content:
            application/json:
              schema:
                type: object
                properties:
                  request_id:
                    type: string
                    description: >-
                      Returned when the request is accepted but result metadata
                      is not ready yet.
                  model:
                    type: string
                    description: xAI video model id.
                  usage:
                    type: object
                    properties:
                      cost_in_usd_ticks:
                        type: integer
                        description: Billing usage value returned by xAI.
                    description: >-
                      Billing metadata. `cost_in_usd_ticks` reports the cost in
                      provider ticks.
                  video:
                    type: object
                    description: >-
                      Generated video metadata. Present when the job has
                      completed.
                    properties:
                      url:
                        type: string
                        description: Temporary URL for the generated MP4.
                      duration:
                        type: integer
                        description: Video duration in seconds.
                      respect_moderation:
                        type: boolean
                        description: Moderation flag returned with the video.
                  status:
                    type: string
                    description: xAI job state. `done` means the video metadata is ready.
                    enum:
                      - queued
                      - processing
                      - done
                      - failed
                      - expired
                  progress:
                    type: integer
                    description: Completion percentage when returned.
                  error:
                    description: Error details when the job fails.
                    nullable: true
                    oneOf:
                      - type: string
                      - type: object
              examples:
                accepted:
                  summary: Task accepted, keep polling
                  value:
                    request_id: <request_id>
                done:
                  summary: Task finished successfully
                  value:
                    model: grok-imagine-video-1.5
                    usage:
                      cost_in_usd_ticks: 500000000
                    video:
                      url: https://example.com/xai-video.mp4
                      duration: 1
                      respect_moderation: true
                    status: done
                    progress: 100
              example:
                model: grok-imagine-video-1.5
                usage:
                  cost_in_usd_ticks: 500000000
                video:
                  url: https://example.com/xai-video.mp4
                  duration: 1
                  respect_moderation: true
                status: done
                progress: 100
      x-codeSamples:
        - lang: Shell
          label: Default
          source: |
            REQUEST_ID="<request_id>"

            curl "https://api.cometapi.com/grok/v1/videos/$REQUEST_ID" \
              -H "Authorization: Bearer $COMETAPI_KEY"
        - lang: Shell
          label: Poll until done
          source: |
            REQUEST_ID="<request_id>"

            while true; do
              STATUS=$(curl -s "https://api.cometapi.com/grok/v1/videos/$REQUEST_ID" \
                -H "Authorization: Bearer $COMETAPI_KEY" | python3 -c "import json,sys; print(json.load(sys.stdin)['status'])")
              echo "status: $STATUS"
              case "$STATUS" in done | failed | expired) break;; esac
              sleep 20
            done
        - lang: Python
          label: Default
          source: |
            import os
            import requests

            request_id = "<request_id>"

            response = requests.get(
                f"https://api.cometapi.com/grok/v1/videos/{request_id}",
                headers={"Authorization": "Bearer " + os.environ["COMETAPI_KEY"]},
            )

            print(response.json())
        - lang: Python
          label: Poll until done
          source: |
            import os
            import time
            import requests

            request_id = "<request_id>"
            headers = {"Authorization": "Bearer " + os.environ["COMETAPI_KEY"]}

            while True:
                task = requests.get(
                    f"https://api.cometapi.com/grok/v1/videos/{request_id}", headers=headers
                ).json()
                print(task.get("status"), task.get("progress"))
                if task.get("status") in ("done", "failed", "expired"):
                    break
                time.sleep(10)

            if task.get("status") == "done":
                print(task["video"]["url"])
        - lang: JavaScript
          label: Default
          source: >
            const requestId = "<request_id>";


            const response = await
            fetch(`https://api.cometapi.com/grok/v1/videos/${requestId}`, {
                headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}` },
            });


            console.log(await response.json());
        - lang: JavaScript
          label: Poll until done
          source: >
            const requestId = "<request_id>";

            const headers = { Authorization: `Bearer
            ${process.env.COMETAPI_KEY}` };


            let task;

            while (true) {
                task = await (await fetch(`https://api.cometapi.com/grok/v1/videos/${requestId}`, { headers })).json();
                console.log(task.status, task.progress);
                if (["done", "failed", "expired"].includes(task.status)) break;
                await new Promise((resolve) => setTimeout(resolve, 10000));
            }


            if (task.status === "done") console.log(task.video.url);
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: Bearer token authentication. Use your CometAPI key.

````