import os
import time
import requests
API_KEY = os.environ["KWI_API_KEY"]
BASE_URL = "https://api.keywordinsights.ai"
HEADERS = {"X-API-Key": API_KEY}
def create_order(keywords, volumes):
"""Create a clustering order."""
response = requests.post(
f"{BASE_URL}/api/keywords-insights/order/",
headers=HEADERS,
json={
"project_name": "API automation example",
"keywords": 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",
},
)
response.raise_for_status()
return response.json()
def wait_for_completion(order_id):
"""Poll until the order is done."""
while True:
response = requests.get(
f"{BASE_URL}/api/keywords-insights/order/",
headers=HEADERS,
params={"order_id": order_id},
)
data = response.json()
print(f"Status: {data['status']} ({data['progress']:.0%})")
if data["status"] == "done":
return data
time.sleep(30)
def get_results(order_id):
"""Fetch all clusters as JSON."""
response = requests.get(
f"{BASE_URL}/api/keywords-insights/order/json/{order_id}/",
headers=HEADERS,
params={"page_size": 100, "page_number": 1},
)
response.raise_for_status()
return response.json()
# --- Run ---
keywords = ["best running shoes", "running shoes review", "top sneakers for running"]
volumes = [12000, 8500, 3200]
result = create_order(keywords, volumes)
order_id = result["order_id"]
print(f"Order created: {order_id} (cost: {result['cost']} credits)")
wait_for_completion(order_id)
data = get_results(order_id)
for cluster in data["result"]["payload"]["clusters"]:
print(f" {cluster['name']} — {cluster['number_of_keywords']} kw, vol: {cluster['search_volume']}")