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

# Recuperare un task Midjourney

> Usa CometAPI GET /mj/task/{id}/fetch per recuperare rapidamente e in modo affidabile lo stato di un singolo task Midjourney per il monitoraggio e il polling dei risultati.

Usa questo endpoint dopo ogni chiamata di invio Midjourney. È l'endpoint principale di polling per i flussi di lavoro imagine, action, modal, blend ed editor.

## Controlla prima questi campi

* `status` per lo stato complessivo del task
* `progress` per il segnale di completamento corrente
* `imageUrl` o `videoUrl` quando la risorsa è pronta
* `buttons` per i successivi valori `customId` disponibili

## Regole di polling

* Continua il polling finché il task non raggiunge `SUCCESS`, `MODAL` o `FAILURE`
* Considera l'array `buttons` come la fonte di verità per le azioni successive
* Usa `imageUrl` quando ti serve la griglia finale o il risultato dell'upscale


## OpenAPI

````yaml api/openapi/image/midjourney/task-fetching-api/get-fetch-single-task.openapi.json GET /mj/task/{id}/fetch
openapi: 3.1.0
info:
  title: Fetch Single Task API
  version: 1.0.0
  description: >-
    Poll a Midjourney task created through CometAPI and read the finished image
    URL plus the next available action buttons.
servers:
  - url: https://api.cometapi.com
security:
  - bearerAuth: []
paths:
  /mj/task/{id}/fetch:
    get:
      summary: Fetch a Midjourney task
      description: >-
        Use the task id returned by imagine, action, blend, modal, or editor
        endpoints. This is the main polling endpoint for Midjourney workflows on
        CometAPI.
      operationId: fetch_single_task
      parameters:
        - name: id
          in: path
          required: true
          description: Midjourney task id.
          schema:
            type: string
      responses:
        '200':
          description: Current task state.
          content:
            application/json:
              schema:
                type: object
                required:
                  - id
                  - status
                  - progress
                  - imageUrl
                  - buttons
                properties:
                  id:
                    type: string
                    description: Task id.
                  action:
                    type: string
                    description: >-
                      Task type: `IMAGINE`, `UPSCALE`, `VARIATION`, `DESCRIBE`,
                      `BLEND`, `VIDEO`, or another action name.
                  customId:
                    type: string
                    description: >-
                      Button customId that created this task, when the task came
                      from an action.
                  botType:
                    type: string
                    description: >-
                      Bot that handled the task, `MID_JOURNEY` or
                      `NIJI_JOURNEY`, when reported.
                  prompt:
                    type: string
                    description: Original prompt as submitted.
                  promptEn:
                    type: string
                    description: >-
                      Prompt after translation to the provider language. For
                      `DESCRIBE` tasks, the extracted prompt suggestions arrive
                      here.
                  description:
                    type: string
                    description: Human-readable submission status message.
                  state:
                    type: string
                    description: >-
                      Custom state string echoed back from the submission for
                      your own tracking.
                  submitTime:
                    type: integer
                    description: Submission time as a Unix timestamp in milliseconds.
                  startTime:
                    type: integer
                    description: Processing start time as a Unix timestamp in milliseconds.
                  finishTime:
                    type: integer
                    description: Completion time as a Unix timestamp in milliseconds.
                  imageUrl:
                    type: string
                    description: >-
                      Stable CometAPI-proxied image link
                      (`https://api.cometapi.com/mj/image/{id}`). Prefer this
                      link; entries in `image_urls` point at provider storage
                      and can expire.
                  videoUrl:
                    type: string
                    description: Generated video link for `VIDEO` tasks.
                  status:
                    type: string
                    description: >-
                      Task lifecycle state: `NOT_START`, `SUBMITTED`,
                      `IN_PROGRESS`, `SUCCESS`, or `FAILURE`.
                  progress:
                    type: string
                    description: >-
                      Progress percentage string such as `58%` while the task
                      runs and `100%` when finished.
                  failReason:
                    type: string
                    description: Failure reason when `status` is `FAILURE`.
                  buttons:
                    type: array
                    items:
                      type: object
                      properties:
                        customId:
                          type: string
                        emoji:
                          type: string
                        label:
                          type: string
                        type:
                          type: integer
                        style:
                          type: integer
                    description: >-
                      Action buttons available on the finished task. Send a
                      button's `customId` together with this task's id to
                      `/mj/submit/action` to upscale, vary, zoom, or pan.
                  maskBase64:
                    type: string
                    description: Mask attached to the task when a region edit created it.
                  properties:
                    type: object
                    properties:
                      finalPrompt:
                        type: string
                      finalZhPrompt:
                        type: string
                    description: Additional task metadata, such as `finalPrompt`.
                example:
                  id: '1773314942177684'
                  status: SUCCESS
                  progress: 100%
                  imageUrl: https://api.cometapi.com/mj/image/1773314942177684
                  videoUrl: ''
                  buttons:
                    - customId: MJ::JOB::upsample::1::example
                      emoji: ''
                      label: U1
                      type: 2
                      style: 1
      x-codeSamples:
        - lang: Shell
          label: Default
          source: |
            TASK_ID="<task_id>"

            curl "https://api.cometapi.com/mj/task/$TASK_ID/fetch" \
              -H "Authorization: Bearer $COMETAPI_KEY"
        - lang: Shell
          label: Poll until done
          source: |
            TASK_ID="<task_id>"

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

            task_id = "<task_id>"

            response = requests.get(
                f"https://api.cometapi.com/mj/task/{task_id}/fetch",
                headers={"Authorization": "Bearer " + os.environ["COMETAPI_KEY"]},
            )

            task = response.json()
            print(task["status"], task["progress"], task.get("imageUrl"))
        - lang: Python
          label: Poll until done
          source: |
            import os
            import time
            import requests

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

            while True:
                task = requests.get(
                    f"https://api.cometapi.com/mj/task/{task_id}/fetch", headers=headers
                ).json()
                print(task["status"], task.get("progress"))
                if task["status"] in ("SUCCESS", "FAILURE"):
                    break
                time.sleep(20)

            if task["status"] == "SUCCESS":
                print(task["imageUrl"])
            else:
                print(task.get("failReason"))
        - lang: JavaScript
          label: Default
          source: >
            const taskId = "<task_id>";


            const response = await
            fetch(`https://api.cometapi.com/mj/task/${taskId}/fetch`, {
                headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}` },
            });


            const task = await response.json();

            console.log(task.status, task.progress, task.imageUrl);
        - lang: JavaScript
          label: Poll until done
          source: >
            const taskId = "<task_id>";

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


            let task;

            while (true) {
                task = await (await fetch(`https://api.cometapi.com/mj/task/${taskId}/fetch`, { headers })).json();
                console.log(task.status, task.progress);
                if (task.status === "SUCCESS" || task.status === "FAILURE") break;
                await new Promise((resolve) => setTimeout(resolve, 20000));
            }


            console.log(task.status === "SUCCESS" ? task.imageUrl :
            task.failReason);
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: Bearer token authentication. Use your CometAPI key.

````