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

# タスク取得

> Midjourney タスクの状態と結果を取得。統一タスク API /v1/tasks/{task_id} と MJ 形式 API /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": "認証情報が無効です",
      "type": "authentication_error"
    }
  }
  ```

  ```json 403 theme={null}
  {
    "error": {
      "code": 403,
      "message": "アクセスが禁止されています。このリソースへのアクセス権限がありません",
      "type": "permission_error"
    }
  }
  ```

  ```json 404 theme={null}
  {
    "error": {
      "code": 404,
      "message": "タスクが見つかりません",
      "type": "not_found_error"
    }
  }
  ```

  ```json 429 theme={null}
  {
    "error": {
      "code": 429,
      "message": "レート制限を超過しました。後でもう一度お試しください",
      "type": "rate_limit_error"
    }
  }
  ```

  ```json 500 theme={null}
  {
    "error": {
      "code": 500,
      "message": "内部サーバーエラーが発生しました。後でもう一度お試しください",
      "type": "server_error"
    }
  }
  ```

  ```json 502 theme={null}
  {
    "error": {
      "code": 502,
      "message": "不正なゲートウェイです。サーバーが一時的に利用できません",
      "type": "bad_gateway"
    }
  }
  ```
</ResponseExample>

通常のポーリングには統一タスク API を推奨します。

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

統一タスクの状態は `pending` / `processing` / `completed` / `failed` です。成功結果は `result.images[].url` に入ります。

二次操作用に `buttons[].customId` が必要な場合は、MJ 形式の取得を使います。

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

## 状態遷移

```
SUBMITTED → IN_PROGRESS → SUCCESS
                        → FAILURE
                        → MODAL（追加パラメータ要、「インペイント」参照）
```

## レスポンス例

```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` は 2x2 のグリッド画像、`image_urls` は切り出された 4 枚の単画像 URL です。

<Warning>
  **フィールド差異の注意**

  * `/v1/tasks/{task_id}` は統一された `pending` / `processing` / `completed` / `failed` 状態を返します。
  * `/v1/midjourney/{task_id}` は `grid_image_url`、`image_urls`、`buttons` などの MJ 形式フィールドを返します。
</Warning>

**`buttons` について：** 多くの二次操作は `index`、`direction`、`zoom_ratio` から該当する `customId` を自動解決します。自動マッチングに失敗する場合は `custom_id` を直接渡してください。

## ステータス一覧

| status        | 意味                                       | 終端  |
| ------------- | ---------------------------------------- | --- |
| `NOT_START`   | 行作成済み、システム未確認（一時的）                       | いいえ |
| `SUBMITTED`   | システムが受理、キュー待ち                            | いいえ |
| `IN_PROGRESS` | システムが処理中                                 | いいえ |
| `MODAL`       | `/modal` のパラメータ待ち（Inpaint 参照）            | いいえ |
| `SUCCESS`     | 完了                                       | ✓   |
| `FAILURE`     | 失敗 → 自動返金（`quota` → 0、`fail_reason` に原因） | ✓   |

## クエリの注意

* クエリ エンドポイントは**個別課金されません**が、頻度は適度に（3〜5s のポーリング推奨）。
* 一般ユーザーは自分のタスクのみ照会可能。他人のタスクは `403` を返します。
* タスクは既定で **3 日間**保持され、その後の照会は `404` を返しますが、生成された画像 / 動画 URL は引き続きアクセス可能です。

## 上級：`custom_id` で直接操作

`buttons[].customId` を読み取った後、二次操作エンドポイントの `custom_id` フィールドに直接渡すことで自動マッチングをスキップできます：

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