CloudPython

Salesforce Platform Events Using Python

Salesforce publishes standard platform events in response to an action that occurred in the org or to report errors. For example, LoginEventStream monitors user login activity and BatchApexErrorEvent reports errors encountered in batch Apex jobs.

In this article, we are going to implement and publish a Platform Event in Salesforce and subscribe to it from outside Salesforce using Python.

We will have 2 parts in this article.

1)The authentication to Salesforce from Python

2)Creation of Platform Events in Salesforce and their consumption from Python.

Authentication to Salesforce from Python

Before we start with the Platform Events, we need to set up two preconditions in Salesforce for the authentication from the outside world — a Connected App & a User.

1) Connected App in Salesforce

To create a Connected App, navigate to Setup > App Manager > New Connected App. You need to specify a name, your email and ensure to Enable OAuth Settings. Additionally, select the required OAuth Scopes.

Connected App
Platform Event

Save the Connected App and note down your Consumer Key & Secret.

  •  User in Salesforce

2)To create a new User, navigate to Setup > Users > New User. You need to specify a username and a Profile. For now just select System Administrator.

User creation
Platform Event Config

Note down the Username. Additionally, trigger a Password Reset for the user and note down the Password and the Security Token for the user.

3) Test Authentication from Python

Now we can test the authentication to Salesforce from Python.

import requests

salesforceAuthUrl = "https://test.salesforce.com/services/oauth2/token"
parameter = {
‘grant_type’ : 'password',
‘username’ : ‘<salesforce username>’,
‘password’ : ‘<password+security token>’,
‘client_id’ : ‘<consumer key from connected app>’,

‘client_secret’:'<client screct for connected app>’
}

response = requests.post(salesforceAuthUrl, params=parameter)
print(response.status_code)
print(response.text)

Run the Above code.

Subscribe to Platform Events from Python

In Salesforce we have the full overview of our customer data. Whenever a new Account is created, we want to fire a Platform Event with the Account’s name, the website, and the Salesforce Account Id.

Salesforce Account
Platform Event
  • 1) Create a Platform Event

The Platform Event defines the event schema or model. To create a Platform Event move to Setup → Integrations → Platform Events and create a new Platform Event AccountEvent with three custom fields AccountIdAccountName and AccountWebsite as shown in the below screenshots.

Salesforce Platform Events
Setup-Events
platform events2
  • 2) Publish a Platform Event (with Process Builder)

To publish Platform Event whenever an Account is created we will set up a Process Builder. To create a Process move to Setup → Process Automation → Process Builder and create a new Process AccountCreate.

Trigger the process whenever a new Account is created and map the three fields from your Account (Id, Name, Website) to your Platform Events custom fields AccountIdAccountName and AccountWebsite as shown in the below screenshots.

Salesforce Process Builder
Salesforce Process Builder1
Flows

Once done you are already creating Platform Events when a new Account is created.

3) Subscribe to Platform Event from Python

Subscribe to the Salesforce Platform Event from Python.

import asyncio
from aiosfstream import SalesforceStreamingClient

async def subscribeToSalesforce():
    async with SalesforceStreamingClient(
            #Connect to Salesforce streaming API
            consumer_key='<Enter Consumer Key from your Connected App',
            consumer_secret='<Enter Consumer Secret from your Connected App>',
            username='<Enter Salesforce username>',
            password='<Enter password+security token>') as client:

        #Subscribe to one or more topics
        await client.subscribe("/event/AccountEvent__e")
        
        # listen for incoming messages
        async for message in client:
            topic = message["channel"]
            data = message["data"]
            print(f"{topic}: {data}")

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(subscribeToSalesforce())

Run the above code. It will start listening to the new messages.

>When we create a new Account in Salesforce, then this will trigger the Platform Event creation. As soon as we hit the Save Button, a new Platform Event will be created.

Loading

Translate »