본문 바로가기

메뉴

  • 미디어
  • 요금제
  • 개발자 문서
  • 언어: 한국어

    회색으로 표시된 언어로는 이 페이지가 제공되지 않습니다.

    • English
    • Español
    • Português
    • Français
    • Deutsch
    • Italiano
    • Nederlands
    • Polski
    • 日本語
    • 한국어
    • Bahasa Indonesia
    • Tiếng Việt
    • Türkçe
    • العربية
    • ไทย
    • Български
    • Català
    • Hrvatski
    • Eesti
    • Magyar
    • Latviešu
    • Lietuvių
    • Srpski
    • Slovenčina
    • Slovenščina
    • Українська
    • Čeština
    • Română
    • Svenska
    • Dansk
    • Norsk bokmål
    • Suomi
    • עברית
    • हिन्दी
    • Tagalog
    • Bahasa Melayu
    • Ελληνικά
    • 简体中文
    • 繁體中文

빠른 시작

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를 호출하고, 요청이 거부되면 해당 오류 코드로 예외를 던집니다.
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를 호출하고, 요청이 거부되면 해당 오류 코드로 예외를 발생시킵니다."""
    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

1. API 키 만들기

워크스페이스의 설정에서 API 키를 열고 API 키 만들기를 선택하세요. 키 이름을 정하고 본인 확인을 마치면 키가 한 번만 표시됩니다. 이 키를 FILESOKAY_KEY에 복사해 두세요.

2. 파일 업로드하기

파일 이름과 크기로 업로드를 시작합니다. 응답으로 받은 링크에 파일을 보낸 다음 업로드를 완료하면 파일 검사가 진행됩니다.

# 파일 이름과 크기(바이트)로 업로드를 시작합니다.
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는 작업에서 이 파일을 사용할 수 있다는 뜻입니다. 5GB 이하 파일은 요청 한 번으로 보낼 수 있습니다. 더 큰 파일을 보내는 방법은 파일 업로드를 참고하세요.

3. 작업 시작하기

오퍼레이션과 파일을 지정합니다. 생략한 설정에는 기본값이 적용되며, 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": []
    }
  ]
}

작업은 즉시 시작되어 백그라운드에서 실행됩니다. 이 시점에 크레딧이 예약되고, 실제로는 사용한 만큼만 차감됩니다.

4. 작업이 끝날 때까지 기다리기

작업 상태가 waiting이나 processing이 아닐 때까지 5초마다 작업을 조회합니다. 실제 앱에서는 웹훅으로 작업 종료 알림을 받을 수 있으므로 계속 조회할 필요가 없습니다.

# 상태가 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"
        }
      ]
    }
  ]
}

5. 결과 다운로드하기

완료된 태스크마다 결과 목록이 있고, 결과마다 해당 파일 이름 그대로 내려받을 수 있는 링크가 함께 제공됩니다. 링크는 최대 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.4MB에서 7.3MB로 줄었고, 1크레딧이 사용되었습니다.

다음 단계

  • 작업 실행

    설정, 견적, 일괄 처리, 상태를 알아봅니다.

  • 웹훅

    반복 조회는 그만하고, 작업이 끝나면 서명된 메시지를 받으세요.

  • 오류 코드

    모든 오류를 코드별로 처리하세요.