const API_KEY = process.env.KWI_API_KEY;
const BASE_URL = "https://api.keywordinsights.ai";
const HEADERS = { "X-API-Key": API_KEY };
async function createOrder(keywords, volumes) {
const response = await fetch(`${BASE_URL}/api/keywords-insights/order/`, {
method: "POST",
headers: { ...HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({
project_name: "API automation example",
keywords,
search_volumes: volumes,
language: "en",
location: "United States",
insights: ["cluster", "context"],
folder_id: "<your_folder_id>",
clustering_method: "volume",
grouping_accuracy: 4,
hub_creation_method: "medium",
}),
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return await response.json();
}
async function waitForCompletion(orderId) {
while (true) {
const url = new URL(`${BASE_URL}/api/keywords-insights/order/`);
url.searchParams.append("order_id", orderId);
const response = await fetch(url, { headers: HEADERS });
const data = await response.json();
console.log(`Status: ${data.status} (${(data.progress * 100).toFixed(0)}%)`);
if (data.status === "done") return data;
await new Promise((r) => setTimeout(r, 30000));
}
}
async function getResults(orderId) {
const url = new URL(`${BASE_URL}/api/keywords-insights/order/json/${orderId}/`);
url.searchParams.append("page_size", "100");
url.searchParams.append("page_number", "1");
const response = await fetch(url, { headers: HEADERS });
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return await response.json();
}
async function run() {
const keywords = ["best running shoes", "running shoes review", "top sneakers for running"];
const volumes = [12000, 8500, 3200];
const result = await createOrder(keywords, volumes);
const orderId = result.order_id;
console.log(`Order created: ${orderId} (cost: ${result.cost} credits)`);
await waitForCompletion(orderId);
const data = await getResults(orderId);
data.result.payload.clusters.forEach((cluster) => {
console.log(
` ${cluster.name} — ${cluster.number_of_keywords} kw, vol: ${cluster.search_volume}`
);
});
}
run();