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_brief(keyword, language="en", location="United States"):
"""Create a content brief order."""
response = requests.post(
f"{BASE_URL}/api/content-brief/order/",
headers=HEADERS,
json={"keyword": keyword, "language": language, "location": location, "folder_id": "<your_folder_id>"},
)
response.raise_for_status()
return response.json()["result"]["payload"]
def wait_for_brief(order_id):
"""Poll until the content brief is ready."""
while True:
response = requests.get(
f"{BASE_URL}/api/content-brief/order/",
headers=HEADERS,
params={"id": order_id},
)
data = response.json()["result"]["payload"]
if data["status"]:
return data
print("Brief processing...")
time.sleep(15)
def generate_outline(order_id, context=""):
"""Trigger AI outline generation and wait for results."""
response = requests.post(
f"{BASE_URL}/api/content-brief/order/{order_id}/outline/",
headers=HEADERS,
json={"additional_context": context},
)
auto_id = response.json()["result"]["payload"]["auto_generate_order_id"]
while True:
response = requests.get(
f"{BASE_URL}/api/content-brief/order/{order_id}/outline/",
headers=HEADERS,
params={"auto_generate_order_id": auto_id},
)
data = response.json()["result"]["payload"]
if data["status"]:
return data
time.sleep(10)
# --- Run ---
result = create_brief("best project management tools")
order_id = result["id"]
print(f"Brief created: {order_id} (cost: {result['cost']} credits)")
brief = wait_for_brief(order_id)
print(f"Target: {brief['word_count_min']}–{brief['word_count_max']} words")
print(f"Title suggestions: {brief['brief_title_suggests']}")
outline = generate_outline(order_id, context="Focus on remote teams")
print(f"\nAI Outline:\n{outline['string']}")