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

# Consultar tarefa

> Consulta o status e o resultado de tarefas Midjourney. Endpoint unificado /v1/tasks/{task_id} e endpoint estilo MJ /v1/midjourney/{task_id}

<RequestExample>
  ```bash cURL theme={null}
  curl --request GET \
    --url https://api.apimart.ai/v1/midjourney/task_01KV52C0TEJSYZMCG0NCS4YWKK \
    --header 'Authorization: Bearer <token>'
  ```

  ```python Python theme={null}
  import requests

  url = "https://api.apimart.ai/v1/midjourney/task_01KV52C0TEJSYZMCG0NCS4YWKK"

  headers = {
      "Authorization": "Bearer <token>"
  }

  response = requests.get(url, headers=headers)

  print(response.json())
  ```

  ```javascript JavaScript theme={null}
  const url = "https://api.apimart.ai/v1/midjourney/task_01KV52C0TEJSYZMCG0NCS4YWKK";

  const headers = {
    "Authorization": "Bearer <token>"
  };

  fetch(url, {
    method: "GET",
    headers: headers
  })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
  ```

  ```go Go theme={null}
  package main

  import (
      "fmt"
      "io/ioutil"
      "net/http"
  )

  func main() {
      url := "https://api.apimart.ai/v1/midjourney/task_01KV52C0TEJSYZMCG0NCS4YWKK"

      req, _ := http.NewRequest("GET", url, nil)
      req.Header.Set("Authorization", "Bearer <token>")

      client := &http.Client{}
      resp, err := client.Do(req)
      if err != nil {
          panic(err)
      }
      defer resp.Body.Close()

      body, _ := ioutil.ReadAll(resp.Body)
      fmt.Println(string(body))
  }
  ```

  ```java Java theme={null}
  import java.net.http.HttpClient;
  import java.net.http.HttpRequest;
  import java.net.http.HttpResponse;
  import java.net.URI;

  public class Main {
      public static void main(String[] args) throws Exception {
          String url = "https://api.apimart.ai/v1/midjourney/task_01KV52C0TEJSYZMCG0NCS4YWKK";

          HttpClient client = HttpClient.newHttpClient();
          HttpRequest request = HttpRequest.newBuilder()
              .uri(URI.create(url))
              .header("Authorization", "Bearer <token>")
              .GET()
              .build();

          HttpResponse<String> response = client.send(request,
              HttpResponse.BodyHandlers.ofString());

          System.out.println(response.body());
      }
  }
  ```

  ```php PHP theme={null}
  <?php

  $url = "https://api.apimart.ai/v1/midjourney/task_01KV52C0TEJSYZMCG0NCS4YWKK";

  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
      "Authorization: Bearer <token>"
  ]);

  $response = curl_exec($ch);
  curl_close($ch);

  echo $response;
  ?>
  ```

  ```ruby Ruby theme={null}
  require 'net/http'
  require 'json'
  require 'uri'

  url = URI("https://api.apimart.ai/v1/midjourney/task_01KV52C0TEJSYZMCG0NCS4YWKK")

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true

  request = Net::HTTP::Get.new(url)
  request["Authorization"] = "Bearer <token>"

  response = http.request(request)
  puts response.body
  ```

  ```swift Swift theme={null}
  import Foundation

  let url = URL(string: "https://api.apimart.ai/v1/midjourney/task_01KV52C0TEJSYZMCG0NCS4YWKK")!

  var request = URLRequest(url: url)
  request.httpMethod = "GET"
  request.setValue("Bearer <token>", forHTTPHeaderField: "Authorization")

  let task = URLSession.shared.dataTask(with: request) { data, response, error in
      if let error = error {
          print("Error: \(error)")
          return
      }
      
      if let data = data, let responseString = String(data: data, encoding: .utf8) {
          print(responseString)
      }
  }

  task.resume()
  ```

  ```csharp C# theme={null}
  using System;
  using System.Net.Http;
  using System.Threading.Tasks;

  class Program
  {
      static async Task Main(string[] args)
      {
          var url = "https://api.apimart.ai/v1/midjourney/task_01KV52C0TEJSYZMCG0NCS4YWKK";

          using var client = new HttpClient();
          client.DefaultRequestHeaders.Add("Authorization", "Bearer <token>");

          var response = await client.GetAsync(url);
          var result = await response.Content.ReadAsStringAsync();

          Console.WriteLine(result);
      }
  }
  ```

  ```c C theme={null}
  #include <stdio.h>
  #include <curl/curl.h>

  int main(void) {
      CURL *curl;
      CURLcode res;

      curl_global_init(CURL_GLOBAL_DEFAULT);
      curl = curl_easy_init();

      if(curl) {
          const char *url = "https://api.apimart.ai/v1/midjourney/task_01KV52C0TEJSYZMCG0NCS4YWKK";

          struct curl_slist *headers = NULL;
          headers = curl_slist_append(headers, "Authorization: Bearer <token>");

          curl_easy_setopt(curl, CURLOPT_URL, url);
          curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

          res = curl_easy_perform(curl);

          if(res != CURLE_OK) {
              fprintf(stderr, "curl_easy_perform() failed: %s\n",
                      curl_easy_strerror(res));
          }

          curl_slist_free_all(headers);
          curl_easy_cleanup(curl);
      }

      curl_global_cleanup();
      return 0;
  }
  ```

  ```objectivec Objective-C theme={null}
  #import <Foundation/Foundation.h>

  int main(int argc, const char * argv[]) {
      @autoreleasepool {
          NSURL *url = [NSURL URLWithString:@"https://api.apimart.ai/v1/midjourney/task_01KV52C0TEJSYZMCG0NCS4YWKK"];
          
          NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
          [request setHTTPMethod:@"GET"];
          [request setValue:@"Bearer <token>" forHTTPHeaderField:@"Authorization"];
          
          NSURLSessionDataTask *task = [[NSURLSession sharedSession] 
              dataTaskWithRequest:request
              completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                  if (error) {
                      NSLog(@"Error: %@", error);
                      return;
                  }
                  NSString *result = [[NSString alloc] initWithData:data 
                                                          encoding:NSUTF8StringEncoding];
                  NSLog(@"%@", result);
              }];
          
          [task resume];
          [[NSRunLoop mainRunLoop] run];
      }
      return 0;
  }
  ```

  ```ocaml OCaml theme={null}
  (* Requires cohttp and yojson libraries *)
  open Lwt
  open Cohttp
  open Cohttp_lwt_unix

  let url = "https://api.apimart.ai/v1/midjourney/task_01KV52C0TEJSYZMCG0NCS4YWKK"

  let () =
    let headers = Header.init ()
      |> fun h -> Header.add h "Authorization" "Bearer <token>"
    in
    let response = Client.get ~headers (Uri.of_string url) >>= fun (resp, body) ->
      body |> Cohttp_lwt.Body.to_string >|= fun body_str ->
      print_endline body_str
    in
    Lwt_main.run response
  ```

  ```dart Dart theme={null}
  import 'package:http/http.dart' as http;

  void main() async {
    final url = Uri.parse('https://api.apimart.ai/v1/midjourney/task_01KV52C0TEJSYZMCG0NCS4YWKK');
    
    final response = await http.get(
      url,
      headers: {
        'Authorization': 'Bearer <token>',
      },
    );
    
    print(response.body);
  }
  ```

  ```r R theme={null}
  library(httr)

  url <- "https://api.apimart.ai/v1/midjourney/task_01KV52C0TEJSYZMCG0NCS4YWKK"

  response <- GET(
    url,
    add_headers(
      Authorization = "Bearer <token>"
    )
  )

  cat(content(response, "text"))
  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={null}
  {
    "id": "task_01KV52C0TEJSYZMCG0NCS4YWKK",
    "status": "SUCCESS",
    "action": "IMAGINE",
    "progress": "100%",
    "grid_image_url": "https://cdn.apimart.ai/mj_xxxx.png",
    "image_urls": [
      "https://cdn.apimart.ai/mj_xxxx_0.png",
      "https://cdn.apimart.ai/mj_xxxx_1.png",
      "https://cdn.apimart.ai/mj_xxxx_2.png",
      "https://cdn.apimart.ai/mj_xxxx_3.png"
    ],
    "buttons": [
      {"customId": "MJ::JOB::upsample::1::abc123def456", "label": "U1"},
      {"customId": "MJ::JOB::variation::1::abc123def456", "label": "V1"}
    ],
    "prompt": "a beautiful sunset over mountains"
  }
  ```

  ```json 401 theme={null}
  {
    "error": {
      "code": 401,
      "message": "Invalid authentication credentials",
      "type": "authentication_error"
    }
  }
  ```

  ```json 403 theme={null}
  {
    "error": {
      "code": 403,
      "message": "Access forbidden. You don't have permission to access this resource",
      "type": "permission_error"
    }
  }
  ```

  ```json 404 theme={null}
  {
    "error": {
      "code": 404,
      "message": "Task not found",
      "type": "not_found_error"
    }
  }
  ```

  ```json 429 theme={null}
  {
    "error": {
      "code": 429,
      "message": "Rate limit exceeded. Please try again later",
      "type": "rate_limit_error"
    }
  }
  ```

  ```json 500 theme={null}
  {
    "error": {
      "code": 500,
      "message": "Internal server error. Please try again later",
      "type": "server_error"
    }
  }
  ```

  ```json 502 theme={null}
  {
    "error": {
      "code": 502,
      "message": "Bad gateway. The server is temporarily unavailable",
      "type": "bad_gateway"
    }
  }
  ```
</ResponseExample>

Endpoint de polling recomendado:

```
GET /v1/tasks/{task_id}
```

Os status unificados são `pending` / `processing` / `completed` / `failed`; os resultados estão em `result.images[].url`.

Use o endpoint estilo MJ quando precisar de `buttons[].customId` para ações de acompanhamento:

```
GET /v1/midjourney/{task_id}
```

## Fluxo de status

```
SUBMITTED → IN_PROGRESS → SUCCESS
                        → FAILURE
                        → MODAL (veja Inpaint)
```

## Exemplo de response

```json theme={null}
{
  "id": "task_01JWXXXX",
  "status": "SUCCESS",
  "action": "IMAGINE",
  "progress": "100%",
  "grid_image_url": "https://cdn.apimart.ai/mj_xxxx.png",
  "image_urls": [
    "https://cdn.apimart.ai/mj_xxxx_0.png",
    "https://cdn.apimart.ai/mj_xxxx_1.png",
    "https://cdn.apimart.ai/mj_xxxx_2.png",
    "https://cdn.apimart.ai/mj_xxxx_3.png"
  ],
  "buttons": [
    {"customId": "MJ::JOB::upsample::1::abc123def456", "label": "U1"},
    {"customId": "MJ::JOB::variation::1::abc123def456", "label": "V1"}
  ],
  "prompt": "a beautiful sunset over mountains"
}
```

> `grid_image_url` é a imagem grid 2x2; `image_urls` são as quatro URLs de imagens individuais recortadas.

<Warning>
  **Diferenças de campos**

  * `/v1/tasks/{task_id}` retorna status unificados `pending` / `processing` / `completed` / `failed`.
  * `/v1/midjourney/{task_id}` retorna campos estilo MJ como `grid_image_url`, `image_urls`, `buttons`.
</Warning>

**Sobre `buttons`:** Para a maioria das ações de acompanhamento, passe `index`, `direction` ou `zoom_ratio` e o serviço encontra o `customId` correspondente. Se o auto-matching falhar, passe `custom_id` diretamente.

## Resumo de status

| status        | Significado                                                            | Terminal |
| ------------- | ---------------------------------------------------------------------- | -------- |
| `NOT_START`   | Linha criada, ainda não confirmada pelo sistema (transitório)          | Não      |
| `SUBMITTED`   | O sistema aceita, na fila                                              | Não      |
| `IN_PROGRESS` | O sistema processando                                                  | Não      |
| `MODAL`       | Aguardando parâmetros de `/modal` (ver Inpaint)                        | Não      |
| `SUCCESS`     | Concluído                                                              | ✓        |
| `FAILURE`     | Falhou → reembolso automático (`quota` → 0, `fail_reason` com a causa) | ✓        |

## Notas de consulta

* O endpoint de consulta **não é cobrado separadamente**, mas mantenha uma frequência razoável (polling de 3–5s recomendado).
* Um usuário comum só pode consultar suas próprias tarefas; consultar as de outros retorna `403`.
* As tarefas são retidas por **3 dias** por padrão; depois, consultas retornam `404`, mas as URLs de imagem / vídeo geradas continuam acessíveis.

## Avançado: usar custom\_id diretamente

Após ler `buttons[].customId`, você pode passá-lo diretamente no campo `custom_id` dos endpoints de ação de acompanhamento, ignorando o auto-matching:

```json theme={null}
{
  "task_id": "task_01JWXXXX",
  "custom_id": "MJ::JOB::upsample::1::abc123def456"
}
```
