twiliotwilio-api

Call Twilio studio REST API from Serverless API


I have a Twilio studio flow that triggers a serverless function, and this function should call the Twilio REST API to start the same Twilio studio flow but with a different "To" phone number. I am using a vanilla JS "fetch" function, but the function call doesn't seem to do anything. I have run this block of code outside of the Twilio function and it calls the API just fine. What am I missing?

// This is your new function. To start, set the name and path on the left.

exports.handler = function(context, event, callback) {
  const myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
    myHeaders.append("Authorization", "ENCODED_PASSWORD");

  const urlencoded = new URLSearchParams();
  urlencoded.append("To", "OUTBOUND_PHONE_NUMBER");
  urlencoded.append("From", "TWILIO_PHONE_NUMBER");

  const requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: urlencoded,
  redirect: "follow"
  };

  const post = fetch("https://studio.twilio.com/v2/Flows/TWILIO_STUDIO_ID/Executions", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.error(error));

  // This callback is what is returned in response to this function being invoked.
  // It's really important! E.g. you might respond with TWiML here for a voice or SMS response.
  // Or you might return JSON data to a studio flow. Don't forget it!
  console.log('post created');

  console.log(post);

  return callback(null);
};

Solution

  • The issue you are facing appears to be related to the asynchronous behavior of the fetch function and the need to properly wait for it to complete before running subsequent code. In JavaScript, fetch is an asynchronous function that returns a promise. If you don't wait for it to resolve, the rest of the function might execute before the API call has a chance to complete. This is why your API call seems to "do nothing." Here is how you can modify your function to properly await the fetch request:

    exports.handler = async function(context, event, callback) {
        const myHeaders = new Headers();
        myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
        myHeaders.append("Authorization", "ENCODED_PASSWORD");
    
        const urlencoded = new URLSearchParams();
        urlencoded.append("To", "OUTBOUND_PHONE_NUMBER");
        urlencoded.append("From", "TWILIO_PHONE_NUMBER");
    
        const requestOptions = {
            method: "POST",
            headers: myHeaders,
            body: urlencoded,
            redirect: "follow"
        };
    
        try {
            const response = await fetch("https://studio.twilio.com/v2/Flows/TWILIO_STUDIO_ID/Executions", requestOptions);
            const result = await response.text();
            console.log(result);
        } catch (error) {
            console.error(error);
        }
    
        // It's really important to call the callback to respond to the function invocation.
        // You might respond with TWiML here for a voice or SMS response,
        // or return JSON data to a studio flow. Don't forget it!
        console.log('Post created');
        return callback(null);
    };
    

    By using the async keyword and await for the fetch call, the function will wait for the fetch to complete before moving on to the next line of code.