Need to count words in text programmatically? This guide covers everything you need to know about word counting via API, including use cases, implementation examples, and best practices for text analysis.
What is Word Counting?
Word counting is the process of determining the number of words in a piece of text. While seemingly simple, accurate word counting must handle edge cases like hyphenated words, contractions, numbers, and special characters.
A professional word count API provides consistent, reliable results across different text formats and languages.
Why Use a Word Count API?
Using an API for word counting offers several advantages:
- Consistency: Same counting rules applied everywhere
- Accuracy: Handles edge cases properly
- Additional metrics: Get character count, sentence count, and more
- No dependencies: No need to maintain counting logic
Using the Word Count API
TinyFn provides a simple endpoint to count words:
POST https://api.tinyfn.io/v1/text/word-count
Headers: X-API-Key: your-api-key
Content-Type: application/json
{
"text": "Hello world! This is a sample text."
}
{
"word_count": 7,
"character_count": 36,
"character_count_no_spaces": 30
}
Parameters
| Parameter | Type | Description |
|---|---|---|
text |
string | The text to analyze (required) |
include_numbers |
boolean | Count numbers as words (default: true) |
Code Examples
JavaScript / Node.js
const response = await fetch(
'https://api.tinyfn.io/v1/text/word-count',
{
method: 'POST',
headers: {
'X-API-Key': 'your-api-key',
'Content-Type': 'application/json'
},
body: JSON.stringify({ text: 'Hello world! This is a sample text.' })
}
);
const { word_count } = await response.json();
console.log(word_count); // 7
Python
import requests
response = requests.post(
'https://api.tinyfn.io/v1/text/word-count',
headers={'X-API-Key': 'your-api-key'},
json={'text': 'Hello world! This is a sample text.'}
)
word_count = response.json()['word_count']
print(word_count) # 7
cURL
curl -X POST "https://api.tinyfn.io/v1/text/word-count" \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json" \
-d '{"text": "Hello world! This is a sample text."}'
Common Use Cases
- Content Management: Enforce article length requirements
- Writing Tools: Display real-time word counts to users
- SEO Analysis: Ensure content meets length guidelines
- Academic Tools: Check essay word limits
- Translation Services: Calculate pricing based on word count
Best Practices
- Handle empty text: Always validate input before sending
- Consider language: Word boundaries vary by language
- Cache results: Cache counts for static content
- Batch requests: Process multiple texts in one request when possible