❄️ Winter Sale: 40% OFF AIWU
WINTER_SECRET
Valid until Mar 1st
JavaScript API Guide: Call AIWU from Browser and Node.js - AIWU – AI Plugin for WordPress
Table of Contents
< All Topics

JavaScript API Guide: Call AIWU from Browser and Node.js

This guide shows how to call the AIWU REST API from JavaScript — both in the browser (frontend) and in Node.js (backend). Includes ready-to-use code snippets for the most common use cases: generating text, triggering workflows, and creating posts programmatically.


Before You Start

  • AIWU REST API enabled and an API key generated (see REST API Quick Start)
  • Basic JavaScript knowledge
⚠️ Never expose your API key in browser JavaScript. If your code runs in the browser and can be viewed by visitors, your API key will be visible. For browser-side integrations, proxy requests through your own backend or use the public-facing AIWU chatbot instead.

Setup: Base URL and Headers

Define these once and reuse across all calls:

const AIWU_BASE = 'https://yoursite.com/wp-json/aiwu/v1';
const AIWU_KEY  = 'YOUR_API_KEY'; // Keep server-side only

const headers = {
  'Authorization': `Bearer ${AIWU_KEY}`,
  'Content-Type': 'application/json'
};

1. Generate Text

async function generateText(prompt) {
  const response = await fetch(`${AIWU_BASE}/generate`, {
    method: 'POST',
    headers,
    body: JSON.stringify({
      prompt,
      model: 'default',
      max_tokens: 500
    })
  });

  const data = await response.json();
  return data.content; // The generated text
}

// Usage
const text = await generateText('Write a 50-word description for a bamboo cutting board.');
console.log(text);

2. Trigger a Workflow

async function triggerWorkflow(workflowId, customData = {}) {
  const response = await fetch(`${AIWU_BASE}/workflows/${workflowId}/trigger`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ custom_data: customData })
  });

  const data = await response.json();
  return data; // { triggered: true, execution_id: '...' }
}

// Usage — trigger workflow ID 42 with custom variables
await triggerWorkflow(42, {
  product_name: 'Bamboo Cutting Board',
  category: 'Kitchen',
  target_language: 'Spanish'
});

3. Create a WordPress Post

async function createPost({ title, content, status = 'draft', categories = [] }) {
  const response = await fetch(`${AIWU_BASE}/posts`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ title, content, status, categories })
  });

  const data = await response.json();
  return data; // { id: 1234, url: 'https://...' }
}

// Usage
const post = await createPost({
  title: 'My New Article',
  content: '

Article content here...

', status: 'draft', categories: [5, 12] }); console.log(`Draft created: ${post.url}`);

4. Search Posts

async function searchPosts(query, limit = 10) {
  const params = new URLSearchParams({ search: query, limit });
  const response = await fetch(`${AIWU_BASE}/posts?${params}`, { headers });
  const data = await response.json();
  return data.posts; // Array of post objects
}

// Usage
const results = await searchPosts('product description tips', 5);
results.forEach(post => console.log(post.title, post.url));

5. Batch Generate with Rate Limit Handling

async function batchGenerate(prompts, delayMs = 1000) {
  const results = [];

  for (const prompt of prompts) {
    try {
      const text = await generateText(prompt);
      results.push({ prompt, text, success: true });
    } catch (error) {
      if (error.status === 429) {
        // Rate limited — wait and retry once
        await new Promise(r => setTimeout(r, delayMs * 3));
        const text = await generateText(prompt);
        results.push({ prompt, text, success: true });
      } else {
        results.push({ prompt, error: error.message, success: false });
      }
    }

    // Pause between requests to avoid rate limits
    await new Promise(r => setTimeout(r, delayMs));
  }

  return results;
}

// Usage — generate descriptions for 5 products
const products = [
  'Write a 100-word description for: Bamboo Cutting Board',
  'Write a 100-word description for: Cast Iron Skillet',
  // ...
];

const descriptions = await batchGenerate(products);

Node.js: Full Working Example

// generate-descriptions.js
// Run: node generate-descriptions.js

const products = [
  { id: 101, name: 'Bamboo Cutting Board', category: 'Kitchen' },
  { id: 102, name: 'Cast Iron Skillet',    category: 'Kitchen' },
];

const AIWU_BASE = 'https://yoursite.com/wp-json/aiwu/v1';
const AIWU_KEY  = process.env.AIWU_API_KEY; // Use env var

async function run() {
  for (const product of products) {
    const prompt = `Write a 100-word SEO product description for: ${product.name}. Category: ${product.category}.`;

    const response = await fetch(`${AIWU_BASE}/generate`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${AIWU_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ prompt, max_tokens: 200 })
    });

    const { content } = await response.json();
    console.log(`n=== ${product.name} ===n${content}`);

    await new Promise(r => setTimeout(r, 500)); // Respect rate limits
  }
}

run().catch(console.error);

Run with: AIWU_API_KEY=your_key node generate-descriptions.js


What’s Next


Last verified: AIWU v.4.9.2 · Updated: 2026-02-25

Scroll to Top