快速入門
只要五個步驟,就能用 FilesOkay API 壓縮一部影片。每個步驟都提供 curl、Node.js 和 Python 的呼叫方式,以及得到的回應。
本頁內容
- 一個具有有效訂閱的 FilesOkay 工作空間。原因請參閱限制與點數。
- Node.js 步驟需要 Node.js 20 以上版本。Python 步驟需要 Python 3.9 以上版本,以及
requests套件。 - 一部要壓縮的影片。範例中的檔名為
lecture.mp4。
這些步驟會逐步組成一支指令碼。請先寫下這段程式碼,它會從 FILESOKAY_KEY 環境變數讀取您的金鑰:
export FILESOKAY_KEY="filesokay_…"// quickstart.mjs:以 `node quickstart.mjs` 執行(Node.js 20 以上版本)。
import fs from "node:fs";
import https from "node:https";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
const API = "https://api.filesokay.com/v1";
// 呼叫 API;API 拒絕時拋出其錯誤代碼。
async function api(method, path, body, headers = {}) {
const res = await fetch(API + path, {
method,
headers: {
Authorization: `Bearer ${process.env.FILESOKAY_KEY}`,
"Content-Type": "application/json",
...headers,
},
body: body && JSON.stringify(body),
});
const data = res.status === 204 ? null : await res.json();
if (!res.ok) throw new Error(`${data.code}: ${data.detail}`);
return data;
}# quickstart.py:以 `python quickstart.py` 執行(Python 3.9 以上版本,並需先 `pip install requests`)。
import os
import time
import uuid
import requests
API = "https://api.filesokay.com/v1"
def api(method, path, body=None, headers=None):
"""呼叫 API;API 拒絕時引發其錯誤代碼。"""
res = requests.request(
method,
API + path,
json=body,
headers={"Authorization": f"Bearer {os.environ['FILESOKAY_KEY']}", **(headers or {})},
)
data = res.json() if res.content else None
if not res.ok:
raise RuntimeError(f"{data['code']}: {data['detail']}")
return data在工作空間中開啟設定,接著開啟 API 金鑰,然後選取建立 API 金鑰。為金鑰命名並驗證您的身分。金鑰只會顯示一次:請將它複製到 FILESOKAY_KEY。
以檔案的名稱和大小開始上傳。將檔案傳送到傳回的連結,然後完成上傳,系統會在這時檢查檔案。
# 以檔名和大小(位元組)開始上傳。
curl https://api.filesokay.com/v1/uploads \
-H "Authorization: Bearer $FILESOKAY_KEY" \
-H "Content-Type: application/json" \
-d '{
"operation": "video.compress",
"files": [{ "name": "lecture.mp4", "size": 12417467 }]
}'
# 將檔案傳送到其分段連結:回應中的 files[0].parts[0].url。
curl -X PUT --upload-file lecture.mp4 "$PART_URL"
# 完成上傳,此時會檢查檔案。
curl -X POST https://api.filesokay.com/v1/uploads/file_3cf0737aefa34b89b7b4443c9467d60c/complete \
-H "Authorization: Bearer $FILESOKAY_KEY"const name = "lecture.mp4";
const { size } = fs.statSync(name);
// 以檔名和大小(位元組)開始上傳。
const { files: [upload] } = await api("POST", "/uploads", {
operation: "video.compress",
files: [{ name, size }],
});
// 直接從磁碟將檔案傳送到其連結。連結本身帶有權限:不需要金鑰。
await new Promise((resolve, reject) => {
const req = https.request(upload.parts[0].url, {
method: "PUT",
headers: { "Content-Length": size },
});
req.on("response", (res) => {
res.resume();
if (res.statusCode === 200) resolve();
else reject(new Error(`Upload failed: ${res.statusCode}`));
});
req.on("error", reject);
fs.createReadStream(name).on("error", reject).pipe(req);
});
// 完成上傳,此時會檢查檔案。
const uploaded = await api("POST", `/uploads/${upload.id}/complete`);
console.log(uploaded.check.state);name = "lecture.mp4"
# 以檔名和大小(位元組)開始上傳。
upload = api("POST", "/uploads", {
"operation": "video.compress",
"files": [{"name": name, "size": os.path.getsize(name)}],
})["files"][0]
# 直接從磁碟將檔案傳送到其連結。連結本身帶有權限:不需要金鑰。
with open(name, "rb") as f:
requests.put(upload["parts"][0]["url"], data=f).raise_for_status()
# 完成上傳,此時會檢查檔案。
uploaded = api("POST", f"/uploads/{upload['id']}/complete")
print(uploaded["check"]["state"]){
"id": "file_3cf0737aefa34b89b7b4443c9467d60c",
"name": "lecture.mp4",
"operation": "video.compress",
"state": "uploaded",
"size": 12417467,
"created_at": "2026-12-03T08:59:54Z",
"uploaded_at": "2026-12-03T09:00:00Z",
"delete_at": "2026-12-04T09:00:00Z",
"check": {
"state": "proceed",
"kind": "video",
"type": "mp4",
"facts": {
"container": "mp4",
"protection": "none",
"attachments": [],
"duration_ms": 20023,
"frame_count": 600,
"audio_tracks": [
{
"codec": "aac",
"channels": 1,
"sample_rate": 44100
}
],
"video_tracks": [
{
"hdr": "none",
"codec": "h264",
"width": 1280,
"chroma": "420",
"height": 720,
"profile": "High",
"rotation": 0,
"bit_depth": 8,
"frame_rate": 30,
"interlaced": false,
"variable_frame_rate": false
}
],
"data_end_bytes": 12417467,
"subtitle_tracks": []
},
"facts_complete": true
}
}proceed 表示工作可以使用這個檔案。5 GB 以內的檔案只需一次要求即可傳送。較大檔案的傳送方式,請參閱上傳檔案。
指定操作和檔案。未提供的設定會採用預設值;以 video.compress 來說,預設是均衡的品質等級。Idempotency-Key 標頭能讓重試安全無虞,請參閱安全重試。
curl https://api.filesokay.com/v1/jobs \
-H "Authorization: Bearer $FILESOKAY_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: $(uuidgen)" \
-d '{
"operation": "video.compress",
"inputs": [{ "file_id": "file_3cf0737aefa34b89b7b4443c9467d60c" }]
}'const job = await api(
"POST",
"/jobs",
{ operation: "video.compress", inputs: [{ file_id: upload.id }] },
{ "Idempotency-Key": crypto.randomUUID() },
);
console.log(job.id, job.status);job = api(
"POST",
"/jobs",
{"operation": "video.compress", "inputs": [{"file_id": upload["id"]}]},
{"Idempotency-Key": str(uuid.uuid4())},
)
print(job["id"], job["status"]){
"id": "job_a1c9531eeb00434aba0058796f1ca517",
"operation": "video.compress",
"status": "waiting",
"client_reference": null,
"settings": {
"audio": "keep",
"codec": "same",
"level": "balanced",
"method": "quality",
"frame_rate": "original",
"resolution": "original",
"output_format": "same"
},
"created_at": "2026-12-03T09:00:12Z",
"reserved_credits": 2,
"charged_credits": 0,
"tasks": [
{
"id": "task_4256d03a73a741afa1821546a2bcba98",
"status": "waiting",
"progress": 0,
"reserved_credits": 2,
"inputs": [
{
"file_id": "file_3cf0737aefa34b89b7b4443c9467d60c",
"name": "lecture.mp4"
}
],
"outputs": []
}
]
}工作會立即啟動並在背景執行。所需點數會在此時預留,最後只扣除實際用量。
每 5 秒查詢一次工作,直到狀態不再是 waiting 或 processing。在您自己的應用程式中,可以改用 Webhook 在工作結束時通知您,就不必一直查詢。
# 每隔幾秒再查詢一次,直到狀態不再是 waiting 或 processing。
curl https://api.filesokay.com/v1/jobs/job_a1c9531eeb00434aba0058796f1ca517 \
-H "Authorization: Bearer $FILESOKAY_KEY"let current = job;
while (current.status === "waiting" || current.status === "processing") {
await new Promise((resolve) => setTimeout(resolve, 5000));
current = await api("GET", `/jobs/${job.id}`);
}
console.log(current.status);current = job
while current["status"] in ("waiting", "processing"):
time.sleep(5)
current = api("GET", f"/jobs/{job['id']}")
print(current["status"]){
"id": "job_a1c9531eeb00434aba0058796f1ca517",
"operation": "video.compress",
"status": "completed",
"client_reference": null,
"settings": {
"audio": "keep",
"codec": "same",
"level": "balanced",
"method": "quality",
"frame_rate": "original",
"resolution": "original",
"output_format": "same"
},
"created_at": "2026-12-03T09:00:12Z",
"started_at": "2026-12-03T09:00:30Z",
"finished_at": "2026-12-03T09:00:51Z",
"reserved_credits": 2,
"charged_credits": 1,
"tasks": [
{
"id": "task_4256d03a73a741afa1821546a2bcba98",
"status": "completed",
"progress": 100,
"reserved_credits": 2,
"charged_credits": 1,
"inputs": [
{
"file_id": "file_3cf0737aefa34b89b7b4443c9467d60c",
"name": "lecture.mp4"
}
],
"outputs": [
{
"file_id": "file_8dd09e1ec2fb42c1940e4ef92a153a4e",
"name": "lecture-compressed.mp4",
"size": 7268734,
"download_url": "https://…",
"download_expires_at": "2026-12-06T09:00:51Z"
}
]
}
]
}每個已完成的任務都會列出結果,每個結果各附一個連結,下載時會使用該結果的檔名。連結最長有效 7 天,且不需要金鑰。
# 連結位於工作的 tasks[0].outputs[0].download_url,不需要金鑰。
curl -o lecture-compressed.mp4 "$DOWNLOAD_URL"for (const task of current.tasks) {
for (const output of task.outputs) {
const res = await fetch(output.download_url);
if (!res.ok) throw new Error(`${output.name}: ${res.status}`);
await pipeline(Readable.fromWeb(res.body), fs.createWriteStream(output.name));
console.log(`Saved ${output.name}: ${output.size} bytes`);
}
}for task in current["tasks"]:
for output in task["outputs"]:
with requests.get(output["download_url"], stream=True) as res:
res.raise_for_status()
with open(output["name"], "wb") as f:
for chunk in res.iter_content(chunk_size=1 << 20):
f.write(chunk)
print(f"Saved {output['name']}: {output['size']} bytes")在這個範例中,lecture.mp4 從 12.4 MB 縮小到 7.3 MB,花費 1 點。