# Upload a video and schedule it

A complete Node.js and Python script that uploads a video from your computer, schedules it on a TikTok account and follows its status.

This script takes a video file on your computer to a scheduled TikTok post in one run: it gets an upload link, uploads the file, schedules the post and follows it until TikTok's scheduler has it. The [Quickstart](/getting-started/quickstart) walks through the same calls one at a time with `curl`.

<Callout type="warn">
There is no test mode. The post goes to TikTok on your real account. Cancel it before it goes out if you don't want it.
</Callout>

## Run it [#run-it]

You need an API key with the `posts:write` and `posts:read` scopes, the `id` of an account that can post (from `GET /accounts`), and an MP4, MOV or WebM video.

```bash
export TIKTORNADO_API_KEY=<your key>
node upload-and-schedule.mjs j971x2c4ajrq0w8sd5e8fxz3a57v2k8m leg-day.mp4 2026-12-02T15:00:00Z "Leg day, no excuses #fitness"
```

The time is ISO 8601 with a time zone, more than 10 minutes from now. It prints the post's id, the time it was saved for and its status:

```text
Saved post k174wq9nrm6t2f0bd3xh8pz5a87v1c2e for 2026-12-02T15:00:00.000Z
Status: scheduled
```

The Python script runs the same way, `python3 upload_and_schedule.py` with the same arguments. It uses only the standard library, so there is nothing to install.

## The code [#the-code]

<Tabs items={["Node.js","Python"]}>
<Tab value="Node.js">
```js title="upload-and-schedule.mjs"
// Upload a video from your computer, schedule it on one TikTok account, and follow its
// status. Node.js 22 or later, nothing to install.
//
//   export TIKTORNADO_API_KEY=<your key>
//   node upload-and-schedule.mjs <accountId> <video> <time> [caption]
//
// <time> is ISO 8601 with a time zone, more than 10 minutes ahead: 2026-12-02T15:00:00Z
import { randomUUID } from "node:crypto";
import { openAsBlob } from "node:fs";
import { basename, extname } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";

const API = process.env.TIKTORNADO_API_URL ?? "https://api.tiktornado.com/api/v1";
const KEY = process.env.TIKTORNADO_API_KEY;
// api() tries a request at most this many times, waiting this long between tries
// unless the answer says how long (Retry-After).
const ATTEMPTS = 5;
const RETRY_WAIT_MS = 5000;
// How often, and how many times, to check the new post's status.
const STATUS_CHECKS = 30;
const STATUS_WAIT_MS = 10_000;
const VIDEO_TYPES = { ".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm" };

class ApiError extends Error {
  constructor(status, error) {
    super(`${status} ${error.reason}: ${error.message}`);
    this.status = status;
    this.reason = error.reason;
  }
}

// One API call. On 429, 409, 5xx or a dropped connection it waits and sends the exact
// same request again, Idempotency-Key and body included, so a change is never made twice.
async function api(method, path, body, idempotencyKey) {
  const headers = { Authorization: `Bearer ${KEY}` };
  if (body !== undefined) headers["Content-Type"] = "application/json";
  if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
  const text = body === undefined ? undefined : JSON.stringify(body);
  for (let attempt = 1; ; attempt++) {
    let res;
    try {
      res = await fetch(API + path, { method, headers, body: text });
    } catch (error) {
      if (attempt === ATTEMPTS) throw error;
      await sleep(RETRY_WAIT_MS);
      continue;
    }
    const answer = await res.json().catch(() => null);
    if (res.ok) return answer;
    const error = answer?.error ?? { reason: "unknown_error", message: `HTTP ${res.status}` };
    if (attempt === ATTEMPTS || !(res.status === 429 || res.status === 409 || res.status >= 500)) throw new ApiError(res.status, error);
    await sleep(res.status === 429 ? Number(res.headers.get("retry-after") ?? 60) * 1000 : RETRY_WAIT_MS);
  }
}

const [accountId, file, scheduledFor, caption = ""] = process.argv.slice(2);
const contentType = VIDEO_TYPES[extname(file ?? "").toLowerCase()];
if (!KEY || !accountId || !file || !scheduledFor || !contentType) {
  console.error("Set TIKTORNADO_API_KEY, then: node upload-and-schedule.mjs <accountId> <video.mp4|.mov|.webm> <time> [caption]");
  process.exit(1);
}

try {
  // An upload link for this one file. It needs no Idempotency-Key: a repeat gives a new link.
  const video = await openAsBlob(file);
  const link = await api("POST", "/uploads", { accountId, filename: basename(file), contentType, size: video.size });

  // The file goes to the link with only the headers the answer lists, never your key.
  const upload = await fetch(link.uploadUrl, { method: link.method, headers: link.headers, body: video });
  if (!upload.ok) throw new Error(`The upload failed with HTTP ${upload.status}. Ask for a new link and try again.`);

  // The post, with a new Idempotency-Key: a retry of this request can't post twice.
  const post = await api("POST", "/posts", { accountId, kind: "video", caption, mediaRefs: [link.mediaRef], scheduledFor }, randomUUID());
  console.log(`Saved post ${post.id} for ${post.scheduledFor}`);

  // scheduling until TikTok's scheduler has the post, then scheduled.
  let current = await api("GET", `/posts/${post.id}`);
  for (let check = 1; current.status === "scheduling" && check <= STATUS_CHECKS; check++) {
    await sleep(STATUS_WAIT_MS);
    current = await api("GET", `/posts/${post.id}`);
  }
  console.log(`Status: ${current.status}`);
  if (current.status === "failed") console.log(`Why: ${current.error.reason}: ${current.error.message}`);
} catch (error) {
  console.error(error.message);
  process.exit(1);
}
```
</Tab>

<Tab value="Python">
```python title="upload_and_schedule.py"
# Upload a video from your computer, schedule it on one TikTok account, and follow its
# status. Python 3.9 or later, standard library only.
#
#   export TIKTORNADO_API_KEY=<your key>
#   python3 upload_and_schedule.py <accountId> <video> <time> [caption]
#
# <time> is ISO 8601 with a time zone, more than 10 minutes ahead: 2026-12-02T15:00:00Z
import json
import os
import sys
import time
import urllib.error
import urllib.request
import uuid

API = os.environ.get("TIKTORNADO_API_URL", "https://api.tiktornado.com/api/v1")
KEY = os.environ.get("TIKTORNADO_API_KEY")
# api() tries a request at most this many times, waiting this long between tries
# unless the answer says how long (Retry-After).
ATTEMPTS = 5
RETRY_WAIT_SECONDS = 5
# How often, and how many times, to check the new post's status.
STATUS_CHECKS = 30
STATUS_WAIT_SECONDS = 10
VIDEO_TYPES = {".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm"}

class ApiError(Exception):
    def __init__(self, status, error):
        super().__init__(f"{status} {error['reason']}: {error['message']}")
        self.status = status
        self.reason = error["reason"]

def api(method, path, body=None, idempotency_key=None):
    """One API call. On 429, 409, 5xx or a dropped connection it waits and sends the exact
    same request again, Idempotency-Key and body included, so a change is never made twice."""
    headers = {"Authorization": f"Bearer {KEY}"}
    if body is not None:
        headers["Content-Type"] = "application/json"
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key
    data = None if body is None else json.dumps(body).encode()
    for attempt in range(1, ATTEMPTS + 1):
        request = urllib.request.Request(API + path, data=data, method=method, headers=headers)
        try:
            with urllib.request.urlopen(request, timeout=60) as res:
                return json.load(res)
        except urllib.error.HTTPError as res:
            try:
                error = json.load(res)["error"]
            except (ValueError, KeyError):
                error = {"reason": "unknown_error", "message": f"HTTP {res.code}"}
            if attempt == ATTEMPTS or not (res.code in (409, 429) or res.code >= 500):
                raise ApiError(res.code, error) from None
            time.sleep(int(res.headers.get("Retry-After", "60")) if res.code == 429 else RETRY_WAIT_SECONDS)
        except OSError:
            if attempt == ATTEMPTS:
                raise
            time.sleep(RETRY_WAIT_SECONDS)

def main(account_id, path, scheduled_for, caption=""):
    content_type = VIDEO_TYPES[os.path.splitext(path)[1].lower()]
    size = os.path.getsize(path)

    # An upload link for this one file. It needs no Idempotency-Key: a repeat gives a new link.
    link = api("POST", "/uploads", {"accountId": account_id, "filename": os.path.basename(path), "contentType": content_type, "size": size})

    # The file goes to the link with only the headers the answer lists, never your key.
    with open(path, "rb") as video:
        headers = {**link["headers"], "Content-Length": str(size)}
        urllib.request.urlopen(urllib.request.Request(link["uploadUrl"], data=video, method=link["method"], headers=headers), timeout=600).close()

    # The post, with a new Idempotency-Key: a retry of this request can't post twice.
    body = {"accountId": account_id, "kind": "video", "caption": caption, "mediaRefs": [link["mediaRef"]], "scheduledFor": scheduled_for}
    post = api("POST", "/posts", body, str(uuid.uuid4()))
    print(f"Saved post {post['id']} for {post['scheduledFor']}")

    # scheduling until TikTok's scheduler has the post, then scheduled.
    current = api("GET", f"/posts/{post['id']}")
    for _ in range(STATUS_CHECKS):
        if current["status"] != "scheduling":
            break
        time.sleep(STATUS_WAIT_SECONDS)
        current = api("GET", f"/posts/{post['id']}")
    print(f"Status: {current['status']}")
    if current["status"] == "failed":
        print(f"Why: {current['error']['reason']}: {current['error']['message']}")

if __name__ == "__main__":
    args = sys.argv[1:]
    if not KEY or not 3 <= len(args) <= 4 or os.path.splitext(args[1])[1].lower() not in VIDEO_TYPES:
        sys.exit("Set TIKTORNADO_API_KEY, then: python3 upload_and_schedule.py <accountId> <video.mp4|.mov|.webm> <time> [caption]")
    try:
        main(*args)
    except (ApiError, OSError) as error:
        sys.exit(str(error))
```
</Tab>
</Tabs>

## How it works [#how-it-works]

- **The upload link.** `POST /uploads` takes the file's name, type and size in bytes, and answers an `uploadUrl` and a `mediaRef`. It needs no `Idempotency-Key`: asking again simply gives a new link.
- **The upload.** The file goes to `uploadUrl` with an HTTP `PUT` and only the headers the answer lists. Your API key never goes there. The link expires, so upload soon after you get it, and post soon after you upload.
- **The post.** `POST /posts` with the `mediaRef` and a new `Idempotency-Key`. On a `429`, `409`, `5xx` or a dropped connection, `api()` waits and sends the same request again with the same key, so the post is never made twice. See [Safe retries](/getting-started/idempotency).
- **The status.** The answer's status is `scheduling` until TikTok's scheduler has the post. The script reads the post with `GET /posts/{postId}` every 10 seconds until it isn't. Once it is `scheduled` it goes out at its time: `publishing`, then `published`. See [Post statuses](/posting/post-statuses).

## What can go wrong [#what-can-go-wrong]

The script prints the refusal's status, `reason` and `message`, and exits with an error.

| Reason | What to do |
| --- | --- |
| `schedule_too_soon` | Pick a time more than 10 minutes from now |
| `daily_limit_reached` | The account already has 15 videos in some 24 hours around that time. Pick another time |
| `past_account_end` | The account ends before that time. Pick an earlier one |
| `file_type_not_supported`, `file_too_large` | Use an MP4, MOV or WebM video up to 4 GB |
| `link_unreachable`, `file_damaged` | The uploaded file couldn't be read. Check the upload finished, or export the video again and upload it again |
| `upload_expired` | Upload the file again, then schedule it soon after |
| `account_not_ready`, `invalid_state` | The account can't take posts right now. Check its status with `GET /accounts` |
| `api_scope_missing` | The key needs `posts:write` and `posts:read` |
| `slow_down` | `api()` waits the `Retry-After` seconds and tries again. See [Rate limits](/getting-started/rate-limits) |

Every reason is on [Errors](/getting-started/errors).