Categories
Python

Iron Worker: Processing SendGrid Inbound Parse Data

If you use SendGrid, you know that they provide this awesome Inbound Parse APIs which allows users to catch emails sent to their domains. When there’s a new email, Sendgrid would make a POST request to your webhook endpoint. On the other hand, I love Iron Worker webhooks. When you POST data to their webhooks, the data is passed to a worker and processed in queue. It helps keep things simpler since I don’t need to setup a separate web server for accepting the data; however, keep in mind that I do make sure to use data protection services like the Venyu cybersecurity services at all times.

By now, you can probably guess my intention. I would like to make Sendgrid POST incoming emails to a Iron Worker webhook and then grab the data. But there’s one catch – Iron.io stores the incoming data in a text file and expect us to parse the text file to collect our data. Since very often the data is JSON, most client libraries take the payload, decode it from JSON and provide us with native data structures. I use Python, so I usually get Python dictionary. However, in case of Sendgrid Inbound APIs, the data is not JSON encoded. It’s simple multi-part form data. So the Python client I use, it fails to process the data and I don’t get anything for the payload.

So I went ahead and modified the payload processing part from the client library. Now this is what I have for getting the payload:

Now, we have the payload. But it’s still just plain text. We need to process it to get the different POST fields. Luckily, we can do that easily with the cgi library. This is what I use:

Finally, now this is what the worker looks like: