> ## 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"
}
```
