Step 5: Write Code That Publishes a Platform Event Message

Follow instructions in this step to build a publisher client.

When you copy the code snippets in this page, ensure that the indentation starts from the comment block below the with grpc.secure_channel statement that you added in Step 2: Build the Python Client. In Python, code blocks are delimited by their indentation.

Before you publish a custom platform event message, ensure that the platform event is defined in your org. You can view defined platform events in Setup on the Platform Events page.

For example, this image shows the definition of Order_Event__e. This event has two fields: Order_Number__c of type Text and Has_Shipped__c of type Checkbox.

The Order Event detail page

  1. Create a separate Python file, publish.py, for publishing so that you can run the publisher and subscriber clients independently. Include common code from the subscriber client that you created earlier. Include the import statements, code for creating the channel, the authentication code to build authmetadata, and the stub. Also, add this import statement: from datetime import datetime, timedelta

  2. Get the topic name for the event that you want to publish. The topic format is /event/EventName__e. For example, for Order_Event__e the topic is /event/Order_Event__e. You use it in the next step.

  3. Replace the mypubtopic placeholder value with your topic. Get the schema ID and schema for the event. To get the schema ID, call the GetTopic method and pass the topic name. Next, pass the schema ID to the GetSchema method, which returns the schema.

  4. Create a function to encode the information that you want to send by using the schema.

  5. Create a function that creates a PublishRequest. Construct the payload by adding the event fields and values in the payload variable. Populate the values of the required system fields: CreatedDate and CreatedById. The CreatedById value isn’t validated. For {event field}: {field value}, list the event fields and values. For example, for Order_Event__e, you can add:

    The req variable contains the encoded payload, which is returned by the encode function. It also contains the schema ID.

  6. Make the publish call, and handle any acknowledgements that you get back.

  7. Modify your subscriber client, PubSubAPIClient.py, to susbribe to the platform event.

  8. Run the client by entering this command on the command line.

    If the publish request is successful, you receive a PublishResponse message containing the replay ID. The subscriber client receives and displays the event message.

    If the publish request wasn’t successful, you get an error similar to: