> ## 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 任务状态与结果。统一任务接口 /v1/tasks/{task_id} 与 MJ 风格接口 /v1/midjourney/{task_id}

```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"))
```

```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": "身份验证失败，请检查您的API密钥",
    "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"
  }
}
```

推荐业务侧轮询统一任务接口：

```
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` 是四宫格合成大图，`image_urls` 是裁剪后的 4 张单图 URL 数组。

> [!WARNING]
>
> **字段差异提醒**
>
> * `/v1/tasks/{task_id}` 返回统一 `pending` / `processing` / `completed` / `failed` 状态。
> * `/v1/midjourney/{task_id}` 返回 MJ 风格字段，如 `grid_image_url`、`image_urls`、`buttons`。

**关于 `buttons`：** 大部分二次操作可传 `index`、`direction` 或 `zoom_ratio`，系统会自动匹配对应 `customId`；如自动匹配失败，可直接传 `custom_id`。

## 状态字段总览

| status | 含义 | 终态 |
| - | - | - |
| `NOT_START` | 已建行，系统未确认（瞬时态） | 否 |
| `SUBMITTED` | 系统接受，排队中 | 否 |
| `IN_PROGRESS` | 系统处理中 | 否 |
| `MODAL` | 等待调 `/modal` 补参（见局部重绘） | 否 |
| `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"
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.