Mohammad Raheem
Mohammad Raheem

Reputation: 1157

Node.js Twilio make calls using REST API

I am trying to make call from the Twilio REST API but I am getting an error, looks like I missed something, any help will appreciate:

var options = { method: 'POST',
  url: 'https://[email protected]/2010-04-01/Accounts/xxxxxxxxxxx/Calls',
  headers: 
   { 
     'Cache-Control': 'no-cache',
     'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' },
  formData: 
   { To: '+919200070974',
     From: '14245060471',
     Url: '<?xml version="1.0" encoding="UTF-8"?>\n<Response>\n    <Say voice="woman">This is me....</Say>\n</Response>'} };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});

Now I set url parameters but its showing invalid

    <?xml version='1.0' encoding='UTF-8'?>
<TwilioResponse>
    <RestException>
        <Code>21205</Code>
        <Message>Url is not a valid url: &lt;?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say voice="woman">This is me....</Say>
</Response></Message>
        <MoreInfo>https://www.twilio.com/docs/errors/21205</MoreInfo>
        <Status>400</Status>
    </RestException>
</TwilioResponse>

I am not getting where I have to set URL parameter, I didn't find in the documentation clearly what I have to set.

Upvotes: 0

Views: 1336

Answers (2)

philnash
philnash

Reputation: 73027

Twilio developer evangelist here.

What you need to do in this case, is send to Twilio a URL. When the call connects, Twilio will then make a request to that URL to get the TwiML response.

From the documentation:

When you initiate a call through the REST API, Twilio makes a synchronous HTTP request to the URL found in the value of the 'Url' POST parameter, in order to retrieve TwiML for handling the call. This request is identical to the request Twilio sends when receiving a phone call to one of your Twilio numbers. URLs must contain a valid hostname (underscores are not permitted).

So, your formData here should be:

formData: {
  To: '+919200070974',
  From: '14245060471',
  Url: 'https://example.com/twiml'
}

And the URL at https://example.com/twiml should respond with the TwiML you defined originally.

Upvotes: 1

Jairo Malanay
Jairo Malanay

Reputation: 1347

twilio has an npm library already.

you can follow their Node.js Guide

// Twilio Credentials
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';

// require the Twilio module and create a REST client
const client = require('twilio')(accountSid, authToken);

client.messages
  .create({
    to: '+15558675310',
    from: '+15017122661',
    body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
  })
  .then(message => console.log(message.sid));

Upvotes: 1

Related Questions