One can publish platform events via Apex (Apex is a language used in Salesforce to write business logic) or via SOAP and REST API.
To demonstrate how one can publish an event using platform events, let's run a simple Apex code from the developer console:
List<Temperature_Sensor__e> temperatureSensorEvents =
new List<Temperature_Sensor__e>();
temperatureSensorEvents.add(new Temperature_Sensor__e
(CustomerId__c='12345', DeviceId__c='12345', Temperature__c=30));
temperatureSensorEvents.add(new Temperature_Sensor__e
(CustomerId__c= '12345', DeviceId__c='10013',Temperature__c=40));
// Call method to publish events
List<Database.SaveResult> results = EventBus.publish
(temperatureSensorEvents);
// Inspect publishing result for each event
for (Database.SaveResult sr : results) {
if (sr.isSuccess()) {
System.debug('Successfully published event.');
}
else {
for(Database.Error err : sr.getErrors()) {
System.debug('Error returned: ' +
err.getStatusCode() +
' - ' +
err.getMessage());
}
}
}
Open the developer console using the Setup menu and run the preceding code:
Using the Salesforce REST API or SOAP API, a device can push these events to Salesforce. For our examples, the API to publish the events will be as shown in the following code. A third-party client needs to make an HTTP POST to the following URL:
/services/data/v40.0/sobjects/Temperature_Sensor__e/
The sample payload any device needs to be pushed as shown here:
{
"CustomerId__c": "12345",
"DeviceId__c": "12345",
"Temperature__c": 50
}
To connect to Salesforce using the REST API, the external device has to authenticate with Salesforce using the OAuth 2.0 protocol. One has to create a connected application in Salesforce.