Code examples
View as MarkdownOne complete program, in eight languages, that makes a video from start to finish. Copy it, set your key, run it, and you get hello.mp4.
Before you run it
Set your API key (create a key in the console):
export BLITFRAME_API_KEY=blitframe_...
| What | Detail |
|---|---|
| Address | The program calls https://blitframe.codeartworks.com/v1, or the address in BLITFRAME when it is set, as on every other page. It needs no other variable. |
| The video | 3 seconds at 1280×720, which the free trial allows. On the trial it carries a small watermark. |
| Errors | If a request fails, the program stops with the API's error code and message. |
Blitframe is plain JSON over HTTPS, so any language with an HTTP client works. The API reference has a page for every endpoint, with its request in curl, Python, Node.js, PHP, Ruby, Go, C# and Java. To have an AI agent do this instead, connect it over MCP.
The program
The program:
- Creates a project.
- Edits it to add a small
data.json(a blue plate on a dark background), which creates its first version. - Renders the project as an MP4 and waits until it finishes.
- Downloads the video to
hello.mp4.
The comment at the top of each language says what it needs and how to run it.
# Needs curl and jq. Save as render.sh and run: bash render.sh
set -euo pipefail
API="${BLITFRAME:-https://blitframe.codeartworks.com/v1}"
call() {
local method=$1 path=$2 response status
shift 2
# Any further arguments carry a JSON body.
if [ $# -gt 0 ]; then set -- -H "Content-Type: application/json" "$@"; fi
response=$(curl -sS -X "$method" "$API$path" -w '\n%{http_code}' \
-H "Authorization: Bearer $BLITFRAME_API_KEY" "$@") || return 1
status=${response##*$'\n'}
response=${response%$'\n'*}
if [ "$status" -ge 400 ]; then
echo "$status $(jq -r '"\(.error.code): \(.error.message)"' <<<"$response")" >&2
return 1
fi
printf '%s\n' "$response"
}
# A 3-second 720p composition: a dark background with a blue rounded plate.
COMPOSITION=$(cat <<'JSON'
{"v": "5.12.2", "nm": "Hello Blitframe", "fr": 30, "ip": 0, "op": 90, "w": 1280, "h": 720, "ddd": 0, "assets": [],
"layers": [
{"ty": 4, "ind": 1, "nm": "Plate", "ip": 0, "op": 90, "st": 0, "sr": 1,
"ks": {"a": {"a": 0, "k": [0, 0, 0]}, "p": {"a": 0, "k": [640, 360, 0]}, "s": {"a": 0, "k": [100, 100, 100]},
"r": {"a": 0, "k": 0}, "o": {"a": 0, "k": 100}},
"shapes": [{"ty": "gr", "nm": "Plate", "it": [
{"ty": "rc", "d": 1, "p": {"a": 0, "k": [0, 0]}, "s": {"a": 0, "k": [800, 300]}, "r": {"a": 0, "k": 32}},
{"ty": "fl", "c": {"a": 0, "k": [0.1, 0.3, 0.8, 1]}, "o": {"a": 0, "k": 100}, "r": 1},
{"ty": "tr", "p": {"a": 0, "k": [0, 0]}, "a": {"a": 0, "k": [0, 0]}, "s": {"a": 0, "k": [100, 100]},
"r": {"a": 0, "k": 0}, "o": {"a": 0, "k": 100}}]}]},
{"ty": 1, "ind": 2, "nm": "Background", "ip": 0, "op": 90, "st": 0, "sr": 1,
"ks": {"a": {"a": 0, "k": [0, 0, 0]}, "p": {"a": 0, "k": [0, 0, 0]}, "s": {"a": 0, "k": [100, 100, 100]},
"r": {"a": 0, "k": 0}, "o": {"a": 0, "k": 100}},
"sw": 1280, "sh": 720, "sc": "#101725"}]}
JSON
)
PROJECT=$(call POST /projects -d '{"name":"Hello Blitframe"}')
PROJECT_ID=$(jq -r .id <<<"$PROJECT")
VERSION=$(jq -n --arg content "$COMPOSITION" \
'{message: "First version", files: [{path: "data.json", content: $content}]}' \
| call POST "/projects/$PROJECT_ID/versions" -d @-)
VERSION_ID=$(jq -r .id <<<"$VERSION")
if [ "$(jq -r .renderable <<<"$VERSION")" != true ]; then
echo "Not renderable: $(jq -r '.problems | join("; ")' <<<"$VERSION")" >&2
exit 1
fi
RENDER=$(call POST /renders -H "Idempotency-Key: hello-$VERSION_ID" \
-d "{\"projectId\":\"$PROJECT_ID\",\"format\":\"mp4\"}")
RENDER_ID=$(jq -r .id <<<"$RENDER")
STATUS=$(jq -r .status <<<"$RENDER")
while [ "$STATUS" = queued ] || [ "$STATUS" = rendering ]; do
sleep 2
RENDER=$(call GET "/renders/$RENDER_ID")
STATUS=$(jq -r .status <<<"$RENDER")
done
if [ "$STATUS" != succeeded ]; then
echo "Render $STATUS: $(jq -r '"\(.error.code): \(.error.message)"' <<<"$RENDER")" >&2
exit 1
fi
curl -sSf -o hello.mp4 "$(jq -r .output.mp4Url <<<"$RENDER")"
echo "Saved hello.mp4 ($(jq -r .chargedSeconds <<<"$RENDER") render seconds)"
# Needs Python 3.9 or later and requests (pip install requests). Save as render.py and run: python render.py
import json
import os
import time
import requests
API = os.environ.get("BLITFRAME", "https://blitframe.codeartworks.com/v1")
session = requests.Session()
session.headers["Authorization"] = "Bearer " + os.environ["BLITFRAME_API_KEY"]
def call(method, path, **kwargs):
response = session.request(method, API + path, **kwargs)
if not response.ok:
error = response.json()["error"]
raise RuntimeError(f"{response.status_code} {error['code']}: {error['message']}")
return response.json() if response.content else None
# A 3-second 720p composition: a dark background with a blue rounded plate.
composition = {
"v": "5.12.2", "nm": "Hello Blitframe", "fr": 30, "ip": 0, "op": 90, "w": 1280, "h": 720, "ddd": 0, "assets": [],
"layers": [
{"ty": 4, "ind": 1, "nm": "Plate", "ip": 0, "op": 90, "st": 0, "sr": 1,
"ks": {"a": {"a": 0, "k": [0, 0, 0]}, "p": {"a": 0, "k": [640, 360, 0]}, "s": {"a": 0, "k": [100, 100, 100]},
"r": {"a": 0, "k": 0}, "o": {"a": 0, "k": 100}},
"shapes": [{"ty": "gr", "nm": "Plate", "it": [
{"ty": "rc", "d": 1, "p": {"a": 0, "k": [0, 0]}, "s": {"a": 0, "k": [800, 300]}, "r": {"a": 0, "k": 32}},
{"ty": "fl", "c": {"a": 0, "k": [0.1, 0.3, 0.8, 1]}, "o": {"a": 0, "k": 100}, "r": 1},
{"ty": "tr", "p": {"a": 0, "k": [0, 0]}, "a": {"a": 0, "k": [0, 0]}, "s": {"a": 0, "k": [100, 100]},
"r": {"a": 0, "k": 0}, "o": {"a": 0, "k": 100}}]}]},
{"ty": 1, "ind": 2, "nm": "Background", "ip": 0, "op": 90, "st": 0, "sr": 1,
"ks": {"a": {"a": 0, "k": [0, 0, 0]}, "p": {"a": 0, "k": [0, 0, 0]}, "s": {"a": 0, "k": [100, 100, 100]},
"r": {"a": 0, "k": 0}, "o": {"a": 0, "k": 100}},
"sw": 1280, "sh": 720, "sc": "#101725"},
],
}
project = call("POST", "/projects", json={"name": "Hello Blitframe"})
version = call("POST", f"/projects/{project['id']}/versions", json={
"message": "First version",
"files": [{"path": "data.json", "content": json.dumps(composition)}],
})
if not version["renderable"]:
raise RuntimeError("Not renderable: " + "; ".join(version["problems"]))
render = call("POST", "/renders", json={"projectId": project["id"], "format": "mp4"},
headers={"Idempotency-Key": f"hello-{version['id']}"})
while render["status"] in ("queued", "rendering"):
time.sleep(2)
render = call("GET", f"/renders/{render['id']}")
if render["status"] != "succeeded":
error = render["error"] or {}
raise RuntimeError(f"Render {render['status']}: {error.get('code')}: {error.get('message')}")
with open("hello.mp4", "wb") as file:
file.write(requests.get(render["output"]["mp4Url"]).content)
print(f"Saved hello.mp4 ({render['chargedSeconds']} render seconds)")
// Needs Node.js 18 or later and no packages. Save as render.mjs and run: node render.mjs
import { writeFile } from "node:fs/promises";
const API = process.env.BLITFRAME ?? "https://blitframe.codeartworks.com/v1";
const headers = { Authorization: `Bearer ${process.env.BLITFRAME_API_KEY}` };
async function call(method, path, body, extraHeaders = {}) {
const json = body === undefined ? {} : { "Content-Type": "application/json" };
const response = await fetch(API + path, {
method,
headers: { ...headers, ...json, ...extraHeaders },
body: body === undefined ? undefined : JSON.stringify(body),
});
const data = response.status === 204 ? null : await response.json();
if (!response.ok) throw new Error(`${response.status} ${data.error.code}: ${data.error.message}`);
return data;
}
const transform = (x, y) => ({
a: { a: 0, k: [0, 0, 0] }, p: { a: 0, k: [x, y, 0] }, s: { a: 0, k: [100, 100, 100] },
r: { a: 0, k: 0 }, o: { a: 0, k: 100 },
});
// A 3-second 720p composition: a dark background with a blue rounded plate.
const composition = {
v: "5.12.2", nm: "Hello Blitframe", fr: 30, ip: 0, op: 90, w: 1280, h: 720, ddd: 0, assets: [],
layers: [
{
ty: 4, ind: 1, nm: "Plate", ip: 0, op: 90, st: 0, sr: 1, ks: transform(640, 360),
shapes: [{
ty: "gr", nm: "Plate", it: [
{ ty: "rc", d: 1, p: { a: 0, k: [0, 0] }, s: { a: 0, k: [800, 300] }, r: { a: 0, k: 32 } },
{ ty: "fl", c: { a: 0, k: [0.1, 0.3, 0.8, 1] }, o: { a: 0, k: 100 }, r: 1 },
{ ty: "tr", p: { a: 0, k: [0, 0] }, a: { a: 0, k: [0, 0] }, s: { a: 0, k: [100, 100] }, r: { a: 0, k: 0 }, o: { a: 0, k: 100 } },
],
}],
},
{ ty: 1, ind: 2, nm: "Background", ip: 0, op: 90, st: 0, sr: 1, ks: transform(0, 0), sw: 1280, sh: 720, sc: "#101725" },
],
};
const project = await call("POST", "/projects", { name: "Hello Blitframe" });
const version = await call("POST", `/projects/${project.id}/versions`, {
message: "First version",
files: [{ path: "data.json", content: JSON.stringify(composition) }],
});
if (!version.renderable) throw new Error("Not renderable: " + version.problems.join("; "));
let render = await call("POST", "/renders", { projectId: project.id, format: "mp4" }, { "Idempotency-Key": `hello-${version.id}` });
while (render.status === "queued" || render.status === "rendering") {
await new Promise((resolve) => setTimeout(resolve, 2000));
render = await call("GET", `/renders/${render.id}`);
}
if (render.status !== "succeeded") throw new Error(`Render ${render.status}: ${render.error?.code}: ${render.error?.message}`);
const video = await fetch(render.output.mp4Url);
await writeFile("hello.mp4", Buffer.from(await video.arrayBuffer()));
console.log(`Saved hello.mp4 (${render.chargedSeconds} render seconds)`);
<?php
// Needs PHP 8.1 or later with the curl extension. Save as render.php and run: php render.php
$api = getenv("BLITFRAME") ?: "https://blitframe.codeartworks.com/v1";
$key = getenv("BLITFRAME_API_KEY");
function call(string $method, string $path, ?array $body = null, array $headers = []): ?array
{
global $api, $key;
$headers[] = "Authorization: Bearer $key";
$curl = curl_init($api . $path);
curl_setopt_array($curl, [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true]);
if ($body !== null) {
$headers[] = "Content-Type: application/json";
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($body));
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$text = curl_exec($curl);
if ($text === false) {
throw new RuntimeException(curl_error($curl));
}
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$data = json_decode($text, true);
if ($status >= 400) {
throw new RuntimeException("$status {$data['error']['code']}: {$data['error']['message']}");
}
return $data;
}
// A 3-second 720p composition: a dark background with a blue rounded plate.
$composition = <<<'JSON'
{"v": "5.12.2", "nm": "Hello Blitframe", "fr": 30, "ip": 0, "op": 90, "w": 1280, "h": 720, "ddd": 0, "assets": [],
"layers": [
{"ty": 4, "ind": 1, "nm": "Plate", "ip": 0, "op": 90, "st": 0, "sr": 1,
"ks": {"a": {"a": 0, "k": [0, 0, 0]}, "p": {"a": 0, "k": [640, 360, 0]}, "s": {"a": 0, "k": [100, 100, 100]},
"r": {"a": 0, "k": 0}, "o": {"a": 0, "k": 100}},
"shapes": [{"ty": "gr", "nm": "Plate", "it": [
{"ty": "rc", "d": 1, "p": {"a": 0, "k": [0, 0]}, "s": {"a": 0, "k": [800, 300]}, "r": {"a": 0, "k": 32}},
{"ty": "fl", "c": {"a": 0, "k": [0.1, 0.3, 0.8, 1]}, "o": {"a": 0, "k": 100}, "r": 1},
{"ty": "tr", "p": {"a": 0, "k": [0, 0]}, "a": {"a": 0, "k": [0, 0]}, "s": {"a": 0, "k": [100, 100]},
"r": {"a": 0, "k": 0}, "o": {"a": 0, "k": 100}}]}]},
{"ty": 1, "ind": 2, "nm": "Background", "ip": 0, "op": 90, "st": 0, "sr": 1,
"ks": {"a": {"a": 0, "k": [0, 0, 0]}, "p": {"a": 0, "k": [0, 0, 0]}, "s": {"a": 0, "k": [100, 100, 100]},
"r": {"a": 0, "k": 0}, "o": {"a": 0, "k": 100}},
"sw": 1280, "sh": 720, "sc": "#101725"}]}
JSON;
$project = call("POST", "/projects", ["name" => "Hello Blitframe"]);
$version = call("POST", "/projects/{$project['id']}/versions", [
"message" => "First version",
"files" => [["path" => "data.json", "content" => $composition]],
]);
if (!$version["renderable"]) {
throw new RuntimeException("Not renderable: " . implode("; ", $version["problems"]));
}
$render = call("POST", "/renders", ["projectId" => $project["id"], "format" => "mp4"],
["Idempotency-Key: hello-{$version['id']}"]);
while (in_array($render["status"], ["queued", "rendering"])) {
sleep(2);
$render = call("GET", "/renders/{$render['id']}");
}
if ($render["status"] !== "succeeded") {
$error = $render["error"] ?? [];
throw new RuntimeException("Render {$render['status']}: " . ($error["code"] ?? "") . ": " . ($error["message"] ?? ""));
}
$download = curl_init($render["output"]["mp4Url"]);
curl_setopt($download, CURLOPT_RETURNTRANSFER, true);
file_put_contents("hello.mp4", curl_exec($download));
echo "Saved hello.mp4 ({$render['chargedSeconds']} render seconds)\n";
# Needs Ruby 3.0 or later and no gems. Save as render.rb and run: ruby render.rb
require "json"
require "net/http"
API = ENV.fetch("BLITFRAME", "https://blitframe.codeartworks.com/v1")
KEY = ENV.fetch("BLITFRAME_API_KEY")
def call(method, path, body = nil, headers = {})
uri = URI(API + path)
headers = { "Authorization" => "Bearer #{KEY}" }.merge(headers)
headers["Content-Type"] = "application/json" if body
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http|
http.send_request(method, uri.request_uri, body && JSON.generate(body), headers)
end
data = response.body.to_s.empty? ? nil : JSON.parse(response.body)
raise "#{response.code} #{data["error"]["code"]}: #{data["error"]["message"]}" if response.code.to_i >= 400
data
end
# A 3-second 720p composition: a dark background with a blue rounded plate.
composition = {
v: "5.12.2", nm: "Hello Blitframe", fr: 30, ip: 0, op: 90, w: 1280, h: 720, ddd: 0, assets: [],
layers: [
{ ty: 4, ind: 1, nm: "Plate", ip: 0, op: 90, st: 0, sr: 1,
ks: { a: { a: 0, k: [0, 0, 0] }, p: { a: 0, k: [640, 360, 0] }, s: { a: 0, k: [100, 100, 100] },
r: { a: 0, k: 0 }, o: { a: 0, k: 100 } },
shapes: [{ ty: "gr", nm: "Plate", it: [
{ ty: "rc", d: 1, p: { a: 0, k: [0, 0] }, s: { a: 0, k: [800, 300] }, r: { a: 0, k: 32 } },
{ ty: "fl", c: { a: 0, k: [0.1, 0.3, 0.8, 1] }, o: { a: 0, k: 100 }, r: 1 },
{ ty: "tr", p: { a: 0, k: [0, 0] }, a: { a: 0, k: [0, 0] }, s: { a: 0, k: [100, 100] },
r: { a: 0, k: 0 }, o: { a: 0, k: 100 } }] }] },
{ ty: 1, ind: 2, nm: "Background", ip: 0, op: 90, st: 0, sr: 1,
ks: { a: { a: 0, k: [0, 0, 0] }, p: { a: 0, k: [0, 0, 0] }, s: { a: 0, k: [100, 100, 100] },
r: { a: 0, k: 0 }, o: { a: 0, k: 100 } },
sw: 1280, sh: 720, sc: "#101725" },
],
}
project = call("POST", "/projects", { name: "Hello Blitframe" })
version = call("POST", "/projects/#{project["id"]}/versions", {
message: "First version",
files: [{ path: "data.json", content: JSON.generate(composition) }],
})
raise "Not renderable: #{version["problems"].join("; ")}" unless version["renderable"]
render = call("POST", "/renders", { projectId: project["id"], format: "mp4" },
{ "Idempotency-Key" => "hello-#{version["id"]}" })
while %w[queued rendering].include?(render["status"])
sleep 2
render = call("GET", "/renders/#{render["id"]}")
end
unless render["status"] == "succeeded"
error = render["error"] || {}
raise "Render #{render["status"]}: #{error["code"]}: #{error["message"]}"
end
File.binwrite("hello.mp4", Net::HTTP.get(URI(render["output"]["mp4Url"])))
puts "Saved hello.mp4 (#{render["chargedSeconds"]} render seconds)"
// Needs Go 1.21 or later and only the standard library. Save as main.go and run: go run main.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
var api = "https://blitframe.codeartworks.com/v1"
// A 3-second 720p composition: a dark background with a blue rounded plate.
const composition = `
{"v": "5.12.2", "nm": "Hello Blitframe", "fr": 30, "ip": 0, "op": 90, "w": 1280, "h": 720, "ddd": 0, "assets": [],
"layers": [
{"ty": 4, "ind": 1, "nm": "Plate", "ip": 0, "op": 90, "st": 0, "sr": 1,
"ks": {"a": {"a": 0, "k": [0, 0, 0]}, "p": {"a": 0, "k": [640, 360, 0]}, "s": {"a": 0, "k": [100, 100, 100]},
"r": {"a": 0, "k": 0}, "o": {"a": 0, "k": 100}},
"shapes": [{"ty": "gr", "nm": "Plate", "it": [
{"ty": "rc", "d": 1, "p": {"a": 0, "k": [0, 0]}, "s": {"a": 0, "k": [800, 300]}, "r": {"a": 0, "k": 32}},
{"ty": "fl", "c": {"a": 0, "k": [0.1, 0.3, 0.8, 1]}, "o": {"a": 0, "k": 100}, "r": 1},
{"ty": "tr", "p": {"a": 0, "k": [0, 0]}, "a": {"a": 0, "k": [0, 0]}, "s": {"a": 0, "k": [100, 100]},
"r": {"a": 0, "k": 0}, "o": {"a": 0, "k": 100}}]}]},
{"ty": 1, "ind": 2, "nm": "Background", "ip": 0, "op": 90, "st": 0, "sr": 1,
"ks": {"a": {"a": 0, "k": [0, 0, 0]}, "p": {"a": 0, "k": [0, 0, 0]}, "s": {"a": 0, "k": [100, 100, 100]},
"r": {"a": 0, "k": 0}, "o": {"a": 0, "k": 100}},
"sw": 1280, "sh": 720, "sc": "#101725"}]}`
func call(method, path string, body any, idempotencyKey string) map[string]any {
var payload io.Reader
if body != nil {
encoded, err := json.Marshal(body)
if err != nil {
panic(err)
}
payload = bytes.NewReader(encoded)
}
request, err := http.NewRequest(method, api+path, payload)
if err != nil {
panic(err)
}
request.Header.Set("Authorization", "Bearer "+os.Getenv("BLITFRAME_API_KEY"))
if body != nil {
request.Header.Set("Content-Type", "application/json")
}
if idempotencyKey != "" {
request.Header.Set("Idempotency-Key", idempotencyKey)
}
response, err := http.DefaultClient.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
var data map[string]any
if err := json.NewDecoder(response.Body).Decode(&data); err != nil && err != io.EOF {
panic(err)
}
if response.StatusCode >= 400 {
problem, _ := data["error"].(map[string]any)
panic(fmt.Sprintf("%d %v: %v", response.StatusCode, problem["code"], problem["message"]))
}
return data
}
func main() {
if address := os.Getenv("BLITFRAME"); address != "" {
api = address
}
project := call("POST", "/projects", map[string]any{"name": "Hello Blitframe"}, "")
version := call("POST", fmt.Sprintf("/projects/%v/versions", project["id"]), map[string]any{
"message": "First version",
"files": []map[string]string{{"path": "data.json", "content": composition}},
}, "")
if version["renderable"] != true {
var problems []string
for _, problem := range version["problems"].([]any) {
problems = append(problems, fmt.Sprint(problem))
}
panic("Not renderable: " + strings.Join(problems, "; "))
}
render := call("POST", "/renders", map[string]any{"projectId": project["id"], "format": "mp4"},
fmt.Sprintf("hello-%v", version["id"]))
for render["status"] == "queued" || render["status"] == "rendering" {
time.Sleep(2 * time.Second)
render = call("GET", fmt.Sprintf("/renders/%v", render["id"]), nil, "")
}
if render["status"] != "succeeded" {
problem, _ := render["error"].(map[string]any)
panic(fmt.Sprintf("Render %v: %v: %v", render["status"], problem["code"], problem["message"]))
}
video, err := http.Get(render["output"].(map[string]any)["mp4Url"].(string))
if err != nil {
panic(err)
}
defer video.Body.Close()
content, err := io.ReadAll(video.Body)
if err != nil {
panic(err)
}
if err := os.WriteFile("hello.mp4", content, 0o644); err != nil {
panic(err)
}
fmt.Printf("Saved hello.mp4 (%v render seconds)\n", render["chargedSeconds"])
}
// Needs .NET 8 or later and no packages. Run "dotnet new console", replace Program.cs with this, then "dotnet run".
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Nodes;
var api = Environment.GetEnvironmentVariable("BLITFRAME") ?? "https://blitframe.codeartworks.com/v1";
using var http = new HttpClient();
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("BLITFRAME_API_KEY"));
async Task<JsonNode> Call(HttpMethod method, string path, object? body = null, string? idempotencyKey = null)
{
using var request = new HttpRequestMessage(method, api + path);
if (body is not null) request.Content = JsonContent.Create(body);
if (idempotencyKey is not null) request.Headers.Add("Idempotency-Key", idempotencyKey);
using var response = await http.SendAsync(request);
var json = JsonNode.Parse(await response.Content.ReadAsStringAsync())!;
if (!response.IsSuccessStatusCode)
throw new Exception($"{(int)response.StatusCode} {json["error"]!["code"]}: {json["error"]!["message"]}");
return json;
}
JsonObject Transform(int x, int y) => new()
{
["a"] = new JsonObject { ["a"] = 0, ["k"] = new JsonArray(0, 0, 0) },
["p"] = new JsonObject { ["a"] = 0, ["k"] = new JsonArray(x, y, 0) },
["s"] = new JsonObject { ["a"] = 0, ["k"] = new JsonArray(100, 100, 100) },
["r"] = new JsonObject { ["a"] = 0, ["k"] = 0 },
["o"] = new JsonObject { ["a"] = 0, ["k"] = 100 },
};
// A 3-second 720p composition: a dark background with a blue rounded plate.
var composition = new JsonObject
{
["v"] = "5.12.2", ["nm"] = "Hello Blitframe", ["fr"] = 30, ["ip"] = 0, ["op"] = 90, ["w"] = 1280, ["h"] = 720, ["ddd"] = 0,
["assets"] = new JsonArray(),
["layers"] = new JsonArray(
new JsonObject
{
["ty"] = 4, ["ind"] = 1, ["nm"] = "Plate", ["ip"] = 0, ["op"] = 90, ["st"] = 0, ["sr"] = 1, ["ks"] = Transform(640, 360),
["shapes"] = JsonNode.Parse("""
[{"ty":"gr","nm":"Plate","it":[
{"ty":"rc","d":1,"p":{"a":0,"k":[0,0]},"s":{"a":0,"k":[800,300]},"r":{"a":0,"k":32}},
{"ty":"fl","c":{"a":0,"k":[0.1,0.3,0.8,1]},"o":{"a":0,"k":100},"r":1},
{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100}}]}]
"""),
},
new JsonObject
{
["ty"] = 1, ["ind"] = 2, ["nm"] = "Background", ["ip"] = 0, ["op"] = 90, ["st"] = 0, ["sr"] = 1, ["ks"] = Transform(0, 0),
["sw"] = 1280, ["sh"] = 720, ["sc"] = "#101725",
}),
};
var project = await Call(HttpMethod.Post, "/projects", new { name = "Hello Blitframe" });
var version = await Call(HttpMethod.Post, $"/projects/{project["id"]}/versions", new
{
message = "First version",
files = new[] { new { path = "data.json", content = composition.ToJsonString() } },
});
if (!(bool)version["renderable"]!)
throw new Exception("Not renderable: " + string.Join("; ", version["problems"]!.AsArray()));
var render = await Call(HttpMethod.Post, "/renders", new { projectId = (string)project["id"]!, format = "mp4" }, $"hello-{version["id"]}");
while ((string)render["status"]! is "queued" or "rendering")
{
await Task.Delay(2000);
render = await Call(HttpMethod.Get, $"/renders/{render["id"]}");
}
if ((string)render["status"]! != "succeeded") throw new Exception($"Render {render["status"]}: {render["error"]?["code"]}: {render["error"]?["message"]}");
using var download = new HttpClient(); // download links are signed URLs: send them no API key
await File.WriteAllBytesAsync("hello.mp4", await download.GetByteArrayAsync((string)render["output"]!["mp4Url"]!));
Console.WriteLine($"Saved hello.mp4 ({render["chargedSeconds"]} render seconds)");
// Needs Java 17 or later and Jackson (the jackson-databind dependency).
// Save as Example.java in a Maven or Gradle project that has it and run the Example class.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
public class Example {
static final String API = System.getenv().getOrDefault("BLITFRAME", "https://blitframe.codeartworks.com/v1");
static final HttpClient HTTP = HttpClient.newHttpClient();
static final ObjectMapper JSON = new ObjectMapper();
// A 3-second 720p composition: a dark background with a blue rounded plate.
static final String COMPOSITION = """
{"v": "5.12.2", "nm": "Hello Blitframe", "fr": 30, "ip": 0, "op": 90, "w": 1280, "h": 720, "ddd": 0, "assets": [],
"layers": [
{"ty": 4, "ind": 1, "nm": "Plate", "ip": 0, "op": 90, "st": 0, "sr": 1,
"ks": {"a": {"a": 0, "k": [0, 0, 0]}, "p": {"a": 0, "k": [640, 360, 0]}, "s": {"a": 0, "k": [100, 100, 100]},
"r": {"a": 0, "k": 0}, "o": {"a": 0, "k": 100}},
"shapes": [{"ty": "gr", "nm": "Plate", "it": [
{"ty": "rc", "d": 1, "p": {"a": 0, "k": [0, 0]}, "s": {"a": 0, "k": [800, 300]}, "r": {"a": 0, "k": 32}},
{"ty": "fl", "c": {"a": 0, "k": [0.1, 0.3, 0.8, 1]}, "o": {"a": 0, "k": 100}, "r": 1},
{"ty": "tr", "p": {"a": 0, "k": [0, 0]}, "a": {"a": 0, "k": [0, 0]}, "s": {"a": 0, "k": [100, 100]},
"r": {"a": 0, "k": 0}, "o": {"a": 0, "k": 100}}]}]},
{"ty": 1, "ind": 2, "nm": "Background", "ip": 0, "op": 90, "st": 0, "sr": 1,
"ks": {"a": {"a": 0, "k": [0, 0, 0]}, "p": {"a": 0, "k": [0, 0, 0]}, "s": {"a": 0, "k": [100, 100, 100]},
"r": {"a": 0, "k": 0}, "o": {"a": 0, "k": 100}},
"sw": 1280, "sh": 720, "sc": "#101725"}]}
""";
static JsonNode call(String method, String path, Object body, String idempotencyKey) throws Exception {
var request = HttpRequest.newBuilder(URI.create(API + path))
.header("Authorization", "Bearer " + System.getenv("BLITFRAME_API_KEY"))
.method(method, body == null
? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofString(JSON.writeValueAsString(body)));
if (body != null) request.header("Content-Type", "application/json");
if (idempotencyKey != null) request.header("Idempotency-Key", idempotencyKey);
var response = HTTP.send(request.build(), HttpResponse.BodyHandlers.ofString());
var data = JSON.readTree(response.body());
if (response.statusCode() >= 400) {
var error = data.path("error");
throw new RuntimeException(response.statusCode() + " " + error.path("code").asText() + ": " + error.path("message").asText());
}
return data;
}
public static void main(String[] args) throws Exception {
var project = call("POST", "/projects", Map.of("name", "Hello Blitframe"), null);
var projectId = project.get("id").asText();
var version = call("POST", "/projects/" + projectId + "/versions", Map.of(
"message", "First version",
"files", List.of(Map.of("path", "data.json", "content", COMPOSITION))), null);
var versionId = version.get("id").asText();
if (!version.get("renderable").asBoolean()) {
throw new RuntimeException("Not renderable: " + String.join("; ", JSON.convertValue(version.get("problems"), String[].class)));
}
var render = call("POST", "/renders", Map.of("projectId", projectId, "format", "mp4"), "hello-" + versionId);
while (List.of("queued", "rendering").contains(render.get("status").asText())) {
Thread.sleep(2000);
render = call("GET", "/renders/" + render.get("id").asText(), null, null);
}
if (!render.get("status").asText().equals("succeeded")) {
var error = render.path("error");
throw new RuntimeException("Render " + render.get("status").asText() + ": " + error.path("code").asText() + ": " + error.path("message").asText());
}
var video = HTTP.send(HttpRequest.newBuilder(URI.create(render.get("output").get("mp4Url").asText())).build(),
HttpResponse.BodyHandlers.ofByteArray());
Files.write(Path.of("hello.mp4"), video.body());
System.out.println("Saved hello.mp4 (" + render.get("chargedSeconds").asText() + " render seconds)");
}
}
The Quickstart runs the same flow one request at a time, in the same languages.
Adapting the examples
| To | Change |
|---|---|
| Render your own composition | Replace the inline composition with your data.json. Add every image, video and 3D model file it references to files, at the path the composition uses. Binary files go in contentBase64. See data.json basics for the layout. |
| Add a font | Add it as fonts/Family-Style.ttf, named after its family and style rather than by a path. The edit must carry "fontLicenseAccepted": true (Fonts). |
| Add sound | Sound does not come from the composition. Send the audio file and name it in the edit's soundtrack (Soundtrack). |
| Change an existing project | Edit it again with only the files that change. The others are kept from its head. To be sure nobody changed it since you read it, send expectedHeadVersionId with the headVersionId you read. If the head has moved, you get 409 head_moved: get the project and make your change again (Editing a project). |
| Send large files | An edit request can be up to 64 MB. Send larger files through an upload, and reference them by uploadId (Uploading large files). |
| Make many videos from one project | Render one version many times, each with its own text, images or video, in one batch render (Many videos from a data sheet). |
| Poll less | Send Prefer: wait=50 with GET /v1/renders/{renderId} to hold the response until the render finishes or 50 seconds pass. Or register a webhook and wait for render.succeeded. |