Need to encode special characters as HTML entities? This guide covers everything you need to know about HTML encoding via API, including security implications and proper usage.
What is HTML Encoding?
HTML encoding converts special characters into their HTML entity equivalents. This prevents browsers from interpreting characters as HTML markup and is essential for displaying user-generated content safely.
Example: "<" becomes "<" and "&" becomes "&"
Common HTML Entities
Key characters that need encoding:
- < becomes <
- > becomes >
- & becomes &
- " becomes "
- ' becomes ' or '
Using the HTML Encode API
TinyFn provides a simple endpoint to encode HTML:
POST https://api.tinyfn.io/v1/text/html-encode
Headers: X-API-Key: your-api-key
Content-Type: application/json
{
"text": "<script>alert('XSS')</script>",
"encode_all": false
}
{
"encoded": "<script>alert('XSS')</script>",
"original_length": 28,
"encoded_length": 52
}
Parameters
| Parameter | Type | Description |
|---|---|---|
text |
string | The text to encode (required) |
encode_all |
boolean | Encode all non-ASCII characters (default: false) |
use_named |
boolean | Use named entities when available (default: true) |
Code Examples
JavaScript / Node.js
const response = await fetch(
'https://api.tinyfn.io/v1/text/html-encode',
{
method: 'POST',
headers: {
'X-API-Key': 'your-api-key',
'Content-Type': 'application/json'
},
body: JSON.stringify({
text: '<script>alert("XSS")</script>'
})
}
);
const result = await response.json();
console.log(result.encoded); // Safe HTML entities
Python
import requests
response = requests.post(
'https://api.tinyfn.io/v1/text/html-encode',
headers={'X-API-Key': 'your-api-key'},
json={'text': '<script>alert("XSS")</script>'}
)
result = response.json()
print(result['encoded']) # Safe HTML entities
cURL
curl -X POST "https://api.tinyfn.io/v1/text/html-encode" \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json" \
-d '{"text": "<script>alert(\"XSS\")</script>"}'
Common Use Cases
- XSS Prevention: Sanitize user input before display
- Code Display: Show HTML code as text in web pages
- Email Templates: Safely include dynamic content
- Data Export: Prepare content for HTML documents
- Content Management: Store safe versions of user content
Best Practices
- Always encode user input: Never trust user-provided content
- Encode at output: Encode when displaying, not when storing
- Context matters: Different contexts need different encoding
- Don't double-encode: Avoid encoding already-encoded content
Use via MCP
Your AI agent can call this tool directly via Model Context Protocol — no HTTP code needed. Add TinyFn to Claude Desktop, Cursor, or any MCP client:
{
"mcpServers": {
"tinyfn-text": {
"url": "https://api.tinyfn.io/mcp/text/",
"headers": {
"X-API-Key": "your-api-key"
}
}
}
}
See all text analysis tools available via MCP in our Text Analysis MCP Tools for AI Agents guide.