Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

Programmatic testing of TwiML Bins


If you want to programmatically test your TwiML Bins, you'll have to generate a valid X-Twilio-Signature using your Account SID and Auth Token, and then make an HTTP request to your TwiML Bin URL that contains:

  1. The X-Twilio-Signature HTTP header
  2. The AccountSid either as a query parameter or POST body parameter

Generating the X-Twilio-Signature

generating-the-x-twilio-signature page anchor

Some of our helper libraries provide you with the ability to generate an X-Twilio-Signature to verify that a webhook request comes from your Twilio account. You can use the same tooling to generate a valid X-Twilio-Signature. For example, in Node.js this would look like:


_10
const webhooks = require('twilio/lib/webhooks/webhooks');
_10
const eventData = {
_10
AccountSid: accountSid,
_10
}
_10
const signature = webhooks.getExpectedTwilioSignature(
_10
authToken,
_10
url,
_10
eventData
_10
);

Using this data, you can then make your HTTP request successfully, as long as you pass an X-Twilio-Signature HTTP header and the same data in the POST body that you passed to the eventData object of the getExpectedTwilioSignature() function.


Here's a full example in Node.js that makes an HTTP request using Axios to a TwiML Bin URL, and compares the result against the expected result.


_48
const webhooks = require('twilio/lib/webhooks/webhooks');
_48
const { default: axios } = require('axios');
_48
const assert = require('assert');
_48
_48
async function makeTwiMLBinRequest(url, data) {
_48
// Get account credentials from your environment variables
_48
const accountSid = process.env.TWILIO_ACCOUNT_SID;
_48
const authToken = process.env.TWILIO_AUTH_TOKEN;
_48
_48
const eventData = {
_48
AccountSid: accountSid,
_48
...data
_48
}
_48
_48
// Construct a valid application/x-www-form-urlencoded POST body
_48
const params = new URLSearchParams();
_48
for (const [key, value] of Object.entries(eventData)) {
_48
params.append(key, value);
_48
}
_48
data = params.toString();
_48
_48
// Generate the X-Twilio-Signature
_48
const signature = webhooks.getExpectedTwilioSignature(
_48
authToken,
_48
url,
_48
eventData
_48
);
_48
const headers = {};
_48
headers['X-Twilio-Signature'] = signature;
_48
_48
// Make the HTTP request to the passed URL
_48
const response = await axios.request({
_48
method: 'POST',
_48
headers,
_48
url,
_48
data
_48
})
_48
return response.data;
_48
}
_48
_48
// Make an HTTP request to your TwiML Bin
_48
const response = await makeTwiMLBinRequest('https://handler.twilio.com/twiml/EHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', { Body: 'Hello' })
_48
_48
// Compare the output against your expected result
_48
assert.deepEqual(response, `<?xml version="1.0" encoding="UTF-8"?>
_48
<Response>
_48
<Message>Ahoy</Message>
_48
</Response>`);


Rate this page: