SMS Notifications
Send SMS messages to one or more recipients using the Notifications API. This service allows you to send text messages to users directly from your application.
Prerequisites
Before sending SMS notifications, ensure you have:
- A valid API subscription key
- Permission to access the Notifications API
- Valid phone numbers for your recipients
Sending SMS Messages
To send an SMS message, make a POST request to the /Sms/Send
endpoint with the following details:
Request Headers
Header | Description | Required |
---|---|---|
correlationid | Unique identifier for tracking the request | Yes |
x-ls-party-id | Party identifier | Yes |
Ocp-Apim-Subscription-Key | Your API subscription key | Yes |
Request Body
The request body requires:
body
: The text content of the SMS messagesendTo
: An array of recipients, each with:address
: The recipient's phone numbercountryCode
: The country code for the phone number
Code Examples
- C#
- Java
- Python
- JavaScript
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
public class SmsClient
{
private readonly HttpClient _client;
private readonly string _baseUrl = "https://apis.lightstone.co.za/lightstone-capabilities-notifications-api/v1";
public SmsClient(string apiKey)
{
_client = new HttpClient();
_client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apiKey);
}
public async Task<SmsResponse> SendSmsAsync(string message, string correlationId, string partyId,
params (string phoneNumber, string countryCode)[] recipients)
{
var request = new
{
body = message,
sendTo = Array.ConvertAll(recipients, r => new
{
address = r.phoneNumber,
countryCode = r.countryCode
})
};
var content = new StringContent(
JsonSerializer.Serialize(request),
Encoding.UTF8,
"application/json");
_client.DefaultRequestHeaders.Add("correlationid", correlationId);
_client.DefaultRequestHeaders.Add("x-ls-party-id", partyId);
var response = await _client.PostAsync($"{_baseUrl}/Sms/Send", content);
var responseContent = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<SmsResponse>(responseContent);
}
}
public class SmsResponse
{
public int StatusCode { get; set; }
public string Message { get; set; }
}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
public class SmsClient {
private final HttpClient httpClient = HttpClient.newHttpClient();
private final ObjectMapper objectMapper = new ObjectMapper();
private final String baseUrl = "https://apis.lightstone.co.za/lightstone-capabilities-notifications-api/v1";
private final String apiKey;
public SmsClient(String apiKey) {
this.apiKey = apiKey;
}
public SmsResponse sendSms(String message, String correlationId, String partyId,
List<Recipient> recipients) throws Exception {
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("body", message);
requestBody.put("sendTo", recipients);
String requestJson = objectMapper.writeValueAsString(requestBody);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/Sms/Send"))
.header("Content-Type", "application/json")
.header("Ocp-Apim-Subscription-Key", apiKey)
.header("correlationid", correlationId)
.header("x-ls-party-id", partyId)
.POST(HttpRequest.BodyPublishers.ofString(requestJson))
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
return objectMapper.readValue(response.body(), SmsResponse.class);
}
public static class Recipient {
private String address;
private String countryCode;
public Recipient(String phoneNumber, String countryCode) {
this.address = phoneNumber;
this.countryCode = countryCode;
}
// Getters and setters omitted for brevity
}
public static class SmsResponse {
private int statusCode;
private String message;
// Getters and setters omitted for brevity
}
}
import requests
import json
class SmsClient:
def __init__(self, api_key):
self.base_url = "https://apis.lightstone.co.za/lightstone-capabilities-notifications-api/v1"
self.api_key = api_key
def send_sms(self, message, correlation_id, party_id, recipients):
"""
Send SMS message to one or more recipients
Args:
message (str): The SMS content
correlation_id (str): Tracking identifier for the request
party_id (str): Party identifier
recipients (list): List of dictionaries with 'address' and 'countryCode'
Returns:
dict: Response with statusCode and message
"""
headers = {
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": self.api_key,
"correlationid": correlation_id,
"x-ls-party-id": party_id
}
payload = {
"body": message,
"sendTo": recipients
}
response = requests.post(
f"{self.base_url}/Sms/Send",
headers=headers,
data=json.dumps(payload)
)
return response.json()
# Example usage
if __name__ == "__main__":
client = SmsClient("your-api-key")
response = client.send_sms(
message="Your verification code is 123456",
correlation_id="request-123",
party_id="party-456",
recipients=[
{"address": "0721234567", "countryCode": "27"},
{"address": "0821234567", "countryCode": "27"}
]
)
print(response)
class SmsClient {
constructor(apiKey) {
this.baseUrl = 'https://apis.lightstone.co.za/lightstone-capabilities-notifications-api/v1';
this.apiKey = apiKey;
}
async sendSms(message, correlationId, partyId, recipients) {
const url = `${this.baseUrl}/Sms/Send`;
const headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': this.apiKey,
'correlationid': correlationId,
'x-ls-party-id': partyId
};
const body = {
body: message,
sendTo: recipients
};
try {
const response = await fetch(url, {
method: 'POST',
headers: headers,
body: JSON.stringify(body)
});
return await response.json();
} catch (error) {
console.error('Error sending SMS:', error);
throw error;
}
}
}
// Example usage
async function sendNotification() {
const client = new SmsClient('your-api-key');
try {
const response = await client.sendSms(
'Your verification code is 123456',
'request-123',
'party-456',
[
{ address: '0721234567', countryCode: '27' },
{ address: '0821234567', countryCode: '27' }
]
);
console.log('SMS response:', response);
} catch (error) {
console.error('Failed to send SMS:', error);
}
}
Response Handling
The API returns a JSON response with the following structure:
{
"statusCode": 0,
"message": "SMS sent successfully"
}
Status Codes
Status Code | Description |
---|---|
0 | Success |
Other values | Error codes (refer to error message for details) |
Best Practices
- Validate Phone Numbers: Ensure phone numbers are valid before sending messages
- Keep Messages Concise: SMS messages have a 160 character limit per segment
- Handle Failures: Implement proper error handling for failed deliveries
- Rate Limiting: Be mindful of rate limits when sending bulk messages
- Compliance: Ensure your SMS messages comply with relevant regulations and laws
Troubleshooting
If you encounter issues when sending SMS notifications:
- Verify your API key is valid and has the necessary permissions
- Check that the recipient phone numbers are correctly formatted
- Ensure the country codes match the phone numbers
- Review the response message for specific error details
Related Resources
Was this page useful?