开发文档 · SDK 示例
SDK 示例
Python、Java、JavaScript 全流程示例与 SDK 生成。
完整调用示例
以下示例覆盖「上传 → 提交 → 轮询 → 取结果」全流程,可直接用于项目集成。各语言要点相同:统一携带 X-Aistrong-Key,先判断 success,异步任务按 poll_after_ms 轮询。
import time
import requests
class DocuClient:
def __init__(self, base_url: str, api_key: str, timeout: int = 60):
self.base = base_url.rstrip("/") + "/open/v1"
self.session = requests.Session()
self.session.headers["X-Aistrong-Key"] = api_key
self.timeout = timeout
def _unwrap(self, response: requests.Response) -> dict:
payload = response.json()
if not payload.get("success"):
error = payload.get("error") or {}
raise RuntimeError(f"{response.status_code} {error.get('code')}: {error.get('message')}")
return payload["data"]
def upload(self, path: str, client_request_id: str) -> int:
with open(path, "rb") as fh:
response = self.session.post(f"{self.base}/documents", files={"file": fh},
data={"client_request_id": client_request_id}, timeout=self.timeout)
return self._unwrap(response)["doc_id"]
def submit(self, action: str, body: dict) -> str:
response = self.session.post(f"{self.base}/{action}", json=body, timeout=self.timeout)
return self._unwrap(response)["job_id"]
def wait(self, job_id: str, max_seconds: int = 600) -> dict:
deadline = time.monotonic() + max_seconds
while time.monotonic() < deadline:
job = self._unwrap(self.session.get(f"{self.base}/job/{job_id}", timeout=self.timeout))
if job["status"] == "succeeded":
return self._unwrap(self.session.get(f"{self.base}/job/{job_id}/result", timeout=self.timeout))
if job["status"] in ("failed", "cancelled"):
raise RuntimeError(job["error"])
time.sleep(job["poll_after_ms"] / 1000)
raise TimeoutError(job_id)
client = DocuClient("https://<host>", "<API Key>")
doc_a = client.upload("a.pdf", "upload-a")
doc_b = client.upload("b.pdf", "upload-b")
job_id = client.submit("documents:merge", {"doc_ids": [doc_a, doc_b], "client_request_id": "merge-0001"})
print(client.wait(job_id))HttpClient http = HttpClient.newHttpClient();
String base = "https://<host>/open/v1";
String key = "<API Key>";
HttpRequest submit = HttpRequest.newBuilder(URI.create(base + "/documents:merge"))
.header("X-Aistrong-Key", key)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(
"{\"doc_ids\": [1001, 1002], \"client_request_id\": \"merge-0001\"}"))
.build();
HttpResponse<String> accepted = http.send(submit, HttpResponse.BodyHandlers.ofString());
// accepted.statusCode() == 202,data.job_id 在响应体里;随后轮询:
HttpRequest poll = HttpRequest.newBuilder(URI.create(base + "/job/" + jobId))
.header("X-Aistrong-Key", key).GET().build();const BASE = "https://<host>/open/v1";
const HEADERS = { "X-Aistrong-Key": "<API Key>" };
async function unwrap(response) {
const payload = await response.json();
if (!payload.success) throw new Error(`${response.status} ${payload.error.code}: ${payload.error.message}`);
return payload.data;
}
async function waitJob(jobId) {
for (;;) {
const job = await unwrap(await fetch(`${BASE}/job/${jobId}`, { headers: HEADERS }));
if (job.status === "succeeded") return unwrap(await fetch(`${BASE}/job/${jobId}/result`, { headers: HEADERS }));
if (job.status === "failed" || job.status === "cancelled") throw new Error(JSON.stringify(job.error));
await new Promise((r) => setTimeout(r, job.poll_after_ms));
}
}
const accepted = await unwrap(await fetch(`${BASE}/documents:merge`, {
method: "POST",
headers: { ...HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({ doc_ids: [1001, 1002], client_request_id: "merge-0001" }),
}));
console.log(await waitJob(accepted.job_id));生成 SDK
OpenAPI 3 文档可直接导入 Postman / Apifox,或用 openapi-generator 生成任意语言的客户端:
curl -o docu-open-v1.json 'https://<host>/v3/api-docs/open-v1'
openapi-generator-cli generate -i docu-open-v1.json -g python -o ./docu-sdk