import os
import time
import json
import requests
API_KEY = os.environ["KWI_API_KEY"]
BASE_URL = "https://api.keywordinsights.ai"
HEADERS = {"X-API-Key": API_KEY}
def create_content_order(keyword, insights, language="en", location="United States"):
"""Create a keyword content order."""
response = requests.post(
f"{BASE_URL}/api/keyword-content/order/",
headers=HEADERS,
json={
"keyword": keyword,
"language": language,
"location": location,
"content_insights": insights,
},
)
response.raise_for_status()
return response.json()
def wait_for_results(order_id):
"""Poll until results are ready."""
while True:
response = requests.get(
f"{BASE_URL}/api/keyword-content/order/",
headers=HEADERS,
params={"order_id": order_id},
)
data = response.json()["result"]["payload"]
if data["status"] == "done":
return data["results"]
print("Processing...")
time.sleep(10)
# --- Run ---
result = create_content_order(
keyword="best project management tools",
insights=["paa", "reddit_questions"],
)
order_id = result["order_id"]
print(f"Order created: {order_id} (cost: {result['cost']} credits)")
results = wait_for_results(order_id)
# Save to file
with open("content_research.json", "w") as f:
json.dump(results, f, indent=2)
paa_count = len(results.get("paa", []))
reddit_count = len(results.get("reddit_questions", []))
print(f"Saved {paa_count} PAA questions and {reddit_count} Reddit questions")