Preview Message API
Introduction to Preview Message API
Welcome to SMSGatewayCenter's Preview Message API! This powerful API allows you to preview SMS messages before sending them. Get detailed information about message type (text/unicode), character count, number of parts, estimated cost, DLT template matching, and more. Perfect for building message preview features in mobile applications, calculating costs before sending, validating message length, and ensuring DLT compliance. Our RESTful endpoint supports both POST and GET methods with application/x-www-form-urlencoded content type for flexible integration.
About Message Preview
The Preview Message API enables you to:
- Preview message details - Get character count, parts, and message type before sending
- Calculate costs - Estimate SMS cost based on message length and type
- Check DLT template match - Verify message matches registered DLT template (if applicable)
- Validate message length - Ensure messages fit within SMS part limits
- Detect message type - Identify text vs unicode messages automatically
- Get template information - Retrieve matched DLT template ID and entity ID
- Real-time preview - Instant feedback on message characteristics
This API is essential for building user-friendly SMS applications that show message previews, cost estimates, and validation feedback before sending.
What is Message Preview?
Message Preview allows you to analyze SMS messages before sending them. The API returns detailed information including message type (text or unicode), character count, number of SMS parts (single or multi-part), estimated cost, and DLT template matching information. This helps you build better user experiences by showing users exactly what their message will look like and how much it will cost before they send it.
Preview Message
Get a detailed preview of your SMS message including type, length, parts, cost, and DLT template information. Returns comprehensive message analysis without actually sending the SMS.
API Endpoint
https://unify.smsgateway.center/SMSApi/previewHTTP Method
POST GET
Content Type
application/x-www-form-urlencoded
application/x-www-form-urlencoded content type for POST requests. Use --data-urlencode in cURL or appropriate encoding in your HTTP client.
| Key | Value | Description |
|---|---|---|
| Login Credentials (Required) | ||
| Authenticate your API request using userid-password or apiKey—choose one method. | ||
| userid | Your Registered Username | Your registered username; use if apiKey isn't provided. Signup for User ID |
| password | Your Password | URL-encoded password (for special characters); use if apiKey isn't provided. Signup for API Key |
| Header (optional) Parameters | ||
| apiKey | Your unique apiKey | apiKey needs to be sent as HTTP header when you are not using userid-password method. You can avail this from your user control panel and use instead of userid-password HTTP Request parameter. Please do not disclose this to anyone. |
| Parameter | Type | Required | Description |
|---|---|---|---|
msg | String | Yes | SMS message text to preview. Can include DLT template variables as {#var#} |
senderid | String | Yes | Sender ID to use for the message (e.g., "SMSGAT") |
dltEntityId | String | Optional | DLT Entity ID for India TRAI compliance. Required for DLT template matching |
format | String | Optional | Response format. Use json (recommended), xml, or plain. Default: json |
output | String | Optional | Alias for format parameter. Use json for JSON response |
POST Request (JSON Format)
curl -X POST "https://unify.smsgateway.center/SMSApi/preview" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "userid=YOUR_USERNAME" \
-d "password=YOUR_PASSWORD" \
-d "msg=Hello, this is a test message" \
-d "senderid=YOUR_SENDER_ID" \
-d "dltEntityId=YOUR_ENTITY_ID" \
-d "format=json"POST Request (XML Format)
curl -X POST "https://unify.smsgateway.center/SMSApi/preview" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "userid=YOUR_USERNAME" \
-d "password=YOUR_PASSWORD" \
-d "msg=Hello, this is a test message" \
-d "senderid=YOUR_SENDER_ID" \
-d "dltEntityId=YOUR_ENTITY_ID" \
-d "format=xml"POST Request (Plain Text Format)
curl -X POST "https://unify.smsgateway.center/SMSApi/preview" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "userid=YOUR_USERNAME" \
-d "password=YOUR_PASSWORD" \
-d "msg=Hello, this is a test message" \
-d "senderid=YOUR_SENDER_ID" \
-d "format=plain"GET Request (Query Parameters)
curl -X GET "https://unify.smsgateway.center/SMSApi/preview?userid=YOUR_USERNAME&password=YOUR_PASSWORD&msg=Hello%2C%20this%20is%20a%20test%20message&senderid=YOUR_SENDER_ID&dltEntityId=YOUR_ENTITY_ID&format=json"Using API Key (Alternative Authentication)
curl -X POST "https://unify.smsgateway.center/SMSApi/preview" \
-H "Content-Type: application/x-www-form-urlencoded" \
-H "apiKey: YOUR_API_KEY" \
-d "userid=YOUR_USERNAME" \
-d "msg=Hello, this is a test message" \
-d "senderid=YOUR_SENDER_ID" \
-d "format=json"Without DLT Entity ID (Optional Parameter)
curl -X POST "https://unify.smsgateway.center/SMSApi/preview" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "userid=YOUR_USERNAME" \
-d "password=YOUR_PASSWORD" \
-d "msg=Hello, this is a test message" \
-d "senderid=YOUR_SENDER_ID" \
-d "format=json"Example with Unicode Message
curl -X POST "https://unify.smsgateway.center/SMSApi/preview" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "userid=YOUR_USERNAME" \
-d "password=YOUR_PASSWORD" \
-d "msg=नमस्ते, यह एक परीक्षण संदेश है" \
-d "senderid=YOUR_SENDER_ID" \
-d "format=json"{
"status": "success",
"statusCode": "200",
"reason": "Preview generated successfully",
"msgType": "text",
"length": 28,
"parts": 1,
"dltTemplateId": "1234567890123456",
"dltEntityId": "YOUR_ENTITY_ID",
"amount": 0.05,
"message": "Hello, this is a test message"
}Response Fields
| Field | Type | Description |
|---|---|---|
| Success Response Fields | ||
status | String | Response status: "success" or "error" |
statusCode | String | Status code: "200" for success |
reason | String | Result message: "Preview generated successfully" or error description |
msgType | String | Message type: "text" for standard SMS or "unicode" for Unicode messages (Hindi, Arabic, etc.) |
length | Integer | Character count of the message |
parts | Integer | Number of SMS parts required (1 for single SMS, 2+ for multi-part SMS) |
dltTemplateId | String | DLT Template ID that matches the message (if DLT entity ID provided and template found) |
dltEntityId | String | DLT Entity ID used for template matching |
amount | Float | Estimated cost per SMS in your account currency |
message | String | Original message text as submitted |
| Error Response Fields | ||
status | String | "error" |
statusCode | String | Error code (e.g., "401" for authentication failure, "400" for invalid parameters) |
reason | String | Error description |
Understanding Message Types and Parts
The Preview API automatically detects message type and calculates the number of SMS parts required based on message length and character set.
| Message Type | Characters | Description | Example |
|---|---|---|---|
text | Standard ASCII | Standard English characters, numbers, and basic symbols | "Hello, this is a test message" |
unicode | Extended Unicode | Non-ASCII characters including Hindi, Arabic, Chinese, emojis, etc. | "नमस्ते, यह एक परीक्षण संदेश है" |
| Message Type | Single Part Limit | Multi-Part Limit (per part) | Maximum Parts |
|---|---|---|---|
text | 160 characters | 153 characters per part | Up to 255 parts |
unicode | 70 characters | 67 characters per part | Up to 255 parts |
Note: Multi-part SMS messages are automatically concatenated by mobile operators and delivered as a single message to the recipient.
Integration Examples
Example 1: Message Preview in Mobile App
// React Native / JavaScript example
async function previewMessage(message, senderId, dltEntityId) {
const params = new URLSearchParams({
userid: 'YourUsername',
password: 'YourPassword',
output: 'json',
msg: message,
senderid: senderId,
dltEntityId: dltEntityId || ''
});
try {
const response = await fetch('https://unify.smsgateway.center/SMSApi/preview', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: params.toString()
});
const data = await response.json();
if (data.status === 'success' && data.statusCode === '200') {
console.log('Message Preview:');
console.log(`Type: ${data.msgType}`);
console.log(`Length: ${data.length} characters`);
console.log(`Parts: ${data.parts}`);
console.log(`Cost: ${data.amount} per SMS`);
if (data.dltTemplateId) {
console.log(`DLT Template ID: ${data.dltTemplateId}`);
}
// Display preview in UI
return {
type: data.msgType,
length: data.length,
parts: data.parts,
cost: data.amount,
dltTemplateId: data.dltTemplateId
};
} else {
console.error(`Preview failed: ${data.reason}`);
return null;
}
} catch (error) {
console.error('Preview error:', error);
return null;
}
}
// Usage in React Native component
const MessagePreview = ({ message, senderId }) => {
const [preview, setPreview] = useState(null);
useEffect(() => {
if (message && message.length > 0) {
previewMessage(message, senderId).then(setPreview);
}
}, [message, senderId]);
if (!preview) return null;
return (
<View>
<Text>Type: {preview.type}</Text>
<Text>Length: {preview.length} characters</Text>
<Text>Parts: {preview.parts}</Text>
<Text>Cost: {preview.cost} per SMS</Text>
</View>
);
};Example 2: Cost Calculator
import requests
from urllib.parse import urlencode
def calculate_sms_cost(userid, password, message, sender_id, dlt_entity_id=None):
url = 'https://unify.smsgateway.center/SMSApi/preview'
data = {
'userid': userid,
'password': password,
'format': 'json',
'msg': message,
'senderid': sender_id
}
if dlt_entity_id:
data['dltEntityId'] = dlt_entity_id
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.post(url, data=data, headers=headers)
result = response.json()
if result['status'] == 'success':
parts = result.get('parts', 1)
amount_per_sms = float(result.get('amount', 0))
total_cost = parts * amount_per_sms
return {
'message_type': result.get('msgType', 'text'),
'length': result.get('length', 0),
'parts': parts,
'cost_per_sms': amount_per_sms,
'total_cost': total_cost,
'dlt_template_id': result.get('dltTemplateId')
}
else:
raise Exception(f"Preview failed: {result.get('reason', 'Unknown error')}")
# Calculate cost for bulk sending
message = "Hello, this is a test message"
sender_id = "YOUR_SENDER_ID"
recipient_count = 1000
preview = calculate_sms_cost('YourUsername', 'YourPassword', message, sender_id)
total_cost = preview['total_cost'] * recipient_count
print(f"Message Type: {preview['message_type']}")
print(f"Length: {preview['length']} characters")
print(f"Parts: {preview['parts']}")
print(f"Cost per SMS: {preview['cost_per_sms']}")
print(f"Total cost for {recipient_count} recipients: {total_cost}")Example 3: PHP Integration
<?php
function previewSMSMessage($userid, $password, $message, $senderId, $dltEntityId = null) {
$url = 'https://unify.smsgateway.center/SMSApi/preview';
$postData = array(
'userid' => $userid,
'password' => $password,
'output' => 'json',
'msg' => $message,
'senderid' => $senderId
);
if ($dltEntityId !== null) {
$postData['dltEntityId'] = $dltEntityId;
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200) {
$result = json_decode($response, true);
if ($result['status'] === 'success') {
return array(
'success' => true,
'msgType' => $result['msgType'],
'length' => $result['length'],
'parts' => $result['parts'],
'amount' => $result['amount'],
'dltTemplateId' => $result['dltTemplateId'] ?? null,
'message' => $result['message']
);
} else {
return array(
'success' => false,
'error' => $result['reason'] ?? 'Unknown error'
);
}
} else {
return array(
'success' => false,
'error' => 'HTTP Error: ' . $httpCode
);
}
}
// Usage
$preview = previewSMSMessage(
'YourUsername',
'YourPassword',
'Hello, this is a test message',
'YOUR_SENDER_ID',
'YOUR_ENTITY_ID' // Optional
);
if ($preview['success']) {
echo "Message Type: " . $preview['msgType'] . "\n";
echo "Length: " . $preview['length'] . " characters\n";
echo "Parts: " . $preview['parts'] . "\n";
echo "Cost: " . $preview['amount'] . " per SMS\n";
if ($preview['dltTemplateId']) {
echo "DLT Template ID: " . $preview['dltTemplateId'] . "\n";
}
} else {
echo "Error: " . $preview['error'] . "\n";
}
Error Codes
| Status Code | Status | Reason | Description |
|---|---|---|---|
200 | success | Preview generated successfully | Message preview generated successfully |
400 | error | Invalid parameters | Missing or invalid required parameters (msg, senderid, etc.) |
401 | error | Authentication failed | Invalid username, password, or API key |
500 | error | Internal server error | Server error occurred while processing the request |
Best Practices
Recommendations
- Preview Before Sending: Always preview messages before sending to show users cost and length information
- Use x-www-form-urlencoded: Ensure proper content-type header is set for POST requests
- URL Encoding: Use proper URL encoding for special characters in message text
- Cost Calculation: Use preview API to calculate total costs before bulk sending
- Length Validation: Check message length and parts to prevent unexpected costs
- DLT Template Matching: Provide DLT entity ID to get template matching information
- Unicode Detection: Use preview to detect unicode messages and adjust UI accordingly
- Real-time Preview: Call preview API as user types to show live character count and cost
- Error Handling: Handle preview errors gracefully and show user-friendly messages
- Cache Results: Cache preview results for identical messages to reduce API calls
Common Use Cases
Message Preview UI
Show users a preview of their message with character count, parts, and estimated cost before sending.
Cost Calculator
Calculate total SMS costs for bulk campaigns before sending to help users budget their campaigns.
Length Validator
Validate message length and warn users if messages exceed recommended limits or become multi-part.
DLT Template Preview
Preview messages with DLT template matching to ensure compliance before sending.
Unicode Detection
Automatically detect unicode messages and adjust UI or pricing accordingly.
Real-time Feedback
Provide real-time character count, parts, and cost as users type their messages.
Testimonials
Why do Great Businesses Trust SMS Gateway Center?

