Skip to contentSkip to navigationSkip to topbar
Page toolsOn this page
Looking for more inspiration?Visit the

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 SDKs 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:

1
const webhooks = require('twilio/lib/webhooks/webhooks');
2
const eventData = {
3
AccountSid: accountSid,
4
}
5
const signature = webhooks.getExpectedTwilioSignature(
6
authToken,
7
url,
8
eventData
9
);

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.

1
const webhooks = require('twilio/lib/webhooks/webhooks');
2
const { default: axios } = require('axios');
3
const assert = require('assert');
4
5
async function makeTwiMLBinRequest(url, data) {
6
// Get account credentials from your environment variables
7
const accountSid = process.env.TWILIO_ACCOUNT_SID;
8
const authToken = process.env.TWILIO_AUTH_TOKEN;
9
10
const eventData = {
11
AccountSid: accountSid,
12
...data
13
}
14
15
// Construct a valid application/x-www-form-urlencoded POST body
16
const params = new URLSearchParams();
17
for (const [key, value] of Object.entries(eventData)) {
18
params.append(key, value);
19
}
20
data = params.toString();
21
22
// Generate the X-Twilio-Signature
23
const signature = webhooks.getExpectedTwilioSignature(
24
authToken,
25
url,
26
eventData
27
);
28
const headers = {};
29
headers['X-Twilio-Signature'] = signature;
30
31
// Make the HTTP request to the passed URL
32
const response = await axios.request({
33
method: 'POST',
34
headers,
35
url,
36
data
37
})
38
return response.data;
39
}
40
41
// Make an HTTP request to your TwiML Bin
42
const response = await makeTwiMLBinRequest('https://handler.twilio.com/twiml/EHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', { Body: 'Hello' })
43
44
// Compare the output against your expected result
45
assert.deepEqual(response, `<?xml version="1.0" encoding="UTF-8"?>
46
<Response>
47
<Message>Ahoy</Message>
48
</Response>`);