Recipes
Complete scripts for common jobs with the Linkpost API. Post the same text to several accounts, schedule a week of posts from a CSV file, upload a carousel, publish a poll on X and LinkedIn, wait for a post and print its link, and call the API from n8n or Make.
Each recipe is a complete program you can copy, change and run. They use the endpoints described in Posts and Accounts, and they read the key from the LINKPOST_KEY environment variable. See API overview for how to set it and what each language needs.
Every recipe sends consent=1. That tells Linkpost that the owner of each account wants these posts published. Only run a recipe on content the owners approved.
Post the same text to several accounts
This script sends one text to every connected account that takes text posts. It skips accounts that need reconnecting and accounts where the text is too long, and waits when Linkpost asks it to slow down. Each account gets its own post, with its own id and status.
It sends one request per account, so an account that refuses the post does not stop the others. To create the posts of all the accounts or none, in one request, use Publish on several accounts at once.
const API = "https://linkpost.app/api/v1";
const TEXT = "We are closed on Friday for a team day. Orders placed before Thursday at 12:00 ship as usual.";
const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
// Sends a request, and waits and tries again when Linkpost answers 429.
async function send(path, options = {}) {
while (true) {
const response = await fetch(`${API}${path}`, {
...options,
headers: { Authorization: `Bearer ${process.env.LINKPOST_KEY}`, "Content-Type": "application/json" },
});
if (response.status !== 429) {
return response;
}
await sleep(Number(response.headers.get("retry-after") ?? 60));
}
}
const { data: accounts } = await (await send("/accounts")).json();
for (const account of accounts) {
const label = `${account.name} on ${account.platform}`;
const textFormat = account.formats.find((f) => f.format === "text");
if (!textFormat) {
continue;
}
if (account.health === "reconnect") {
console.log(`Skipped ${label}: connect the account again in Linkpost.`);
continue;
}
if ([...TEXT].length > textFormat.max_text) {
console.log(`Skipped ${label}: the text is longer than ${textFormat.max_text} characters.`);
continue;
}
const response = await send("/posts", {
method: "POST",
body: JSON.stringify({ account_id: account.id, format: "text", title: TEXT, consent: true }),
});
const body = await response.json();
console.log(response.status === 201 ? `Queued for ${label}: ${body.data.id}` : `Refused for ${label}: ${body.message}`);
}
import os
import time
import requests
API = "https://linkpost.app/api/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['LINKPOST_KEY']}"}
TEXT = "We are closed on Friday for a team day. Orders placed before Thursday at 12:00 ship as usual."
def send(method, path, **kwargs):
"""Sends a request, and waits and tries again when Linkpost answers 429."""
while True:
response = requests.request(method, f"{API}{path}", headers=HEADERS, timeout=60, **kwargs)
if response.status_code != 429:
return response
time.sleep(int(response.headers.get("Retry-After", 60)))
for account in send("GET", "/accounts").json()["data"]:
label = f"{account['name']} on {account['platform']}"
text_format = next((f for f in account["formats"] if f["format"] == "text"), None)
if text_format is None:
continue
if account["health"] == "reconnect":
print(f"Skipped {label}: connect the account again in Linkpost.")
continue
if len(TEXT) > text_format["max_text"]:
print(f"Skipped {label}: the text is longer than {text_format['max_text']} characters.")
continue
response = send("POST", "/posts", json={"account_id": account["id"], "format": "text", "title": TEXT, "consent": True})
body = response.json()
if response.status_code == 201:
print(f"Queued for {label}: {body['data']['id']}")
else:
print(f"Refused for {label}: {body['message']}")
Each post counts against the limit of 10 new posts a minute. With more than 10 accounts, the script waits for a while in the middle. That is expected.
Schedule a week of posts from a CSV file
This Python script reads a CSV file and schedules one post per line. Each column becomes a field of the post, so a line can carry whatever its network needs, such as privacy_level for LinkedIn or video_title and made_for_kids for YouTube. The file column is the path of the video or photo to upload.
Save the posts as week.csv:
account_id,format,file,title,scheduled_at,privacy_level
12,reel,videos/monday.mp4,New week and new prints in the shop,2026-11-23 09:00,
24,video,videos/tuesday.mp4,How we fold a scarf in 20 seconds,2026-11-24 12:30,
21,video,videos/wednesday.mp4,Meet the team behind the autumn collection,2026-11-25 08:00,PUBLIC
12,story,images/thursday.jpg,,2026-11-26 18:00,
27,video,videos/friday.mp4,The weekend sale starts now,2026-11-27 17:00,
The times have no offset, so the script sends timezone with each line. Change TIMEZONE to yours.
Save the script as schedule_csv.py:
import csv
import os
import sys
import time
import requests
API = "https://linkpost.app/api/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['LINKPOST_KEY']}"}
TIMEZONE = "Europe/Madrid"
def create_post(fields, path):
"""Creates one post. Waits and tries again when Linkpost answers 429."""
while True:
if path:
with open(path, "rb") as media:
response = requests.post(
f"{API}/posts",
headers=HEADERS,
data=fields,
files={"media": (os.path.basename(path), media)},
timeout=900,
)
else:
response = requests.post(f"{API}/posts", headers=HEADERS, data=fields, timeout=60)
if response.status_code != 429:
return response
time.sleep(int(response.headers.get("Retry-After", 60)))
with open(sys.argv[1], newline="", encoding="utf-8") as source:
rows = list(csv.DictReader(source))
refused = 0
for line, row in enumerate(rows, start=2):
path = (row.pop("file", "") or "").strip()
fields = {key: value.strip() for key, value in row.items() if key and isinstance(value, str) and value.strip()}
fields.update({"timezone": TIMEZONE, "consent": 1})
response = create_post(fields, path)
body = response.json()
if response.status_code == 201:
post = body["data"]
print(f"Line {line}: scheduled {post['type']} for {post['scheduled_at']} UTC ({post['id']})")
else:
refused += 1
problems = "; ".join(f"{field}: {' '.join(messages)}" for field, messages in body.get("errors", {}).items())
print(f"Line {line}: not scheduled. {problems or body['message']}")
print(f"Done: {len(rows) - refused} scheduled, {refused} refused.")
Run it:
python schedule_csv.py week.csv
Line 2: scheduled Instagram reel for 2026-11-23T08:00:00Z UTC (01m6xd2k4h8f3q9w7e5r1t6y2a)
Line 3: scheduled X post for 2026-11-24T11:30:00Z UTC (01m6xd3m7p2s6v0x4z8b3n5c7d)
Line 4: scheduled LinkedIn post for 2026-11-25T07:00:00Z UTC (01m6xd4q9r5t8w2y6a0c4e7g1h)
Line 5: scheduled Instagram story for 2026-11-26T17:00:00Z UTC (01m6xd5s2v7y0a4c8e2g5j9k3m)
Line 6: not scheduled. media: Bluesky takes videos from 1 s to 3 min.
Done: 4 scheduled, 1 refused.
A refused line creates nothing, so fix it and run the script again on a file with only that line. Running the script twice on the same file schedules everything twice. To undo a run, cancel the posts with DELETE /api/v1/posts/{id}.
A line without a file creates a post without files, such as format text. Text posts are pending Meta and TikTok certification and are not available to every account yet.
Upload a carousel from a folder
This Node.js script publishes every photo and video in a folder as one Instagram carousel, in the order of their file names (01.jpg, 02.jpg, 03.mp4). It checks the account's carousel limits before it uploads anything, then waits for the result.
Save it as carousel.mjs and run it with the account id, the folder and the caption:
node carousel.mjs 12 ./autumn-carousel "The autumn scarf, from sketch to shop."
import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
const [accountId, folder, caption = ""] = process.argv.slice(2);
const API = "https://linkpost.app/api/v1";
const headers = { Authorization: `Bearer ${process.env.LINKPOST_KEY}` };
const types = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".webp": "image/webp",
".mp4": "video/mp4",
".mov": "video/quicktime",
};
const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
// 1. Check that the account takes carousels, and how many files and characters.
const { data: accounts } = await (await fetch(`${API}/accounts`, { headers })).json();
const account = accounts.find((a) => a.id === Number(accountId));
const carousel = account?.formats.find((f) => f.format === "carousel");
if (!carousel) {
throw new Error("This account does not take carousels, or they are not available on your account yet.");
}
const names = (await readdir(folder)).filter((name) => types[path.extname(name).toLowerCase()]).sort();
if (names.length < carousel.min_files || names.length > carousel.max_files) {
throw new Error(`A carousel takes ${carousel.min_files} to ${carousel.max_files} files. The folder has ${names.length}.`);
}
if ([...caption].length > carousel.max_text) {
throw new Error(`The caption is longer than ${carousel.max_text} characters.`);
}
// 2. Upload the files in name order.
const form = new FormData();
form.append("account_id", accountId);
form.append("format", "carousel");
form.append("title", caption);
form.append("consent", "1");
for (const name of names) {
const type = types[path.extname(name).toLowerCase()];
form.append("files[]", new Blob([await readFile(path.join(folder, name))], { type }), name);
}
const response = await fetch(`${API}/posts`, { method: "POST", headers, body: form });
const body = await response.json();
if (response.status !== 201) {
console.error(body.message, body.errors ?? "");
process.exit(1);
}
console.log(`Created ${body.data.id} with ${names.length} files. Instagram processes each one first.`);
// 3. Wait for the result, every 30 seconds for up to 30 minutes.
for (let check = 0; check < 60; check++) {
await sleep(30);
const { data: post } = await (await fetch(`${API}/posts/${body.data.id}`, { headers })).json();
if (post.is_final) {
console.log(post.status === "published" ? "Published." : `Failed: ${post.fail_reason}`);
process.exit(0);
}
}
console.log("Still processing. Check the post in the app.");
Instagram only takes photos between 4:5 and 1.91:1. A photo outside that range makes the whole carousel fail after the upload, so crop the photos before you run the script.
Publish a poll on X and LinkedIn
X and LinkedIn take polls with different limits: a LinkedIn question has up to 140 characters and its answers up to 30, while X answers have up to 25.
The X account posts through your own X app, so X charges each poll to that app's credits. See Your X app.
- The cURL loop sends the same poll to both accounts as it is. Where the poll does not fit, Linkpost refuses it with
422and the reason, and creates nothing for that account. - The Python script reads each account's limits from
formatsfirst, and only publishes where the poll fits. It tells you why it skipped the others.
for ACCOUNT in 24 21; do
curl https://linkpost.app/api/v1/posts \
-H "Authorization: Bearer $LINKPOST_KEY" \
-H "Content-Type: application/json" \
-d "{
\"account_id\": $ACCOUNT,
\"format\": \"poll\",
\"title\": \"Which colour should our next scarf come in?\",
\"poll_options\": [\"Rust\", \"Forest green\", \"Navy\"],
\"poll_hours\": 72,
\"consent\": true
}"
echo
done
import os
import requests
API = "https://linkpost.app/api/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['LINKPOST_KEY']}"}
QUESTION = "Which colour should our next scarf come in?"
ANSWERS = ["Rust", "Forest green", "Navy"]
HOURS = 72 # 24, 72 or 168
ACCOUNT_IDS = [24, 21] # an X account and a LinkedIn account
accounts = {a["id"]: a for a in requests.get(f"{API}/accounts", headers=HEADERS, timeout=30).json()["data"]}
for account_id in ACCOUNT_IDS:
account = accounts[account_id]
label = f"{account['name']} on {account['platform']}"
poll = next((f for f in account["formats"] if f["format"] == "poll"), None)
if poll is None:
print(f"Skipped {label}: this account does not take polls.")
continue
problems = []
if len(QUESTION) > poll["max_text"]:
problems.append(f"the question is longer than {poll['max_text']} characters")
if not 2 <= len(ANSWERS) <= poll["poll_answers"]:
problems.append(f"it needs 2 to {poll['poll_answers']} answers")
problems += [f'"{a}" is longer than {poll["poll_answer_chars"]} characters' for a in ANSWERS if len(a) > poll["poll_answer_chars"]]
if problems:
print(f"Skipped {label}: " + "; ".join(problems) + ".")
continue
response = requests.post(
f"{API}/posts",
headers=HEADERS,
json={
"account_id": account_id,
"format": "poll",
"title": QUESTION,
"poll_options": ANSWERS,
"poll_hours": HOURS,
"consent": True,
},
timeout=60,
)
body = response.json()
print(f"Queued for {label}: {body['data']['id']}" if response.status_code == 201 else f"Refused for {label}: {body['message']}")
On LinkedIn the question is the whole post. On X the poll closes after poll_hours. To add a Telegram channel, add its id: Telegram takes up to 10 answers of 100 characters, and its polls stay open until someone stops them.
Wait for a post and print its link
The API returns the network's id for a published post in provider_post_id, but not a link. This script waits for a post to finish and builds the link where the network allows it. For TikTok it reads the creator's username from creator info. For Instagram, Facebook and Telegram it prints the id. See Post statuses.
const API = "https://linkpost.app/api/v1";
const headers = { Authorization: `Bearer ${process.env.LINKPOST_KEY}` };
const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
async function get(path) {
while (true) {
const response = await fetch(`${API}${path}`, { headers });
if (response.status === 429) {
await sleep(Number(response.headers.get("retry-after") ?? 60));
continue;
}
if (!response.ok) {
throw new Error(`${response.status}: ${(await response.json()).message}`);
}
return (await response.json()).data;
}
}
// The web address of a published post, or null when it cannot be built from the id.
async function link(post) {
const id = post.provider_post_id;
if (!id) return null;
switch (post.platform) {
case "youtube":
return `https://www.youtube.com/watch?v=${id}`;
case "x":
return `https://x.com/i/status/${id}`;
case "linkedin":
return `https://www.linkedin.com/feed/update/${id}/`;
case "bluesky": {
const parts = id.split("/");
return `https://bsky.app/profile/${parts[2]}/post/${parts.at(-1)}`;
}
case "tiktok": {
if (!post.account_id) return null;
const { username } = await get(`/accounts/${post.account_id}/creator-info`);
return username ? `https://www.tiktok.com/@${username}/video/${id}` : null;
}
default:
return null;
}
}
const postId = process.argv[2];
let post = await get(`/posts/${postId}`);
if (post.status === "scheduled") {
console.log(`The post is scheduled for ${post.scheduled_at}. Run this again after that time.`);
process.exit(0);
}
const deadline = Date.now() + 60 * 60 * 1000;
while (!post.is_final && Date.now() < deadline) {
console.log(new Date().toLocaleTimeString(), post.status_label);
await sleep(30);
post = await get(`/posts/${postId}`);
}
if (post.status === "published") {
const url = await link(post);
if (url) {
console.log(url);
} else if (post.provider_post_id) {
console.log(`Published. The network's id is ${post.provider_post_id}.`);
} else {
console.log("Published. The network returned no id, so there is no link.");
}
} else if (post.is_final) {
console.log(`${post.status_label}: ${post.status_detail}`);
} else {
console.log("Still not final after an hour. Check the post in the app.");
}
import os
import sys
import time
import requests
API = "https://linkpost.app/api/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['LINKPOST_KEY']}"}
def get(path):
while True:
response = requests.get(f"{API}{path}", headers=HEADERS, timeout=30)
if response.status_code != 429:
response.raise_for_status()
return response.json()["data"]
time.sleep(int(response.headers.get("Retry-After", 60)))
def link(post):
"""The web address of a published post, or None when it cannot be built from the id."""
platform, remote_id = post["platform"], post["provider_post_id"]
if not remote_id:
return None
if platform == "youtube":
return f"https://www.youtube.com/watch?v={remote_id}"
if platform == "x":
return f"https://x.com/i/status/{remote_id}"
if platform == "linkedin":
return f"https://www.linkedin.com/feed/update/{remote_id}/"
if platform == "bluesky":
did, rkey = remote_id.split("/")[2], remote_id.split("/")[-1]
return f"https://bsky.app/profile/{did}/post/{rkey}"
if platform == "tiktok" and post["account_id"]:
username = get(f"/accounts/{post['account_id']}/creator-info")["username"]
return f"https://www.tiktok.com/@{username}/video/{remote_id}" if username else None
return None
post_id = sys.argv[1]
post = get(f"/posts/{post_id}")
if post["status"] == "scheduled":
print(f"The post is scheduled for {post['scheduled_at']}. Run this again after that time.")
sys.exit(0)
deadline = time.monotonic() + 60 * 60
while not post["is_final"] and time.monotonic() < deadline:
print(f"{time.strftime('%H:%M:%S')} {post['status_label']}")
time.sleep(30)
post = get(f"/posts/{post_id}")
if post["status"] == "published":
url = link(post)
if url:
print(url)
elif post["provider_post_id"]:
print(f"Published. The network's id is {post['provider_post_id']}.")
else:
print("Published. The network returned no id, so there is no link.")
elif post["is_final"]:
print(f"{post['status_label']}: {post['status_detail']}")
else:
print("Still not final after an hour. Check the post in the app.")
Save the JavaScript version as post_link.mjs, or the Python version as post_link.py, and run it with a post id:
node post_link.mjs 01m6xardvrc76m2h9pfm7as4wr
python post_link.py 01m6xardvrc76m2h9pfm7as4wr
The output for a LinkedIn video:
10:20:21 Uploading to LinkedIn
10:20:51 LinkedIn is processing the video
10:21:21 LinkedIn is processing the video
https://www.linkedin.com/feed/update/urn:li:ugcPost:7262618447195271168/
For Instagram, Facebook and Telegram, and for a TikTok account whose username Linkpost cannot read, the script prints Published. The network's id is followed by the id. A TikTok post can also be published without a provider_post_id. The script then prints Published. The network returned no id, so there is no link.
Call the API from n8n or Make
Any automation tool that can send an HTTP request with a header and a multipart body can use the API. The settings are the same as in the cURL examples: the URL, the Authorization header, the fields and the file.
n8n
First, store the key as a credential:
- In n8n, create a credential of the type Header Auth.
- Set Name to
Authorizationand Value toBearer lp_your_key, with a space afterBearer.
To publish a video, the workflow needs the file as binary data from an earlier node, such as a node that reads a file from disk or downloads it from cloud storage. n8n calls that binary field data unless you renamed it. Then add an HTTP Request node:
- Method:
POST. - URL:
https://linkpost.app/api/v1/posts. - Authentication: Generic Credential Type, then Header Auth, then the credential you created.
- Turn on Send Body and set Body Content Type to Form-Data.
- Add one body parameter per field. For each text field, set Parameter Type to Form Data, then the Name and the Value:
account_id:12format:reeltitle: the caption, for example{{ $json.caption }}consent:1
- Add one more parameter with Parameter Type set to n8n Binary File, Name set to
mediaand Input Data Field Name set todata.
The node outputs the new post. Its id is in {{ $json.data.id }}.
For a text post or a poll, set Body Content Type to JSON instead and send the fields as JSON, with "consent": true.
Good to know:
- The file name matters. Linkpost checks that it ends in an extension the network takes, like
.mp4. If the earlier node gives the binary data another name, rename it first. - Errors stop the workflow by default, with Linkpost's message. To handle a
422in the workflow instead, open the node's Options, add Response, and turn on Never Error. Then check the status code yourself. - Do not retry the create request automatically. If a create request times out, a retry can publish the post twice. See Avoid duplicate posts.
- To follow the post, add a Wait node of one minute, then an HTTP Request node with Method
GETand URLhttps://linkpost.app/api/v1/posts/{{ $json.data.id }}, then an If node on{{ $json.data.is_final }}. Send the false branch back to the Wait node, and stop the loop after an hour.
Make
Use the HTTP app's module that makes a request. Make changes the labels of this app from version to version, so look for these settings:
- The URL:
https://linkpost.app/api/v1/posts, and the method:POST. - A header named
Authorizationwith the valueBearer lp_your_key. Store the key in a keychain or connection if your version offers one, rather than in the scenario itself. - The body type:
multipart/form-data. - Fields: text fields
account_id,format,titleandconsentwith the value1, and a file field namedmedia. Map the file's data and its file name from the module that got the file. The file name must end in an extension the network takes, like.mp4. - Turn on the option that parses the response, so later modules can read
data.idanddata.status.
For a text post or a poll, choose a JSON body instead, and send the fields as JSON with "consent": true.
To follow the post, add a request to GET https://linkpost.app/api/v1/posts/{id} after a pause, and repeat it until data.is_final is true.