Build a Word Counter with the Text Analysis API

Adding a word counter to a content management system, blog editor, or form field is one of the most common text analysis tasks. Rather than writing string-splitting logic that breaks on edge cases (hyphenated words, Unicode, multiple spaces), you can offload the counting to the Apixies Text Analyzer API and get consistent, accurate results every time.

Why Use an API for Word Counting?

A naive text.split(' ').length approach fails in surprising ways:

Input Naive Split API Result Issue
"hello world" 3 (empty string) 2 Double spaces create empty tokens
"well-known fact" 2 3 or 2 Hyphenation handling varies
"café résumé" 2 2 Unicode characters need proper handling
"line1\nline2" 1 2 Newlines aren't spaces

The API normalizes whitespace, handles Unicode, and returns a consistent count along with sentences, paragraphs, and character counts -- all in one call.

Building a Word Counter: Step by Step

Step 1 -- Basic API Call

Send your text to the analyze endpoint:

curl -X POST "https://apixies.io/api/v1/analyze-text" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"text": "This is a sample blog post. It has two sentences."}'

Response:

{
  "status": "success",
  "data": {
    "words": 11,
    "characters": 51,
    "characters_no_spaces": 41,
    "sentences": 2,
    "paragraphs": 1,
    "avg_word_length": 3.7,
    "reading_time_min": 0.1,
    "top_words": { "is": 1, "a": 1 }
  }
}

Step 2 -- Display Word Count in a Blog CMS

Here's a practical JavaScript function that updates a word count display as users type:

const API_URL = "https://apixies.io/api/v1/analyze-text";

async function getWordCount(text) {
  const response = await fetch(API_URL, {
    method: "POST",
    headers: {
      "X-API-Key": "YOUR_API_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ text }),
  });

  const result = await response.json();
  return result.data;
}

// Debounce to avoid excessive API calls while typing
let timer;
document.getElementById("editor").addEventListener("input", (e) => {
  clearTimeout(timer);
  timer = setTimeout(async () => {
    const stats = await getWordCount(e.target.value);
    document.getElementById("word-count").textContent = `${stats.words} words`;
    document.getElementById("char-count").textContent =
      `${stats.characters} characters`;
    document.getElementById("read-time").textContent =
      `${stats.reading_time_min} min read`;
  }, 500);
});

Step 3 -- Enforce Content Guidelines

Many platforms require minimum or maximum word counts. Use the API response to validate submissions:

import requests
import os

api_key = os.environ["APIXIES_KEY"]

def validate_content(text, min_words=100, max_words=5000):
    response = requests.post(
        "https://apixies.io/api/v1/analyze-text",
        json={"text": text},
        headers={"X-API-Key": api_key},
    )
    data = response.json()["data"]

    errors = []
    if data["words"] < min_words:
        errors.append(f"Too short: {data['words']} words (minimum {min_words})")
    if data["words"] > max_words:
        errors.append(f"Too long: {data['words']} words (maximum {max_words})")

    return {
        "valid": len(errors) == 0,
        "word_count": data["words"],
        "reading_time": data["reading_time_min"],
        "errors": errors,
    }

result = validate_content("Short.", min_words=50)
print(result)
# {'valid': False, 'word_count': 1, 'reading_time': 0.0, 'errors': ['Too short: 1 words (minimum 50)']}

Step 4 -- Batch Analyze Multiple Documents

Process a collection of documents and generate a summary report:

async function batchAnalyze(documents) {
  const results = [];

  for (const doc of documents) {
    const stats = await getWordCount(doc.content);
    results.push({
      title: doc.title,
      words: stats.words,
      sentences: stats.sentences,
      readingTime: stats.reading_time_min,
      avgWordLength: stats.avg_word_length,
    });
  }

  // Summary
  const totalWords = results.reduce((sum, r) => sum + r.words, 0);
  const avgWords = Math.round(totalWords / results.length);

  return { documents: results, totalWords, avgWords };
}

Integration Patterns

With a Rich Text Editor

If your CMS uses a rich text editor (TinyMCE, Quill, ProseMirror), strip HTML before sending to the API. Most editors provide a getContent({ format: 'text' }) method:

// TinyMCE example
const plainText = tinymce.activeEditor.getContent({ format: "text" });
const stats = await getWordCount(plainText);

Server-Side Validation

For form submissions, validate on the server before saving:

$text = strip_tags($request->input('content'));
$stats = analyzeText($text);

if ($stats['words'] < 100) {
    return back()->withErrors(['content' => 'Article must be at least 100 words.']);
}

Next Steps

Get your free API key and start counting words accurately.

Try the Text Analyzer API

Free tier is for development & small projects. 75 requests/day with a registered account.

Getting Started

Explore

Resources

Get Started Free

Free for development and small projects.

Get Free API Key