PopNowAPI 文档
开始使用
正文

快速开始

创建 API 密钥,提交第一个图像生成请求,再获取生成结果。

本指南带你完成 API 密钥创建、图像生成任务提交和结果获取。图像、视频和音频生成共用媒体任务的请求结构:指定 model 及其对应的 input。文件上传和 Webhook 通知的用法分别见各自的文档。

开始之前

  • 一个 PopNow 账户。 在 popnow.ai 注册。API 调用使用你的 PopNow 余额,按美元显示;新账户初始为 $0。请先在 API 账单充值,再发起第一次付费调用。
  • 一个能运行 curl 的终端。 示例用的是 bash;Windows 请用 WSL 或 Git Bash。

1. 创建 API 密钥

打开 API 控制台,选择 Create key。请立即复制密钥:完整值只显示一次。将它保存在环境变量中,不要直接写进代码:

export POPNOW_API_KEY="sk-popnow-..."

每个密钥都以 sk-popnow- 开头,通过它发起的请求使用你的 API 美元余额。密钥仅保存在服务器端;使用限制、密钥轮换和泄露后的处理方式,见鉴权。

2. 提交任务

将以下示例粘贴到同一个终端。它使用一个速度较快的图像模型生成一张图,费用约为 $0.01 USD(1 美分):

POST /api/v1/jobs/createTask?wait=60
export POPNOW_API_KEY="sk-popnow-..."   # your key from the API console

curl -X POST "https://api.popnow.ai/api/v1/jobs/createTask?wait=60" \
  -H "Authorization: Bearer $POPNOW_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
  "model": "alibaba/z-image-turbo/text-to-image",
  "input": {
    "prompt": "A small red fox curled up in a teacup, soft morning light, studio photo"
  }
}'

各部分的作用:

  • model 标识要使用的模型和任务类型。可用的 ID 见模型页。
  • input 按所选模型的输入 schema 校验。未定义的字段会被拒绝,因此字段名称拼写错误会直接报错,不会被忽略。
  • Idempotency-Key 让重试变得安全:超时后用同一个键再发一次,拿回的是原来那个任务,不会重复扣费。见幂等。
  • ?wait=60 让连接最多保持 60 秒。如果任务在这段时间内完成,可以在同一个响应中获取结果。

3. 读取结果

任务完成后的响应示例:

200 · recordInfo / createTask?wait=60
{
  "code": 200,
  "msg": "success",
  "data": {
    "taskId": "job_01JH8Z4Q5W2N7R3K9M6P1C0VXD",
    "model": "alibaba/z-image-turbo/text-to-image",
    "state": "succeeded",
    "output": {
      "assets": [
        {
          "url": "https://…signed-link…",
          "expiresAt": "2026-10-16T09:20:00Z",
          "mime": "image/png",
          "width": 1024,
          "height": 1024
        }
      ]
    },
    "costUsd": "0.01",
    "settled": true
  },
  "request_id": "req_…"
}
A small red fox curled up in a teacup, soft morning light, studio photo
output.assets[0].url
  • state 是 succeeded。没能完成的任务会显示 failed,并带上 errorCode,见错误码。
  • output.assets[0].url 是文件的签名链接,有效期约 20 分钟,下载时不需要 API 密钥。重新查询任务可以请求新的链接。
  • 金额以 costUsd 这个美元十进制字符串为准:settled 为 true 时是最终扣费,settled 为 false 时是冻结金额。响应中可能仍有兼容用的旧整数金额字段,请忽略它们。

如果任务耗时超过 60 秒,接口会返回 202,其中包含 state: "queued" 和 taskId。接着查询任务,直到进入最终状态:

curl "https://api.popnow.ai/api/v1/jobs/recordInfo?taskId=job_..." \
  -H "Authorization: Bearer $POPNOW_API_KEY"

每隔几秒查询一次,直到 state 变成 succeeded、failed 或 expired。在生产环境中,建议传入 callBackUrl,通过 Webhook 接收通知。

用代码发同一个请求

JavaScript (Node.js 18+)
const API = 'https://api.popnow.ai/api/v1';
const headers = {
  Authorization: `Bearer ${process.env.POPNOW_API_KEY}`,
  'Content-Type': 'application/json',
};

const created = await fetch(`${API}/jobs/createTask`, {
  method: 'POST',
  headers: { ...headers, 'Idempotency-Key': crypto.randomUUID() },
  body: JSON.stringify({
    model: 'alibaba/z-image-turbo/text-to-image',
    input: { prompt: 'A small red fox curled up in a teacup, soft morning light' },
  }),
}).then((r) => r.json());
if (created.code !== 200) throw new Error(`${created.code} ${created.msg}`);

// Poll until the task reaches a final state.
let task;
do {
  await new Promise((r) => setTimeout(r, 3000));
  const res = await fetch(`${API}/jobs/recordInfo?taskId=${created.data.taskId}`, { headers });
  task = (await res.json()).data;
} while (task.state === 'queued' || task.state === 'running');

console.log(task.state, task.output?.assets?.[0]?.url);
Python (requests)
import os, time, uuid, requests

API = "https://api.popnow.ai/api/v1"
headers = {"Authorization": f"Bearer {os.environ['POPNOW_API_KEY']}"}

created = requests.post(
    f"{API}/jobs/createTask",
    headers={**headers, "Idempotency-Key": str(uuid.uuid4())},
    json={
        "model": "alibaba/z-image-turbo/text-to-image",
        "input": {"prompt": "A small red fox curled up in a teacup, soft morning light"},
    },
    timeout=30,
).json()
if created["code"] != 200:
    raise RuntimeError(f'{created["code"]} {created["msg"]}')

# Poll until the task reaches a final state.
while True:
    time.sleep(3)
    task = requests.get(
        f"{API}/jobs/recordInfo",
        headers=headers,
        params={"taskId": created["data"]["taskId"]},
        timeout=30,
    ).json()["data"]
    if task["state"] not in ("queued", "running"):
        break

print(task["state"], task.get("output", {}).get("assets", [{}])[0].get("url"))

用官方 SDK。 Python 与 JavaScript SDK 会替你带上幂等键并轮询结果。它们已发布到 PyPI 和 npm,用下面的命令安装:

pip install popnow
npm install popnow
Python (popnow SDK)
from popnow import PopNow

client = PopNow()  # reads POPNOW_API_KEY

task = client.images.generate(
    model="alibaba/z-image-turbo/text-to-image",
    prompt="A small red fox curled up in a teacup, soft morning light",
)
print(task.state, task.urls[0])
JavaScript (popnow SDK)
import { PopNow } from 'popnow';

const popnow = new PopNow(); // reads POPNOW_API_KEY

const task = await popnow.jobs.createAndWait({
  model: 'alibaba/z-image-turbo/text-to-image',
  input: { prompt: 'A small red fox curled up in a teacup, soft morning light' },
});
console.log(task.state, task.output?.assets?.[0]?.url);

响应结构

所有 JSON 响应都是这四个字段:

{ "code": 200, "msg": "success", "data": { }, "request_id": "req_…" }

code 是业务码,不是 HTTP 状态码:200 表示成功,其他值都列在错误码页。请按 code 判断,不要按 msg 的文字判断。联系客服时请附上 request_id。

接下来

本页内容