Tutorial to setup Azure EventGrid Topic to call Azure Function, that triggers a Sendgrid email

Arjit Sharma
Analytics Vidhya
Published in
7 min readApr 20, 2019

--

Azure Eventgrid has virtually solved our all our needs to wait for an action(or event) to be performed, to trigger a some task. It eliminate the polling and unnecessary cost involved in it.
We can setup a serverless monitoring system in literally minutes (Follow the below 6 steps)to send us a notification for a action.
Just a quick note on key terminologies:
Event → Any action is a event (e.g. Http request received, creating a blob storage, commissioning / decommissioning of a VM)
Topic → Topic is the endpoint where the publisher will send the event. For all the azure services, they have their topic already pre-created,so for example we do not have to create topic for azure blob storage.
Event subscription → A built in mechanism inside event grid where the events get routed to single or multiple subscriber.
Event handler Service that reacts to the events that come through from the topic and the specific subscription.
Publisher → The application that triggers events to the topic. In our case we will publish the custom message using PostMan
Subscriber → The application that wait for a specific event to be triggered for a topic it is subscribed to.

Not going into much in theory of what a event is, or what is a difference between pre created and custom events, as all this you can read via Google or Microsoft docs.

Just starting to do our hands dirty..! Here is the list of what we need:

STEP 0 — Pre-Requisties

  1. Azure Subscription
  2. Visual Studio Code* (in our case we will be writing the function directly on portal)
  3. Sendgrid account.
  4. Postman for Testing purpose

Yes thats it..!!

STEP 1 — Setup Eventgrid Topic

Login to Azure Portal and click on create a resource, search for Event Grid Topics

Click on Add (to add the new topic) and fill in the required details (screenshot below).

Click on the topic to view the topic details:

Keep a note of your topic endpoint url and Subscription ID.

STEP 2 — Setup Azure Function

Serverless is one of the best invention that come as part of cloud computation. Now we will write a Azure Function that will subscribe to our topic — “ProofOfConcept”.

Click on Home → Function App → Add, enter the required details and click on create.

I used the Runtime Stack as .Net. [When you use Azure, be ready to use Windows and .Net ;-)]

The function app will allow us to write function logic to call the sendgrid api.

Once the function app is created(it will take couple of minutes), click on view resource.

Your FunctionApp is ready and now its time to create a Function inside it, where our logic of calling Sendgrid email on an event trigger, will reside.

STEP 3 — Write your Function Logic

Click on Add button on Functions. Choose your preferred way to write the function logic. For this tutorial, I am choosing directly via portal.

Click on more templates as we need to select Azure Event Grid Template

And finally select Azure Event Grid trigger. It might ask you to install “Microsoft.Azure. WebJobs.Extensions.EventGrid extension”. Just click on install the extension.

Next write the function name and click on create. This will open a text editor with some initial lines of code.

You can see in Run method EventGrid is added as an argument as we selected it via template.

Write the following line of code to configure email sending.


#r "Microsoft.Azure.EventGrid"
#r "SendGrid"
using SendGrid.Helpers.Mail;
using Microsoft.Azure.EventGrid.Models;
using System.Net.Http;
public static void Run(EventGridEvent eventGridEvent
,ILogger log
,out SendGridMessage message)
{
log.LogInformation(eventGridEvent.Data.ToString());
message = new SendGridMessage();
message.SetSubject("Message Via Azure Event Grid");
message.PlainTextContent= eventGridEvent.Data.ToString();
}

The above code will not compile or run as we have still not configured Eventgrid. So let’s do it. Save the Function code. Now let’s try setting up the Eventgrid.

STEP 4 — Setup Eventgrid as output parameter

On the left panel of Function App, where we have our TestEvntGrdTrigrFunc function, click on integrate, then select click on new output and select SendGrid.

Then update all the required details in SendGrid output parameters. Enter the To and From Email Id, Subject (if you not want to set via code) Body and most importantly SendGrid API key app setting field.

Record your sendgrid API key in Function Configuration and then select from the dropdownlist of SendGrid API key app setting. (if you have any questions regarding this please let me know in comment box and i’ll try to answer with best of my knowledge.)

Now our Function is ready, but we are missing a key step here. Out Azure function is still not subscribed to the EventGrid topic. So let’s do it.

STEP 5 — Add Eventgrid Subscription

There are multiple ways to add eventgrid subscription, the most easy way to do it is through function app only. :-)

Go to your function and click on top link, Add Event grid Subscription.

Enter the Event Subscription details. (I have given the name of Subscription as TestConnection). In the Topic Details enter :
→ Topic Type as Event Grid Topics
→ Subscription as Your Subscription
→ Resource Group as Your Resource Group
→ Resource as Your Topic (here it is ProofOfConcept as Topic name)

Once you press on create and your resource subscription is created, you can see the same under your Topic (ProofofConcept) subscription list.
Yay it there…..!!!!

Everything is now ready and we just need to test it. We can use Postman to test. We have to follow a protocol to publish the event to the Topic.Whether we’re working with custom or built-in events, there are some mandatory fields in every event.

  • Id — A unique ID for event.
  • Subject — Any name or label that have any relevance for our application. This is a good place to put the name of the service/entity that the event is related to.
  • EventType — A value we can create filters against, e.g. CustomerCreated, BlobDeleted, HttpRequestReceived, etc.
  • EventTime — The timestamp for when the event happened in the publisher.
  • Data — Relevant information that’s need to act on this event. This field is optional. However in custom event, this is the field we use to provide details to our Azure function.

Example of one custom event (provided by Azure)

[
{ "id": "1807",
"eventType": "recordInserted",
"subject": "myapp/vehicles/motorcycles",
"eventTime": "2017-08-10T21:03:07+00:00",
"data": {
"make": "Ducati",
"model": "Monster"
},
"dataVersion": "1.0",
"metadataVersion": "1",
"topic": "/subscriptions/{subscription-id}/resourceGroups/{resource-group}/providers/Microsoft.EventGrid/topics/{topic}"
}
]

The topic tag is very important here.

"topic": "/subscriptions/{subscription-id}/resourceGroups/{resource-group}/providers/Microsoft.EventGrid/topics/{topic}"

{subscription-id} → This the Subscription ID for the Azure Function.
{resource-group} → Your Resource Group Name
{topic} → Your Topic Name (in our case it is ProofofConcept)

Everything is now ready, let’s test it using Postman.

STEP 6 — Finally Testing with PostMan

  1. Open Postman, select the method as Post
  2. Enter the API (Topic Endpoint) — https://proofofconcept.westeurope-1.eventgrid.azure.net/api/events
  3. Copy the above example custom message in the body section (as raw JSON). make sure to update your topic details.
  4. Finally a very Important Thing — In the header section add a key value pair (the authentication key):
    Key Name — aeg-sas-key
    Value — The value of your key from the access keys of the topic

That’s It…..!!!!

Your custom topic publish message sending is ready. Now whenever you publish your message (event) to your Topic it will trigger a Azure Function to shoot a email.

Hope you find this article useful. Show your love with a clap. :-) Do kindly let me know in case you find any difficulty setting it up or if you think there is any scope of updates or improvement.

--

--

Arjit Sharma
Analytics Vidhya

My favourite Quote — printf(“Hello World..!”)