跳至主要內容

尋找下一個工具

說明文件/SDK 與開發人員工具/程式碼範例:Node.js、Python、PHP 和 cURL
SDK 與開發人員工具

程式碼範例:Node.js、Python、PHP 和 cURL

完整、可直接複製的範例,用四種語言提交工作、帶退避地等待工作完成並下載結果。

簡要回答

在每種語言中都是同樣的三個呼叫:攜帶 Idempotency-Key 呼叫 POST /api/v1/jobs/,帶退避地輪詢 GET /api/v1/jobs/{jobId}/,然後下載 output.downloadUrl。下面的範例都是包含逾時和錯誤處理的完整程式;執行前請先在環境中設定 MAXSCANNER_API_KEY。

Node.js(18+)

使用內建的 fetch,因此無需安裝任何套件。

const KEY = process.env.MAXSCANNER_API_KEY;
const BASE = 'https://maxscanner.app/api/v1';
const headers = { Authorization: `Bearer ${KEY}`, 'Content-Type': 'application/json' };

const create = await fetch(`${BASE}/jobs/`, {
  method: 'POST',
  headers: { ...headers, 'Idempotency-Key': 'report-2026-11-pdf' },
  body: JSON.stringify({ url: 'https://example.com/report.docx', filename: 'report.docx', format: 'pdf' }),
});
if (!create.ok) throw new Error(`create failed: ${create.status} ${await create.text()}`);
const { jobId } = await create.json();

let delay = 2000, job;
for (let i = 0; i < 60; i++) {
  job = await (await fetch(`${BASE}/jobs/${jobId}/`, { headers })).json();
  if (job.status === 'completed' || job.status === 'failed') break;
  await new Promise((r) => setTimeout(r, delay));
  delay = Math.min(delay * 1.5, 10000);
}
if (job.status !== 'completed') throw new Error(job.error || 'job did not finish');

const file = await fetch(job.output.downloadUrl);
await (await import('node:fs/promises')).writeFile('report.pdf', Buffer.from(await file.arrayBuffer()));

Python

import os, time, requests

KEY = os.environ["MAXSCANNER_API_KEY"]
BASE = "https://maxscanner.app/api/v1"
S = requests.Session()
S.headers.update({"Authorization": f"Bearer {KEY}"})

r = S.post(f"{BASE}/jobs/", json={"url": "https://example.com/report.docx", "filename": "report.docx", "format": "pdf"},
           headers={"Idempotency-Key": "report-2026-11-pdf"}, timeout=30)
r.raise_for_status()
job_id = r.json()["jobId"]

delay, job = 2.0, {}
for _ in range(60):
    job = S.get(f"{BASE}/jobs/{job_id}/", timeout=30).json()
    if job["status"] in ("completed", "failed"):
        break
    time.sleep(delay)
    delay = min(delay * 1.5, 10)

if job.get("status") != "completed":
    raise RuntimeError(job.get("error") or "job did not finish")
with open("report.pdf", "wb") as fh:
    fh.write(requests.get(job["output"]["downloadUrl"], timeout=60).content)

PHP

<?php
$key = getenv('MAXSCANNER_API_KEY');
$base = 'https://maxscanner.app/api/v1';

function api(string $method, string $url, string $key, ?array $body = null, array $extra = []): array {
  $ch = curl_init($url);
  $headers = array_merge(["Authorization: Bearer $key", 'Content-Type: application/json'], $extra);
  curl_setopt_array($ch, [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => $headers, CURLOPT_TIMEOUT => 30]);
  if ($body !== null) curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
  $data = json_decode(curl_exec($ch), true);
  curl_close($ch);
  return $data ?? [];
}

$job = api('POST', "$base/jobs/", $key, ['url' => 'https://example.com/report.docx', 'filename' => 'report.docx', 'format' => 'pdf'], ['Idempotency-Key: report-2026-11-pdf']);
$delay = 2;
for ($i = 0; $i < 60; $i++) {
  $status = api('GET', "$base/jobs/{$job['jobId']}/", $key);
  if (in_array($status['status'], ['completed', 'failed'], true)) break;
  sleep($delay);
  $delay = min($delay * 2, 10);
}
if ($status['status'] === 'completed') file_put_contents('report.pdf', file_get_contents($status['output']['downloadUrl']));

cURL 與 Shell

需要安裝 jq。在編寫應用程式的程式碼之前,用它測試金鑰或格式非常方便。

JOB=$(curl -s -X POST 'https://maxscanner.app/api/v1/jobs/' \
  -H "Authorization: Bearer $MAXSCANNER_API_KEY" -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: report-2026-11-pdf' \
  -d '{ "url": "https://example.com/report.docx", "filename": "report.docx", "format": "pdf" }' | jq -r .jobId)

until STATUS=$(curl -s "https://maxscanner.app/api/v1/jobs/$JOB/" -H "Authorization: Bearer $MAXSCANNER_API_KEY"); \
      echo "$STATUS" | jq -e '.status == "completed" or .status == "failed"' > /dev/null; do sleep 5; done

curl -s -o report.pdf "$(echo "$STATUS" | jq -r .output.downloadUrl)"

OpenAPI 與 AI 程式設計助理

位於 https://maxscanner.app/openapi/maxscanner-v1.yaml 的 OpenAPI 3.1 描述檔可以配合你常用的產生器產生具型別的用戶端。程式設計助理可以讀取 https://maxscanner.app/llms.txt 和 https://maxscanner.app/ai/api.md,其中總結了相同的端點和規則。

常見問題

有官方 SDK 嗎?

暫時沒有。這個 API 規模不大,上面的範例或根據 OpenAPI 檔案產生的用戶端就足以涵蓋。

相關指南