Create many sites at once
Create many sites in one go, within the limits, without making any twice.
2 min read Updated
Create many WordPress sites on a server in one go: within the limits, without making any twice, and able to carry on after a failure.
What you need
-
A token with
sites:read(View sites) andsites:create(Create sites). - The server's id, and each site's name, title and WordPress administrator.
1. Skip the sites there already
List the server's sites first, and leave out the ones it has: a run that stopped half-way can then be started again, and only makes what's missing.
curl "https://api.rabbitflare.com/v1/servers/3f6c1a2b-8d4e-4b7a-9c2d-1e5f7a8b9c0d/sites" \
-H "Authorization: Bearer $RABBITFLARE_TOKEN" const res = await fetch("https://api.rabbitflare.com/v1/servers/3f6c1a2b-8d4e-4b7a-9c2d-1e5f7a8b9c0d/sites", {
headers: {
Authorization: `Bearer ${process.env.RABBITFLARE_TOKEN}`,
},
});
if (!res.ok) throw new Error(`Rabbitflare API error ${res.status}: ${await res.text()}`);
const { data, pagination } = await res.json();
console.log(data, pagination.nextCursor); import { Rabbitflare } from "@rabbitflare/api";
const rf = new Rabbitflare({ token: process.env.RABBITFLARE_TOKEN });
for await (const item of rf.servers.sites.list({
serverId: "3f6c1a2b-8d4e-4b7a-9c2d-1e5f7a8b9c0d",
})) {
console.log(item);
} <?php
$ch = curl_init('https://api.rabbitflare.com/v1/servers/3f6c1a2b-8d4e-4b7a-9c2d-1e5f7a8b9c0d/sites');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('RABBITFLARE_TOKEN'),
],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($body === false || $status >= 400) {
throw new RuntimeException("Rabbitflare API error $status: $body");
}
$answer = json_decode($body, true);
print_r($answer['data']);
echo $answer['pagination']['nextCursor'] ?? 'Last page', PHP_EOL; import os
import requests
response = requests.get(
"https://api.rabbitflare.com/v1/servers/3f6c1a2b-8d4e-4b7a-9c2d-1e5f7a8b9c0d/sites",
headers={
"Authorization": "Bearer " + os.environ["RABBITFLARE_TOKEN"],
},
timeout=120,
)
response.raise_for_status()
answer = response.json()
print(answer["data"], answer["pagination"]["nextCursor"]) 2. Give each site its own key
Create each site with POST /v1/sites, and an Idempotency-Key made from the site itself, like
site- and a hash of the server's id and the site's name. If a request times out and you send it again, the same key answers with the site
that was made instead of making a second one, for 24 hours (see Idempotency).
curl -X POST "https://api.rabbitflare.com/v1/sites" \
-H "Authorization: Bearer $RABBITFLARE_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"serverId": "3f6c1a2b-8d4e-4b7a-9c2d-1e5f7a8b9c0d",
"name": "Shop",
"siteTitle": "Example Shop",
"adminUsername": "editor",
"adminEmail": "[email protected]"
}' const res = await fetch("https://api.rabbitflare.com/v1/sites", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.RABBITFLARE_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
"serverId": "3f6c1a2b-8d4e-4b7a-9c2d-1e5f7a8b9c0d",
"name": "Shop",
"siteTitle": "Example Shop",
"adminUsername": "editor",
"adminEmail": "[email protected]"
}),
});
if (!res.ok) throw new Error(`Rabbitflare API error ${res.status}: ${await res.text()}`);
const { data } = await res.json();
console.log(data); import { Rabbitflare } from "@rabbitflare/api";
const rf = new Rabbitflare({ token: process.env.RABBITFLARE_TOKEN });
const data = await rf.sites.create({
serverId: "3f6c1a2b-8d4e-4b7a-9c2d-1e5f7a8b9c0d",
name: "Shop",
siteTitle: "Example Shop",
adminUsername: "editor",
adminEmail: "[email protected]",
});
console.log(data); <?php
$ch = curl_init('https://api.rabbitflare.com/v1/sites');
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('RABBITFLARE_TOKEN'),
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'serverId' => '3f6c1a2b-8d4e-4b7a-9c2d-1e5f7a8b9c0d',
'name' => 'Shop',
'siteTitle' => 'Example Shop',
'adminUsername' => 'editor',
'adminEmail' => '[email protected]',
]),
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($body === false || $status >= 400) {
throw new RuntimeException("Rabbitflare API error $status: $body");
}
print_r(json_decode($body, true)['data']); import os
import requests
response = requests.post(
"https://api.rabbitflare.com/v1/sites",
headers={
"Authorization": "Bearer " + os.environ["RABBITFLARE_TOKEN"],
},
json={
"serverId": "3f6c1a2b-8d4e-4b7a-9c2d-1e5f7a8b9c0d",
"name": "Shop",
"siteTitle": "Example Shop",
"adminUsername": "editor",
"adminEmail": "[email protected]",
},
timeout=120,
)
response.raise_for_status()
print(response.json()["data"]) 3. Stay within the limits
An account can create 60 sites an hour through the API, and a token can make 30 changes a minute and 4
requests at once. Create the sites one after another: over a limit, the answer is 429 rate_limited, and its
Retry-After header says how many seconds to wait before sending the same request again (see Rate limits).
After the 60th site of an hour, that can be a while: the script waits.
4. Follow them
Each site starts as queued and installs on its own, a minute or two each.
Let webhooks tell you when each is done (site.ready or site.install_failed), or read each site until it's active.
What can go wrong
| Code | Status | What it means | What to do |
|---|---|---|---|
rate_limited | 429 | Too many requests. scope says which limit: token, account, create, operation or network. | Wait for Retry-After seconds, then go on more slowly. |
validation_failed | 422 | One or more fields are missing or wrong. fields names each one with what's wrong. | Correct the fields named in fields. Unknown fields are refused too. |
not_found | 404 | The resource doesn't exist, or isn't this account's. | Check the id. Ids of other accounts' resources answer the same way. |
server_unavailable | 409 | The server isn't in a state that allows this (for example, it's off or still being set up). | Start the server, or wait until it's active, then try again. |
idempotency_key_reused | 422 | The Idempotency-Key was already used in the last 24 hours with another operation or another body, or by another token of the account. | Use a new key for a new request. |
Any other refusal stops the script, with the API's code and message: fix the cause, and run it again.
The whole script
Steps 1 to 3 in JavaScript (Node.js 18 or later; save it as an .mjs file). Put your server's id and your sites in SERVER_ID and
SITES.
// Creates many WordPress sites on one server, within the limits, without making any twice: after a failure, run it
// again and it carries on.
import { createHash } from "node:crypto";
const API = "https://api.rabbitflare.com/v1";
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Sends a request and gives back its data. Over a rate limit (429) it waits as long as Retry-After says, then sends
// the same request again; any other error is thrown with the API's code.
async function rabbitflare(method, path, body, headers = {}) {
for (;;) {
const res = await fetch(API + path, {
method,
headers: {
Authorization: `Bearer ${process.env.RABBITFLARE_TOKEN}`,
...(body ? { "Content-Type": "application/json" } : {}),
...headers,
},
body: body ? JSON.stringify(body) : undefined,
});
if (res.status === 429) {
await sleep((Number(res.headers.get("Retry-After")) || 1) * 1000);
continue;
}
const answer = res.status === 204 ? null : await res.json().catch(() => null);
if (!res.ok) throw Object.assign(new Error(answer?.error?.message ?? `HTTP ${res.status}`), { code: answer?.error?.code });
return answer?.data ?? null;
}
}
const SERVER_ID = "3f6c1a2b-8d4e-4b7a-9c2d-1e5f7a8b9c0d";
const SITES = [
{ name: "Boston Bakery", siteTitle: "Boston Bakery", adminUsername: "editor", adminEmail: "[email protected]" },
{ name: "Denver Dental", siteTitle: "Denver Dental Care", adminUsername: "editor", adminEmail: "[email protected]" },
{ name: "Seattle Yoga", siteTitle: "Seattle Yoga Studio", adminUsername: "editor", adminEmail: "[email protected]" },
];
// The sites the server has already, by name: they aren't made again.
const existing = new Set((await rabbitflare("GET", `/servers/${SERVER_ID}/sites?limit=100`)).map((s) => s.name));
for (const site of SITES) {
if (existing.has(site.name)) {
console.log(`${site.name}: there already`);
continue;
}
// The same key for the same site: if this request is sent twice (after a timeout, say), one site is made.
const key = "site-" + createHash("sha256").update(`${SERVER_ID}/${site.name}`).digest("hex");
// Over the create limit, the API answers 429 and rabbitflare() waits until a site can be made.
const created = await rabbitflare("POST", "/sites", { serverId: SERVER_ID, ...site }, { "Idempotency-Key": key });
console.log(`${site.name}: ${created.id}, ${created.status}`);
} Still have a question?
Our team answers support tickets about the API, and other developers answer in the community.