Leverage Python open source libraries to monitor Salesforce Platform Events
If you already have experienced Salesforce Platform Event feature, you have probably been looking here and there for some sort of tool to help you catching your Platform Event, and displaying the payload in real time. This is useful especially for troubleshooting, to help identifying which application needs further investigations.
If you have never used or even tried Platform Events, you might just want to see it working end to end, just to see the magic happening!
In order to understand this article and successfully setup the whole end to end scenario, you should be familiar with the standard Salesforce platform features (creating custom fields, process builders, platform events). As a starting point, just navigate through the following trailheads if needed:
Creating Custom Fields
Quick start on Process Builder
Platform Event Basics
There is currently no online tool giving you the capability – without code – to simply subscribe to a Salesforce Platform Event and listen to it.
Salesforce is documenting on the Platform Event Basics trailhead different ways to achieve it from the same Salesforce org. We want to see it work from the outside!
I’ve found some very interesting Python open source libraries that will help us building a listener just in a couple of Python lines of code… Even better, I share below a turnkey script that you can just copy below and use on any type of Salesforce org. Pretty awesome isn’t it?!
The script runs locally on your computer, for security concerns as it will prompt for critical authentication information to access your Salesforce org. Better to know where is hosted and run the script then! Therefore you will need to have Python installed as well as one additional module. Just follow the guide below.
Enjoy!
Set your Platform Event ready in your Salesforce Org
Now, let’s start by creating a simple Platform Event on a Salesforce Developer org. In this post, just to illustrate a simple scenario, we’ll trigger a new Platform Event for every new created Account and send its ID (Standard field), Name (Standard field) and ExternalID (Custom field). Our Python application, which will be listening to our Platform Event, will then catch these information and display them in near real time.
Just follow the high level steps in the order below:
- Create an ExternalID custom field on your Account object
- Create a Platform Event (Setup -> Integrations -> Platform Events) with the standard defaults
- Once created the Platform Event is considered as a new object, ending with __e instead of __c. Create new Custom Fields in there, as much as you want to send to your tierce application. Here let’s create 3, to host the Account Name, Account ExternalID and Account ID
- Create a Process Builder which satisfy your conditions (here New Account) and create a new record into your new Platform Event object
Here how it should look like:
Set your API user and your Salesforce Connected App
Now our Platform Event is created; let’s create an API user and a Connected App, so that external applications can interact with our Salesforce org. We will use OAUTH2 Username/Password flow in our example.
In order to setup the API user, please follow our recommendations on the following post: how to setup your Salesforce API user.
In order to setup and test the Connected App, please follow our previous post: test your Salesforce Connected App using postman.
Now your profile is created, grant access to the Platform Event, through the Object section, at least READ permission.
Setup Python and configure the prerequisites on your computer
In order to run Python script locally you have to install it.
Just download it from the officiel Python website and install the last available version (min v3.6.0).
We need to install 2 additional modules:
– aiosfstream: this is a Salesforce Streaming API client
– asyncio: an asynchronous framework to keep on listening for incoming messages
To install modules in Python:
1. Open up the Command Line from your OS. For Windows, hit Windows + R, then enter cmd and hit enter
2. Enter the following command to install asyncio:
python -m pip install asyncio
3. Enter the following command to install aiosfstream
python -m pip install aiosfstream
Here it is! You are not all set up to start listening to your Platform Event!
Run Python locally and listen to your Platform Event
Now, create a folder where you want to store the code source below. You also can download a more elaborated version shared after the code snippet, prompting you to enter you credentials instead of modifying the Python script every time you want to switch org and also enabling you to select on which type of Salesforce org you want to connect (Production/Developer or Sandbox). By default the script below is authenticating against login.salesforce.com.
import asyncio from aiosfstream import SalesforceStreamingClient async def stream_events(): # connect to your Salesforce Org (Production or Developer org) async with SalesforceStreamingClient( consumer_key="yourconnectedappconsumerkey", consumer_secret="yourconnectedappconsumersecret", username="username@salesforce.com", password="password+securitytoken") as client: # subscribe to the platform event using CometD await client.subscribe("/event/NewAccount__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(stream_events())
After downloading the file below, unzip it and execute the .py file from Command Line.
Hint: to stop the program, just hit CTRL+C