Text Utilities API Examples
Complete code examples and integration guides for the Text Utilities API in multiple programming languages.Quick Examples
Analyze Text
Copy
curl "https://api.sinaty.business/text/?text=Hello World&operation=analyze"
Convert to CamelCase
Copy
curl "https://api.sinaty.business/text/?text=hello world&operation=camelcase"
Encode to Base64
Copy
curl "https://api.sinaty.business/text/?text=hello&operation=base64_encode"
JavaScript/Node.js Examples
Basic Text Analysis
Copy
async function analyzeText(text) {
try {
const response = await fetch(
`https://api.sinaty.business/text/?text=${encodeURIComponent(text)}&operation=analyze`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.analysis;
} catch (error) {
console.error('Error analyzing text:', error);
return null;
}
}
// Usage
const analysis = await analyzeText('Hello World! This is a test.');
console.log('Text analysis:', analysis);
Case Transformations
Copy
async function transformText(text, operation) {
try {
const response = await fetch(
`https://api.sinaty.business/text/?text=${encodeURIComponent(text)}&operation=${operation}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.result;
} catch (error) {
console.error('Error transforming text:', error);
return null;
}
}
// Usage examples
const camelCase = await transformText('hello world', 'camelcase');
const snakeCase = await transformText('Hello World', 'snakecase');
const kebabCase = await transformText('Hello World', 'kebabcase');
console.log('camelCase:', camelCase); // helloWorld
console.log('snake_case:', snakeCase); // hello_world
console.log('kebab-case:', kebabCase); // hello-world
Text Encoding/Decoding
Copy
async function encodeText(text, operation) {
try {
const response = await fetch(
`https://api.sinaty.business/text/?text=${encodeURIComponent(text)}&operation=${operation}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.result;
} catch (error) {
console.error('Error encoding text:', error);
return null;
}
}
// Usage
const base64Encoded = await encodeText('hello world', 'base64_encode');
const urlEncoded = await encodeText('hello world', 'url_encode');
const htmlEncoded = await encodeText('<script>alert("hello")</script>', 'html_encode');
console.log('Base64:', base64Encoded);
console.log('URL encoded:', urlEncoded);
console.log('HTML encoded:', htmlEncoded);
Text Manipulation
Copy
async function manipulateText(text, operation) {
try {
const response = await fetch(
`https://api.sinaty.business/text/?text=${encodeURIComponent(text)}&operation=${operation}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.result;
} catch (error) {
console.error('Error manipulating text:', error);
return null;
}
}
// Usage examples
const reversed = await manipulateText('hello', 'reverse');
const reversedWords = await manipulateText('hello world', 'reverse_words');
const noSpaces = await manipulateText('hello world', 'remove_spaces');
const noDuplicates = await manipulateText('hello', 'remove_duplicates');
console.log('Reversed:', reversed); // olleh
console.log('Reversed words:', reversedWords); // world hello
console.log('No spaces:', noSpaces); // helloworld
console.log('No duplicates:', noDuplicates); // helo
Python Examples
Basic Text Analysis
Copy
import requests
import json
def analyze_text(text):
"""Analyze text and return detailed statistics."""
try:
url = "https://api.sinaty.business/text/"
params = {
'text': text,
'operation': 'analyze'
}
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
return data['analysis']
except requests.exceptions.RequestException as e:
print(f"Error analyzing text: {e}")
return None
# Usage
analysis = analyze_text('Hello World! This is a test.')
print(f"Text analysis: {analysis}")
Case Transformations
Copy
def transform_text(text, operation):
"""Transform text using various operations."""
try:
url = "https://api.sinaty.business/text/"
params = {
'text': text,
'operation': operation
}
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
return data['result']
except requests.exceptions.RequestException as e:
print(f"Error transforming text: {e}")
return None
# Usage examples
camel_case = transform_text('hello world', 'camelcase')
snake_case = transform_text('Hello World', 'snakecase')
kebab_case = transform_text('Hello World', 'kebabcase')
print(f"camelCase: {camel_case}")
print(f"snake_case: {snake_case}")
print(f"kebab-case: {kebab_case}")
Text Encoding/Decoding
Copy
def encode_text(text, operation):
"""Encode or decode text using various methods."""
try:
url = "https://api.sinaty.business/text/"
params = {
'text': text,
'operation': operation
}
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
return data['result']
except requests.exceptions.RequestException as e:
print(f"Error encoding text: {e}")
return None
# Usage
base64_encoded = encode_text('hello world', 'base64_encode')
url_encoded = encode_text('hello world', 'url_encode')
html_encoded = encode_text('<script>alert("hello")</script>', 'html_encode')
print(f"Base64: {base64_encoded}")
print(f"URL encoded: {url_encoded}")
print(f"HTML encoded: {html_encoded}")
Text Manipulation
Copy
def manipulate_text(text, operation):
"""Manipulate text using various operations."""
try:
url = "https://api.sinaty.business/text/"
params = {
'text': text,
'operation': operation
}
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
return data['result']
except requests.exceptions.RequestException as e:
print(f"Error manipulating text: {e}")
return None
# Usage examples
reversed_text = manipulate_text('hello', 'reverse')
reversed_words = manipulate_text('hello world', 'reverse_words')
no_spaces = manipulate_text('hello world', 'remove_spaces')
no_duplicates = manipulate_text('hello', 'remove_duplicates')
print(f"Reversed: {reversed_text}")
print(f"Reversed words: {reversed_words}")
print(f"No spaces: {no_spaces}")
print(f"No duplicates: {no_duplicates}")
PHP Examples
Basic Text Analysis
Copy
<?php
function analyzeText($text) {
$url = "https://api.sinaty.business/text/";
$params = http_build_query([
'text' => $text,
'operation' => 'analyze'
]);
$fullUrl = $url . '?' . $params;
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => 'Content-Type: application/json'
]
]);
$response = file_get_contents($fullUrl, false, $context);
if ($response === false) {
return null;
}
$data = json_decode($response, true);
return $data['analysis'] ?? null;
}
// Usage
$analysis = analyzeText('Hello World! This is a test.');
echo "Text analysis: " . json_encode($analysis) . "\n";
?>
Case Transformations
Copy
<?php
function transformText($text, $operation) {
$url = "https://api.sinaty.business/text/";
$params = http_build_query([
'text' => $text,
'operation' => $operation
]);
$fullUrl = $url . '?' . $params;
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => 'Content-Type: application/json'
]
]);
$response = file_get_contents($fullUrl, false, $context);
if ($response === false) {
return null;
}
$data = json_decode($response, true);
return $data['result'] ?? null;
}
// Usage examples
$camelCase = transformText('hello world', 'camelcase');
$snakeCase = transformText('Hello World', 'snakecase');
$kebabCase = transformText('Hello World', 'kebabcase');
echo "camelCase: " . $camelCase . "\n";
echo "snake_case: " . $snakeCase . "\n";
echo "kebab-case: " . $kebabCase . "\n";
?>
Go Examples
Basic Text Analysis
Copy
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
type TextAnalysis struct {
Length int `json:"length"`
WordCount int `json:"word_count"`
LineCount int `json:"line_count"`
CharacterFrequency map[string]int `json:"character_frequency"`
WordFrequency map[string]int `json:"word_frequency"`
UppercaseCount int `json:"uppercase_count"`
LowercaseCount int `json:"lowercase_count"`
DigitCount int `json:"digit_count"`
SpaceCount int `json:"space_count"`
PunctuationCount int `json:"punctuation_count"`
}
type TextResponse struct {
Analysis TextAnalysis `json:"analysis"`
}
func analyzeText(text string) (*TextAnalysis, error) {
baseURL := "https://api.sinaty.business/text/"
params := url.Values{}
params.Add("text", text)
params.Add("operation", "analyze")
fullURL := baseURL + "?" + params.Encode()
resp, err := http.Get(fullURL)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var response TextResponse
err = json.Unmarshal(body, &response)
if err != nil {
return nil, err
}
return &response.Analysis, nil
}
func main() {
analysis, err := analyzeText("Hello World! This is a test.")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Text analysis: %+v\n", analysis)
}
Ruby Examples
Basic Text Analysis
Copy
require 'net/http'
require 'json'
require 'uri'
def analyze_text(text)
url = "https://api.sinaty.business/text/"
uri = URI(url)
params = {
'text' => text,
'operation' => 'analyze'
}
uri.query = URI.encode_www_form(params)
response = Net::HTTP.get_response(uri)
if response.is_a?(Net::HTTPSuccess)
data = JSON.parse(response.body)
return data['analysis']
else
puts "Error: #{response.code} - #{response.message}"
return nil
end
rescue => e
puts "Error analyzing text: #{e.message}"
return nil
end
# Usage
analysis = analyze_text('Hello World! This is a test.')
puts "Text analysis: #{analysis}"
cURL Examples
Basic Text Operations
Copy
# Analyze text
curl "https://api.sinaty.business/text/?text=Hello World&operation=analyze"
# Convert to camelCase
curl "https://api.sinaty.business/text/?text=hello world&operation=camelcase"
# Convert to snake_case
curl "https://api.sinaty.business/text/?text=Hello World&operation=snakecase"
# Convert to kebab-case
curl "https://api.sinaty.business/text/?text=Hello World&operation=kebabcase"
Text Encoding/Decoding
Copy
# Base64 encode
curl "https://api.sinaty.business/text/?text=hello&operation=base64_encode"
# Base64 decode
curl "https://api.sinaty.business/text/?text=aGVsbG8=&operation=base64_decode"
# URL encode
curl "https://api.sinaty.business/text/?text=hello world&operation=url_encode"
# HTML encode
curl "https://api.sinaty.business/text/?text=<script>&operation=html_encode"
Text Manipulation
Copy
# Reverse text
curl "https://api.sinaty.business/text/?text=hello&operation=reverse"
# Reverse word order
curl "https://api.sinaty.business/text/?text=hello world&operation=reverse_words"
# Remove spaces
curl "https://api.sinaty.business/text/?text=hello world&operation=remove_spaces"
# Remove duplicate characters
curl "https://api.sinaty.business/text/?text=hello&operation=remove_duplicates"
Integration Examples
React Component for Text Analysis
Copy
import React, { useState } from 'react';
function TextAnalyzer() {
const [text, setText] = useState('');
const [analysis, setAnalysis] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const analyzeText = async () => {
if (!text.trim()) return;
setLoading(true);
setError(null);
try {
const response = await fetch(
`https://api.sinaty.business/text/?text=${encodeURIComponent(text)}&operation=analyze`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setAnalysis(data.analysis);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
return (
<div>
<h2>Text Analyzer</h2>
<textarea
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Enter text to analyze..."
rows={5}
cols={50}
/>
<br />
<button
onClick={analyzeText}
disabled={!text.trim() || loading}
>
{loading ? 'Analyzing...' : 'Analyze Text'}
</button>
{analysis && (
<div>
<h3>Analysis Results:</h3>
<p>Characters: {analysis.length}</p>
<p>Words: {analysis.word_count}</p>
<p>Lines: {analysis.line_count}</p>
<p>Uppercase: {analysis.uppercase_count}</p>
<p>Lowercase: {analysis.lowercase_count}</p>
<p>Digits: {analysis.digit_count}</p>
<p>Spaces: {analysis.space_count}</p>
<p>Punctuation: {analysis.punctuation_count}</p>
</div>
)}
{error && <p style={{color: 'red'}}>Error: {error}</p>}
</div>
);
}
export default TextAnalyzer;
Express.js Text Processing Middleware
Copy
const express = require('express');
const fetch = require('node-fetch');
const app = express();
app.use(express.json());
// Middleware to process text
async function processText(req, res, next) {
try {
const { text, operation = 'analyze' } = req.body;
if (!text) {
return res.status(400).json({ error: 'Text is required' });
}
const params = new URLSearchParams({
text: text,
operation: operation
});
const response = await fetch(
`https://api.sinaty.business/text/?${params}`
);
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
const data = await response.json();
req.processedText = data;
next();
} catch (error) {
res.status(500).json({ error: error.message });
}
}
// Route for text processing
app.post('/process-text', processText, (req, res) => {
res.json(req.processedText);
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Content Analysis Service
Copy
class ContentAnalyzer {
async analyzeContent(content) {
try {
const response = await fetch(
`https://api.sinaty.business/text/?text=${encodeURIComponent(content)}&operation=analyze`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return this.generateInsights(data.analysis);
} catch (error) {
console.error('Error analyzing content:', error);
return null;
}
}
generateInsights(analysis) {
const readingTime = Math.ceil(analysis.word_count / 200); // 200 wpm
const complexity = this.calculateComplexity(analysis);
return {
wordCount: analysis.word_count,
characterCount: analysis.length,
readingTime: readingTime,
complexity: complexity,
hasNumbers: analysis.digit_count > 0,
hasPunctuation: analysis.punctuation_count > 0,
caseRatio: analysis.uppercase_count / analysis.length
};
}
calculateComplexity(analysis) {
const avgWordLength = analysis.length / analysis.word_count;
const punctuationRatio = analysis.punctuation_count / analysis.length;
if (avgWordLength > 6 && punctuationRatio > 0.1) {
return 'high';
} else if (avgWordLength > 4 && punctuationRatio > 0.05) {
return 'medium';
} else {
return 'low';
}
}
}
// Usage
const analyzer = new ContentAnalyzer();
const insights = await analyzer.analyzeContent('This is a sample text for analysis.');
console.log('Content insights:', insights);
Common Use Cases
Data Cleaning
Copy
async function cleanUserInput(input) {
// Remove duplicates and normalize case
const cleaned = await transformText(input, 'remove_duplicates');
const normalized = await transformText(cleaned, 'lowercase');
return normalized;
}
// Usage
const cleanInput = await cleanUserInput(' Hello World ');
console.log('Cleaned input:', cleanInput);
Content Analysis
Copy
async function analyzeContent(content) {
const analysis = await analyzeText(content);
return {
wordCount: analysis.word_count,
characterCount: analysis.length,
readingTime: Math.ceil(analysis.word_count / 200), // 200 wpm
complexity: analysis.punctuation_count > analysis.word_count * 0.1 ? 'high' : 'low'
};
}
// Usage
const contentAnalysis = await analyzeContent('This is a sample article for analysis.');
console.log('Content analysis:', contentAnalysis);
Format Conversion
Copy
async function convertToCamelCase(text) {
return await transformText(text, 'camelcase');
}
async function convertToSnakeCase(text) {
return await transformText(text, 'snakecase');
}
// Usage
const camelCase = await convertToCamelCase('hello world');
const snakeCase = await convertToSnakeCase('Hello World');
console.log('camelCase:', camelCase);
console.log('snake_case:', snakeCase);