Use Ngrok for Testing APIs on Dev

Recently I was hastily building an API for a client and I wanted to run some tests against it. I’ve written before about using Runscope for API testing, but this was against a local dev platform (inside a VM, not directly on my laptop) rather than a public API. The same problem arises if you want to access a local site or API from elsewhere or from a mobile device. In all these scenarios, ngrok is your friend.

Ngrok allows you to create a secure tunnel from wherever to the outside world, so it’s ideal for testing development APIs and I use it often for this type of thing. I also use it for debugging things that don’t need to be tunnelled particularly – ngrok provides a web interface which allows you to inspect traffic and replay requests (I’ve blogged about ngrok before, I use it with hubot for local development).

One thing which did trip me up and that I’d like to remember how to do in future, is how to set the Host header when using ngrok. You can’t send a Host header when you create the request, because ngrok routes traffic by host header, but what you can do is instruct the tunnel what the Host header should be set to, and it will do that on the way through. The command looks like this:

ngrok http --host-header=example.mysite.local 80

This opens an HTTP tunnel to port 80 (on my VM) to the outside world (ngrok assigns you a random URL) and to add the Host: example.mysite.local to the request as it comes through. For my local development server which uses the Host header to work out which apache vhost to use, this works really well. Using this approach I was able to develop and run my runscope tests against the local version of the API, and then change the environment settings and test again when we deployed to the other “real” platforms.

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.