In-App Notifications
In-app notifications allow you to communicate timely information to your users directly within your application interface. These notifications can display alerts, announcements, and other important information that enhances user experience and engagement.
Overview
The In-App Notifications API provides endpoints to:
- Retrieve unseen notifications for users
- Mark notifications as seen
- Add target users to notifications
Retrieving Unseen Notifications
Retrieve all unseen notifications for a user with the GET /Notifications/{notificationType}/unseen
endpoint.
- C#
- Java
- Python
- JavaScript
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text.Json;
public class NotificationService
{
private readonly HttpClient _client;
private readonly string _baseUrl = "https://apis.lightstone.co.za/lightstone-capabilities-notifications-api/v1";
public NotificationService(string apiKey)
{
_client = new HttpClient();
_client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apiKey);
}
public async Task<List<Notification>> GetUnseenNotificationsAsync(
string notificationType,
string category = null,
string tenantId = null,
string correlationId = null,
string partyId = null)
{
var requestUrl = $"{_baseUrl}/Notifications/{notificationType}/unseen";
if (!string.IsNullOrEmpty(category))
{
requestUrl += $"?category={category}";
}
if (!string.IsNullOrEmpty(tenantId))
{
_client.DefaultRequestHeaders.Add("x-Authenticated-TenantId", tenantId);
}
if (!string.IsNullOrEmpty(correlationId))
{
_client.DefaultRequestHeaders.Add("correlationid", correlationId);
}
if (!string.IsNullOrEmpty(partyId))
{
_client.DefaultRequestHeaders.Add("x-ls-party-id", partyId);
}
var response = await _client.GetAsync(requestUrl);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<List<Notification>>(content);
}
}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
public class NotificationService {
private final HttpClient client;
private final String baseUrl = "https://apis.lightstone.co.za/lightstone-capabilities-notifications-api/v1";
private final String apiKey;
public NotificationService(String apiKey) {
this.client = HttpClient.newHttpClient();
this.apiKey = apiKey;
}
public List<Notification> getUnseenNotifications(
String notificationType,
String category,
String tenantId,
String correlationId,
String partyId) throws Exception {
StringBuilder requestUrl = new StringBuilder(baseUrl + "/Notifications/" + notificationType + "/unseen");
if (category != null && !category.isEmpty()) {
requestUrl.append("?category=").append(category);
}
HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
.uri(URI.create(requestUrl.toString()))
.header("Ocp-Apim-Subscription-Key", apiKey)
.GET();
if (tenantId != null && !tenantId.isEmpty()) {
requestBuilder.header("x-Authenticated-TenantId", tenantId);
}
if (correlationId != null && !correlationId.isEmpty()) {
requestBuilder.header("correlationid", correlationId);
}
if (partyId != null && !partyId.isEmpty()) {
requestBuilder.header("x-ls-party-id", partyId);
}
HttpResponse<String> response = client.send(
requestBuilder.build(),
HttpResponse.BodyHandlers.ofString()
);
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(response.body(), new TypeReference<List<Notification>>(){});
}
}
import requests
import json
from typing import List, Optional
class NotificationService:
def __init__(self, api_key: str):
self.base_url = "https://apis.lightstone.co.za/lightstone-capabilities-notifications-api/v1"
self.api_key = api_key
def get_unseen_notifications(
self,
notification_type: str,
category: Optional[str] = None,
tenant_id: Optional[str] = None,
correlation_id: Optional[str] = None,
party_id: Optional[str] = None
) -> List[dict]:
"""
Retrieve unseen notifications for a user.
"""
url = f"{self.base_url}/Notifications/{notification_type}/unseen"
# Add query parameters if provided
params = {}
if category:
params['category'] = category
# Prepare headers
headers = {
'Ocp-Apim-Subscription-Key': self.api_key
}
if tenant_id:
headers['x-Authenticated-TenantId'] = tenant_id
if correlation_id:
headers['correlationid'] = correlation_id
if party_id:
headers['x-ls-party-id'] = party_id
# Make the request
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
return response.json()
class NotificationService {
constructor(apiKey) {
this.baseUrl = 'https://apis.lightstone.co.za/lightstone-capabilities-notifications-api/v1';
this.apiKey = apiKey;
}
async getUnseenNotifications(notificationType, options = {}) {
const { category, tenantId, correlationId, partyId } = options;
let url = `${this.baseUrl}/Notifications/${notificationType}/unseen`;
// Add query parameters if provided
const params = new URLSearchParams();
if (category) {
params.append('category', category);
}
if (params.toString()) {
url += `?${params.toString()}`;
}
// Prepare headers
const headers = {
'Ocp-Apim-Subscription-Key': this.apiKey
};
if (tenantId) {
headers['x-Authenticated-TenantId'] = tenantId;
}
if (correlationId) {
headers['correlationid'] = correlationId;
}
if (partyId) {
headers['x-ls-party-id'] = partyId;
}
// Make the request
const response = await fetch(url, {
method: 'GET',
headers
});
if (!response.ok) {
throw new Error(`Error fetching notifications: ${response.statusText}`);
}
return response.json();
}
}
Marking Notifications as Seen
After a user views a notification, mark it as seen with the POST /Notifications/{name}/seen
endpoint.
- C#
- Java
- Python
- JavaScript
public class MarkAsSeenRequest
{
public string FlagValue { get; set; }
}
public class NotificationService
{
// ...existing code...
public async Task MarkNotificationAsSeenAsync(
string notificationName,
string flagValue = null,
string tenantId = null,
string correlationId = null,
string partyId = null)
{
var requestUrl = $"{_baseUrl}/Notifications/{notificationName}/seen";
if (!string.IsNullOrEmpty(tenantId))
{
_client.DefaultRequestHeaders.Add("x-Authenticated-TenantId", tenantId);
}
if (!string.IsNullOrEmpty(correlationId))
{
_client.DefaultRequestHeaders.Add("correlationid", correlationId);
}
if (!string.IsNullOrEmpty(partyId))
{
_client.DefaultRequestHeaders.Add("x-ls-party-id", partyId);
}
var payload = new MarkAsSeenRequest
{
FlagValue = flagValue
};
var content = new StringContent(JsonSerializer.Serialize(payload), System.Text.Encoding.UTF8, "application/json");
var response = await _client.PostAsync(requestUrl, content);
response.EnsureSuccessStatusCode();
}
}
public class NotificationService {
// ...existing code...
public void markNotificationAsSeen(
String notificationName,
String flagValue,
String tenantId,
String correlationId,
String partyId) throws Exception {
String requestUrl = baseUrl + "/Notifications/" + notificationName + "/seen";
ObjectMapper mapper = new ObjectMapper();
Map<String, String> payload = new HashMap<>();
if (flagValue != null && !flagValue.isEmpty()) {
payload.put("flagValue", flagValue);
}
HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
.uri(URI.create(requestUrl))
.header("Content-Type", "application/json")
.header("Ocp-Apim-Subscription-Key", apiKey)
.POST(HttpRequest.BodyPublishers.ofString(mapper.writeValueAsString(payload)));
if (tenantId != null && !tenantId.isEmpty()) {
requestBuilder.header("x-Authenticated-TenantId", tenantId);
}
if (correlationId != null && !correlationId.isEmpty()) {
requestBuilder.header("correlationid", correlationId);
}
if (partyId != null && !partyId.isEmpty()) {
requestBuilder.header("x-ls-party-id", partyId);
}
HttpResponse<String> response = client.send(
requestBuilder.build(),
HttpResponse.BodyHandlers.ofString()
);
if (response.statusCode() != 200) {
throw new RuntimeException("Failed to mark notification as seen: " + response.body());
}
}
}
def mark_notification_as_seen(
self,
notification_name: str,
flag_value: Optional[str] = None,
tenant_id: Optional[str] = None,
correlation_id: Optional[str] = None,
party_id: Optional[str] = None
) -> None:
"""
Mark a notification as seen.
"""
url = f"{self.base_url}/Notifications/{notification_name}/seen"
# Prepare headers
headers = {
'Ocp-Apim-Subscription-Key': self.api_key,
'Content-Type': 'application/json'
}
if tenant_id:
headers['x-Authenticated-TenantId'] = tenant_id
if correlation_id:
headers['correlationid'] = correlation_id
if party_id:
headers['x-ls-party-id'] = party_id
# Prepare payload
payload = {}
if flag_value:
payload['flagValue'] = flag_value
# Make the request
response = requests.post(url, headers=headers, json=payload)
response.raise_for_status()
async markNotificationAsSeen(notificationName, options = {}) {
const { flagValue, tenantId, correlationId, partyId } = options;
const url = `${this.baseUrl}/Notifications/${notificationName}/seen`;
// Prepare headers
const headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': this.apiKey
};
if (tenantId) {
headers['x-Authenticated-TenantId'] = tenantId;
}
if (correlationId) {
headers['correlationid'] = correlationId;
}
if (partyId) {
headers['x-ls-party-id'] = partyId;
}
// Prepare payload
const payload = {};
if (flagValue) {
payload.flagValue = flagValue;
}
// Make the request
const response = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error(`Failed to mark notification as seen: ${response.statusText}`);
}
}
Adding Target Users to Notifications
Associate specific users with a notification using the POST /Notifications/{notificationId}/addTargetUsers
endpoint.
- C#
- Java
- Python
- JavaScript
public class NotificationService
{
// ...existing code...
public async Task AddTargetUsersToNotificationAsync(
Guid notificationId,
List<string> userIds,
string correlationId = null,
string partyId = null)
{
var requestUrl = $"{_baseUrl}/Notifications/{notificationId}/addTargetUsers";
if (!string.IsNullOrEmpty(correlationId))
{
_client.DefaultRequestHeaders.Add("correlationid", correlationId);
}
if (!string.IsNullOrEmpty(partyId))
{
_client.DefaultRequestHeaders.Add("x-ls-party-id", partyId);
}
var content = new StringContent(JsonSerializer.Serialize(userIds), System.Text.Encoding.UTF8, "application/json");
var response = await _client.PostAsync(requestUrl, content);
response.EnsureSuccessStatusCode();
}
}
public class NotificationService {
// ...existing code...
public void addTargetUsersToNotification(
UUID notificationId,
List<String> userIds,
String correlationId,
String partyId) throws Exception {
String requestUrl = baseUrl + "/Notifications/" + notificationId.toString() + "/addTargetUsers";
ObjectMapper mapper = new ObjectMapper();
String payload = mapper.writeValueAsString(userIds);
HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
.uri(URI.create(requestUrl))
.header("Content-Type", "application/json")
.header("Ocp-Apim-Subscription-Key", apiKey)
.POST(HttpRequest.BodyPublishers.ofString(payload));
if (correlationId != null && !correlationId.isEmpty()) {
requestBuilder.header("correlationid", correlationId);
}
if (partyId != null && !partyId.isEmpty()) {
requestBuilder.header("x-ls-party-id", partyId);
}
HttpResponse<String> response = client.send(
requestBuilder.build(),
HttpResponse.BodyHandlers.ofString()
);
if (response.statusCode() != 200) {
throw new RuntimeException("Failed to add target users: " + response.body());
}
}
}
def add_target_users_to_notification(
self,
notification_id: str,
user_ids: List[str],
correlation_id: Optional[str] = None,
party_id: Optional[str] = None
) -> None:
"""
Add target users to a notification.
"""
url = f"{self.base_url}/Notifications/{notification_id}/addTargetUsers"
# Prepare headers
headers = {
'Ocp-Apim-Subscription-Key': self.api_key,
'Content-Type': 'application/json'
}
if correlation_id:
headers['correlationid'] = correlation_id
if party_id:
headers['x-ls-party-id'] = party_id
# Make the request
response = requests.post(url, headers=headers, json=user_ids)
response.raise_for_status()
async addTargetUsersToNotification(notificationId, userIds, options = {}) {
const { correlationId, partyId } = options;
const url = `${this.baseUrl}/Notifications/${notificationId}/addTargetUsers`;
// Prepare headers
const headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': this.apiKey
};
if (correlationId) {
headers['correlationid'] = correlationId;
}
if (partyId) {
headers['x-ls-party-id'] = partyId;
}
// Make the request
const response = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(userIds)
});
if (!response.ok) {
throw new Error(`Failed to add target users: ${response.statusText}`);
}
}
Notification Object Structure
When retrieving notifications, the API returns a list of notification objects with the following structure:
{
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"name": "notification-name",
"tag": "notification-tag",
"heading": "Notification Heading",
"description": "Detailed description of the notification",
"imageUrl": "https://example.com/image.png",
"primaryButtonText": "Action",
"primaryButtonValue": "action-value",
"secondaryButtonText": "Dismiss",
"secondaryButtonValue": "dismiss-value",
"notificationType": 863480000,
"startDate": "2023-01-01T00:00:00Z",
"endDate": "2023-12-31T23:59:59Z",
"closeable": true,
"notificationCategory": 863480000,
"viewMoreLocation": "/details",
"viewMoreText": "View more",
"microFrontEndUrl": "https://example.com/micro-frontend"
}
Best Practices
- Poll for new notifications: Set up a polling mechanism to check for new notifications periodically.
- Cache notifications: Store retrieved notifications in a local cache to reduce API calls.
- Prioritize notifications: Display high-priority notifications more prominently in your UI.
- Group by category: Organize notifications by category for a better user experience.
- Handle expired notifications: Check the
endDate
and don't display expired notifications.
Implementation Checklist
- Authenticate with the API using your subscription key
- Periodically fetch unseen notifications for the current user
- Display notifications in your application UI
- Mark notifications as seen when the user interacts with them
- Add target users to notifications when creating custom notifications
Related Resources
Was this page useful?