Simple Webhook Testing Using Sinatra and ngrok


February 13, 2015
Written by
SendGrid Team
Contributor
Opinions expressed by Twilio contributors are their own

Simple Webhook Testing Using Sinatra and ngrok

Webhooks allow for simple, deep integration between apps and services, but debugging them can be a little painful. We have a general guide to debugging webhooks, but you probably want to know what the quickest webhook test environment is for setting-up and using. It's hard to beat Sinatra and ngrok for this purpose. Or, if you'd rather use node.js, you can check-out Martyn's post on Testing Webhooks.

Getting Started

First, you need a ruby environment that has rubygems. If you are new to ruby, then check out rbenv for getting your environment going.

Create a new directory and run gem install sinatra. Now let's make a simple Sinatra app.

Create a file called webhook.rb. We're going to use the SendGrid Event Webhook in this example.

The event webhook returns a JSON body. Let's log the whole JSON payload for each event and append it to a text file in your new webhook.rb:



Boom. We've told Sinatra to accept POST requests at the /event URL and to execute some code based on those requests.

Run Sinatra and Expose Your App to the Internet

Fire up your app by running ruby webhook.rb. Sinatra will launch a WEBrick web server and tell you what port it's running on. By default it's 4567.

Now we need to expose this running instance to the internet. ngrok to the rescue! Follow the installation instructions, and then launch a new instance of your terminal. Run ngrok 4567 and look for your one-off ngrok URL. If you hit your ngrok URL in a browser, you should see the default "no route" page from Sinatra.

Screen Shot 2015-02-12 at 12.21.55 PM

Now configure your SendGrid event notification app to use your ngrok URL. Don't forget to add /event to the URL since that's the route we defined in Sinatra.

Screen Shot 2015-02-12 at 12.22.18 PM

Go ahead and hit the "Test Your Integration" button, or head over to the Mail API reference page and hit "Try It" to send an email.

It Worked!

Your terminal window running ngrok should show you some HTTP requests being tunneled, and you'll see the same requests in the terminal running your Sinatra app.

Screen Shot 2015-02-12 at 12.25.01 PM

You'll also have an events.txt file in your Sinatra app directory that contains something like this: 


That's all there is to it! Now you can inspect what the events look like and start playing around with different workflows utilizing the contents of the JSON payload.

Recommended For You



Most Popular


Send With Confidence

Partner with the email service trusted by developers and marketers for time-savings, scalability, and delivery expertise.