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

Make a request to an external API


At some point in your application development process, you may find yourself wanting to include dynamic or external data in your responses to users or as part of your application logic. A common way to incorporate this into your application is by making requests to APIs and processing their responses.

There are as many potential use cases as there are developers, so we can't possibly document every possible situation. Instead, we'll provide you with some examples and useful strategies that we've found over the years for making API calls in your Functions.

There are a wide variety of npm modules available for making HTTP requests to external APIs, including but not limited to:

For the sake of consistency, all examples will use axios, but the same principles will apply to any HTTP request library. These examples are written assuming that a customer is calling your Twilio phone number and expecting a voice response, but these same concepts apply to any application type.


Create and host a Function

create-and-host-a-function page anchor

In order to run any of the following examples, you will first need to create a Function into which you can paste the example code. You can create a Function using the Twilio Console or the Serverless Toolkit as explained below:

ConsoleServerless Toolkit

If you prefer a UI-driven approach, creating and deploying a Function can be done entirely using the Twilio Console and the following steps:

  1. Log in to the Twilio Console and navigate to the Functions tab(link takes you to an external page) . If you need an account, you can sign up for a free Twilio account here(link takes you to an external page) !
  2. Functions are contained within Services . Create a Service by clicking the Create Service(link takes you to an external page) button and providing a name such as test-function .
  3. Once you've been redirected to the new Service, click the Add + button and select Add Function from the dropdown.
  4. This will create a new Protected Function for you with the option to rename it. The name of the file will be path it is accessed from.
  5. Copy any one of the example code snippets from this page that you want to experiment with, and paste the code into your newly created Function. You can quickly switch examples by using the dropdown menu of the code rail.
  6. Click Save to save your Function's contents.
  7. Click Deploy All to build and deploy the Function. After a short delay, your Function will be accessible from: https://<service-name>-<random-characters>-<optional-domain-suffix>.twil.io/<function-path>
    For example: test-function-3548.twil.io/hello-world .

Your Function is now ready to be invoked by HTTP requests, set as the webhook of a Twilio phone number, invoked by a Twilio Studio Run Function Widget, and more!


Set a Function as a webhook

set-a-function-as-a-webhook page anchor

In order for your Function to react to incoming SMS and/or voice calls, it must be set as a webhook for your Twilio number. There are a variety of methods to set a Function as a webhook, as detailed below:

Twilio ConsoleTwilio CLITwilio SDKs

You can use the Twilio Console(link takes you to an external page) UI as a straightforward way of connecting your Function as a webhook:

  1. Log in to the Twilio Console's Phone Numbers page(link takes you to an external page) .
  2. Click on the phone number you'd like to have connected to your Function.
  3. If you want the Function to respond to incoming SMS, find the A Message Comes In option under Messaging . If you want the Function to respond to Voice, find the A Call Comes In option under Voice & Fax .
  4. Select Function from the A Message Comes In or A Call Comes In dropdown.
  5. Select the Service that you are using, then the Environment (this will default to ui unless you have created custom domains ), and finally Function Path of your Function from the respective dropdown menus.
    Connect a Function as a Messaging webhook using the Function dropdowns.
  • Alternatively, you could select Webhook instead of Function, and directly paste in the full URL of the Function.
    Setting a Function as a Messaging webhook using the webhook dropdown option.
  1. Click the Save button.

Make a single API request

make-a-single-api-request page anchor

Before you can make an API request, you'll need to install axios as a Dependency for your Function. Once axios is installed, copy the following code snippet and paste it as the body of a new, public Function, such as /astro-info. Be sure to use the instructions above to connect this Function as the webhook for incoming calls to your Twilio phone number.

Make a single API request

make-a-single-api-request-1 page anchor

_30
const axios = require('axios');
_30
_30
exports.handler = async (context, event, callback) => {
_30
// Create a new voice response object
_30
const twiml = new Twilio.twiml.VoiceResponse();
_30
_30
try {
_30
// Open APIs From Space: http://open-notify.org
_30
// Number of people in space
_30
const response = await axios.get(`http://api.open-notify.org/astros.json`);
_30
const { number, people } = response.data;
_30
_30
const names = people.map((astronaut) => astronaut.name).sort();
_30
// Create a list formatter to join the names with commas and 'and'
_30
// so that the played speech sounds more natural
_30
const listFormatter = new Intl.ListFormat('en');
_30
_30
twiml.say(`There are ${number} people in space.`);
_30
twiml.pause({ length: 1 });
_30
twiml.say(`Their names are: ${listFormatter.format(names)}`);
_30
// Return the final TwiML as the second argument to `callback`
_30
// This will render the response as XML in reply to the webhook request
_30
// and result in the message being played back to the user
_30
return callback(null, twiml);
_30
} catch (error) {
_30
// In the event of an error, return a 500 error and the error message
_30
console.error(error);
_30
return callback(error);
_30
}
_30
};

This code is:

  • Initializing a TwiML Voice Response, for speaking back to the incoming caller
  • Using axios to perform an API request to the astros endpoint, which will return the number of people currently in space, and a list of their names
  • Performing some operations on the data returned by the API, such as isolating the names into a sorted list, and preparing an Intl.ListFormat(link takes you to an external page) object for formatting the names
  • Generating the message to be returned to the caller, and returning it
  • All of this is wrapped in a try/catch block to handle any exceptions, such as a connection error that could be thrown by the API

There are some key points to keep in mind.

Making an HTTP request to an API is what we call an asynchronous operation, meaning the response from the API will come back to us at a later point in time, and we're free to use computing resources on other tasks in the meantime. Calling axios in this code sample creates a Promise, which will ultimately resolve as the data we want, or reject and throw an exception.

The MDN has an excellent series that introduces asynchronous JavaScript(link takes you to an external page) and related concepts.

Note that we've declared this Function as async. This means that we can leverage the await keyword and structure our code in a very readable, sequential manner. The request is still fundamentally a Promise, but we can treat it almost like synchronous code without the need for callback hell(link takes you to an external page) or lengthy then chains. You can learn more about this async/await syntax(link takes you to an external page) at the MDN.

The other key point is that our code only ever calls callback once our code has successfully completed or if an error has occurred. If the await keyword was removed, or we otherwise didn't wait for the API call to complete before invoking the callback method, this would result in incorrect behavior. If we never invoke callback, the Function will run until the 10-second execution limit is reached, resulting in an error and the customer never receiving a response.


Make sequential API requests

make-sequential-api-requests page anchor

Another common situation you may encounter is the need to make one API request, and then a subsequent request which is dependent on having data from the first request. By properly handling Promises in order, and ensuring that callback is not invoked before our requests have finished, you can make any number of sequential requests in your Function as necessary for your use case (while also keeping in mind that the Function has 10 seconds to complete all requests).

Make sequential API requests

make-sequential-api-requests-1 page anchor

_64
const axios = require('axios');
_64
const qs = require('qs');
_64
_64
exports.handler = async (context, event, callback) => {
_64
// Create a new voice response object
_64
const twiml = new Twilio.twiml.VoiceResponse();
_64
// A pre-initialized Twilio Client is available from the `context` object
_64
const twilioClient = context.getTwilioClient();
_64
_64
try {
_64
// Open APIs From Space: http://open-notify.org
_64
// Number of people in space
_64
const response = await axios.get(`http://api.open-notify.org/astros.json`);
_64
const { number, people } = response.data;
_64
_64
const names = people.map((astronaut) => astronaut.name).sort();
_64
_64
// Select a random astronaut
_64
const astronautName = names[Math.floor(Math.random() * names.length)];
_64
// Search Wikipedia for any article's about the astronaut
_64
const { data: wikipediaResult } = await axios.get(
_64
`https://en.wikipedia.org/w/api.php?${qs.stringify({
_64
origin: '*',
_64
action: 'opensearch',
_64
search: astronautName,
_64
})}`
_64
);
_64
// Attempt to select the first relevant article from the nested result
_64
const article = wikipediaResult[3] ? wikipediaResult[3][0] : undefined;
_64
// Create a list formatter to join the names with commas and 'and'
_64
// so that the played speech sounds more natural
_64
const listFormatter = new Intl.ListFormat('en');
_64
_64
twiml.say(`There are ${number} people in space.`);
_64
twiml.pause({ length: 1 });
_64
twiml.say(`Their names are: ${listFormatter.format(names)}`);
_64
// If there's a defined article for the astronaut, message the link to the user
_64
// and tell them they've been sent a message
_64
if (article) {
_64
// Use `messages.create` to send a text message to the user that
_64
// is separate from this call and includes the article
_64
await twilioClient.messages.create({
_64
to: event.From,
_64
from: context.TWILIO_PHONE_NUMBER,
_64
body: `Learn more about ${astronautName} on Wikipedia at: ${article}`,
_64
});
_64
_64
twiml.pause({ length: 1 });
_64
twiml.say(
_64
`We've just sent you a message with a Wikipedia article about
_64
${astronautName}, enjoy!`
_64
);
_64
}
_64
_64
// Return the final TwiML as the second argument to `callback`
_64
// This will render the response as XML in reply to the webhook request
_64
// and result in the message being played back to the user
_64
return callback(null, twiml);
_64
} catch (error) {
_64
// In the event of an error, return a 500 error and the error message
_64
console.error(error);
_64
return callback(error);
_64
}
_64
};

Similar to the previous example, copy the following code snippet and paste it as the body of a new, public Function, such as /detailed-astro-info. In addition, you will need to install the qs module as a Dependency so that we can make an API request that includes search parameters(link takes you to an external page). Also, for the text messaging to work, you'll need to set your Twilio phone number as an environment variable titled TWILIO_PHONE_NUMBER.

This code is:

  • Initializing a TwiML Voice Response, for speaking back to the incoming caller
  • Using axios to perform an API request to the astros endpoint, which will return the number of people currently in space and a list of their names
  • Performing some operations on the data, and randomly selecting one of the astronaut names
  • Performing a second API request. This time, querying Wikipedia for any articles about the astronaut, with their name as the search term.
  • Generating the message to be returned to the caller, sending the caller a text message containing a Wikipedia article (if one is found), and returning the voice message to the caller
  • All of this is wrapped in a try/catch block to handle any exceptions, such as a connection error that could be thrown by either API

Make parallel API requests

make-parallel-api-requests page anchor

Frequently in applications, we also run into situations where we could make a series of requests one after another, but we can deliver a better and faster experience to users if we perform some requests at the same time.

We can accomplish this in JavaScript by initiating multiple requests, and awaiting their results in parallel using a built-in method, such as Promise.all(link takes you to an external page).

To get started, copy the following code snippet and paste it as the body of a new, public Function, such as /space-info.

In addition to the axios and qs dependencies installed for previous examples, you will want to get a free API key from positionstack(link takes you to an external page). This will enable you to perform reverse geolocation on the International Space Station(link takes you to an external page) or ISS. Set the value of the API key to an environment variable named POSITIONSTACK_API_KEY.


_60
const axios = require('axios');
_60
const qs = require('qs');
_60
_60
exports.handler = async (context, event, callback) => {
_60
// Create a new voice response object
_60
const twiml = new Twilio.twiml.VoiceResponse();
_60
_60
try {
_60
// Open APIs From Space: http://open-notify.org
_60
const openNotifyUri = 'http://api.open-notify.org';
_60
// Create a promise for each API call which can be made
_60
// independently of each other
_60
_60
// Number of people in space
_60
const getAstronauts = axios.get(`${openNotifyUri}/astros.json`);
_60
// The current position of the ISS
_60
const getIss = axios.get(`${openNotifyUri}/iss-now.json`);
_60
_60
// Wait for both requests to be completed in parallel instead of sequentially
_60
const [astronauts, iss] = await Promise.all([getAstronauts, getIss]);
_60
_60
const { number, people } = astronauts.data;
_60
const { latitude, longitude } = iss.data.iss_position;
_60
_60
const names = people.map((astronaut) => astronaut.name).sort();
_60
_60
// We can use reverse geocoding to convert the latitude and longitude
_60
// of the ISS to a human-readable location. We'll use positionstack.com
_60
// since they provide a free API.
_60
// Be sure to set your positionstack API key as an environment variable!
_60
const { data: issLocation } = await axios.get(
_60
`http://api.positionstack.com/v1/reverse?${qs.stringify({
_60
access_key: context.POSITIONSTACK_API_KEY,
_60
query: `${latitude},${longitude}`,
_60
})}`
_60
);
_60
_60
const { label: location } = issLocation.data[0] || 'an unknown location';
_60
_60
// Create a list formatter to join the names with commas and 'and'
_60
// so that the played speech sounds more natural
_60
const listFormatter = new Intl.ListFormat('en');
_60
_60
twiml.say(`There are ${number} people in space.`);
_60
twiml.pause({ length: 1 });
_60
twiml.say(`Their names are: ${listFormatter.format(names)}`);
_60
twiml.pause({ length: 1 });
_60
twiml.say(
_60
`Also, the International Space Station is currently above ${location}`
_60
);
_60
// Return the final TwiML as the second argument to `callback`
_60
// This will render the response as XML in reply to the webhook request
_60
// and result in the message being played back to the user
_60
return callback(null, twiml);
_60
} catch (error) {
_60
// In the event of an error, return a 500 error and the error message
_60
console.error(error);
_60
return callback(error);
_60
}
_60
};

This code is:

  • Initializing a TwiML Voice Response, for speaking back to the incoming caller
  • Using axios to create two requests to the Open Notify API, one for astronaut information and the other for information about the ISS's location, and storing references to the resulting Promises.
  • await ing the result of both requests simultaneously using Promise.all
  • Performing a second API request, this time to convert the latitude and longitude of the ISS into a human-readable location on Earth, such as "North Pacific Ocean"
  • Generating the message to be returned to the caller based on all of the data gathered so far, and returning the voice message to the caller
  • All of this is wrapped in a try/catch block to handle any exceptions, such as a connection error that could be thrown by any of the APIs

Make a write request to an external API

make-a-write-request-to-an-external-api page anchor

Just as you may need to request data in your Serverless applications, there are numerous reasons why you may want to send data to external APIs. Perhaps your Function responds to incoming text messages from customers and attempts to update an internal record about that customer by sending data to an API that manages customer records. Maybe your Function serves as a means to push messages onto a queue, like SQS(link takes you to an external page) so that some other microservice can handle clearing out that queue.

Regardless of the use case, you are free to make write requests to external APIs from your Functions (assuming you have permission to do so from the API). There are no restrictions imposed on this by Runtime itself.

Depending on the scenario, making a write request will mostly consist of using the same principles from the above examples, but using HTTP verbs such as POST and PUT instead of GET.

The below example demonstrates a simple use case where a Function:

  • Receives an incoming text message
  • Derives an identifier from the incoming phone number
  • Retrieves a record from an API, based on the derived ID
  • Writes an update to that API, and responds to the sender once all operations are complete

Make a write request to an external API

make-a-write-request-to-an-external-api-1 page anchor

_52
const axios = require('axios');
_52
_52
exports.handler = async (context, event, callback) => {
_52
// Create a new message response object
_52
const twiml = new Twilio.twiml.MessagingResponse();
_52
_52
// Just for this example, we'll use the first digit of the incoming phone
_52
// number to identify the call. You'll want to use a more robust mechanism
_52
// for your own Functions, such as the full phone number.
_52
const postId = event.From[1];
_52
_52
// Since we're making multiple requests, we'll create an instance of axios
_52
// that includes our API's base URL and any custom headers we might want to
_52
// send with each request. This will simplify the GET and POST request paths.
_52
// JSONPlaceholder is a fake REST API that you can use for testing and prototyping
_52
const instance = axios.create({
_52
baseURL: 'https://jsonplaceholder.typicode.com',
_52
headers: { 'X-Custom-Header': 'Twilio' },
_52
});
_52
_52
try {
_52
// Get the post based on the derived postId
_52
// If the postId was 1, this is effectively making a GET request to:
_52
// https://jsonplaceholder.typicode.com/posts/1
_52
const { data: post } = await instance.get(`/posts/${postId}`);
_52
_52
const newCount = (post.messageCount || 0) + 1;
_52
_52
// Use a POST request to "save" the update to the API
_52
// In this case, we're merging the new count and message into the
_52
// existing post object.
_52
const update = await instance.post('/posts/', {
_52
...post,
_52
messageCount: newCount,
_52
latestMessage: event.Body,
_52
});
_52
_52
console.log(update.data);
_52
_52
// Add a message to the response to let the user know that everything worked
_52
twiml.message(
_52
`Message received! This was message ${newCount} from your phone number. 🎉`
_52
);
_52
return callback(null, twiml);
_52
} catch (error) {
_52
// As always with async functions, you need to be sure to handle errors
_52
console.error(error);
_52
// Add a message to the response to let the user know that something went wrong
_52
twiml.message(`We received your message, but something went wrong 😭`);
_52
return callback(error);
_52
}
_52
};


Make a write request in other formats

make-a-write-request-in-other-formats page anchor

Some APIs may not accept write requests that are formatted using JSON (Content-Type: application/json). The approach to handling this situation varies depending on the expected Content-Type and which HTTP library you are using.

One example of a common alternative, which you'll encounter when using some of Twilio's APIs without the aid of a helper library, is Content-Type: application/x-www-form-urlencoded. As detailed in the axios documentation(link takes you to an external page) and shown in the example below, this requires some slight modifications to the data that you send, the Headers attached to the request, or a combination of both.

Make a write request using x-www-form-urlencoded format

make-a-write-request-using-x-www-form-urlencoded-format page anchor

_57
const axios = require('axios');
_57
const qs = require('qs');
_57
_57
exports.handler = async (context, event, callback) => {
_57
// Create a new message response object
_57
const twiml = new Twilio.twiml.MessagingResponse();
_57
_57
// Just for this example, we'll use the first digit of the incoming phone
_57
// number to identify the call. You'll want to use a more robust mechanism
_57
// for your own Functions, such as the full phone number.
_57
const postId = event.From[1];
_57
_57
// Since we're making multiple requests, we'll create an instance of axios
_57
// that includes our API's base URL and any custom headers we might want to
_57
// send with each request. This will simply be our GET and POST request paths.
_57
// JSONPlaceholder is a fake REST API that you can use for testing and prototyping
_57
const instance = axios.create({
_57
baseURL: 'https://jsonplaceholder.typicode.com',
_57
headers: { 'X-Custom-Header': 'Twilio' },
_57
});
_57
_57
try {
_57
// Get the post based on the derived postId
_57
// If the postId was 1, this is effectively making a GET request to:
_57
// https://jsonplaceholder.typicode.com/posts/1
_57
const { data: post } = await instance.get(`/posts/${postId}`);
_57
_57
const newCount = (post.messageCount || 0) + 1;
_57
_57
// Like before, we're merging the new count and message into the
_57
// existing post object
_57
// In order to send this data in the application/x-www-form-urlencoded
_57
// format, the payload must be encoded via a utility such as qs
_57
const data = qs.stringify({
_57
...post,
_57
messageCount: newCount,
_57
latestMessage: event.Body,
_57
});
_57
_57
// Use a POST request to "save" the update to the API
_57
const update = await instance.post('/posts/', data);
_57
_57
console.log(update.data);
_57
_57
// Add a message to the response to let the user know that everything worked
_57
twiml.message(
_57
`Message received! This was message ${newCount} from your phone number. 🎉`
_57
);
_57
return callback(null, twiml);
_57
} catch (error) {
_57
// As always with async functions, you need to be sure to handle errors
_57
console.error(error);
_57
// Add a message to the response to let the user know that something went wrong
_57
twiml.message(`We received your message, but something went wrong 😭`);
_57
return callback(error);
_57
}
_57
};


API requests aren't always successful. Sometimes the API's server may be under too much load and unable to handle your request, or something simply happened to go wrong with the connection between your server and the API.

A standard approach to this situation is to retry the same request but after a delay. If that fails, subsequent retries are performed but with increasing amounts of delay (also known as exponential backoff(link takes you to an external page)). You could implement this yourself, or use a module such as p-retry(link takes you to an external page) to handle this logic for you. This behavior is also built into got by default.

To see this more explicitly configured, the following code examples implement some previous examples, but while utilizing an unstable API that only sometimes successfully returns the desired data.

(warning)

Warning

V5 and newer versions of p-retry are exported as ES Modules(link takes you to an external page), and Functions currently do not support the necessary import syntax. To utilize p-retry (or any other ES Module package) in the meantime, you will need to import it using dynamic import syntax(link takes you to an external page) inside of your handler method, as highlighted in the following examples.

Configure retries for an API request

configure-retries-for-an-api-request page anchor

_51
const axios = require('axios');
_51
_51
const getAstronauts = () => axios.get('https://unstable-5604.twil.io/astros');
_51
_51
exports.handler = async (context, event, callback) => {
_51
// We need to asynchronously import p-retry since it is an ESM module
_51
const { default: pRetry } = await import('p-retry');
_51
// Create a new voice response object
_51
const twiml = new Twilio.twiml.VoiceResponse();
_51
_51
try {
_51
let attempts = 1;
_51
// Open APIs From Space: http://open-notify.org
_51
// Number of people in space
_51
const response = await pRetry(getAstronauts, {
_51
retries: 3,
_51
onFailedAttempt: ({ attemptNumber, retriesLeft }) => {
_51
attempts = attemptNumber;
_51
console.log(
_51
`Attempt ${attemptNumber} failed. There are ${retriesLeft} retries left.`
_51
);
_51
// 1st request => "Attempt 1 failed. There are 3 retries left."
_51
// 2nd request => "Attempt 2 failed. There are 2 retries left."
_51
// …
_51
},
_51
});
_51
const { number, people } = response.data;
_51
_51
const names = people.map((astronaut) => astronaut.name).sort();
_51
// Create a list formatter to join the names with commas and 'and'
_51
// so that the played speech sounds more natural
_51
const listFormatter = new Intl.ListFormat('en');
_51
_51
twiml.say(`There are ${number} people in space.`);
_51
twiml.pause({ length: 1 });
_51
twiml.say(`Their names are: ${listFormatter.format(names)}`);
_51
// If retries were necessary, add that information to the response
_51
if (attempts > 1) {
_51
twiml.pause({ length: 1 });
_51
twiml.say(`It took ${attempts} attempts to retrieve this information.`);
_51
}
_51
// Return the final TwiML as the second argument to `callback`
_51
// This will render the response as XML in reply to the webhook request
_51
// and result in the message being played back to the user
_51
return callback(null, twiml);
_51
} catch (error) {
_51
// In the event of an error, return a 500 error and the error message
_51
console.error(error);
_51
return callback(error);
_51
}
_51
};

Configure retries for parallel API requests

configure-retries-for-parallel-api-requests page anchor

_73
const axios = require('axios');
_73
const qs = require('qs');
_73
_73
// The root URL for an API which is known to fail on occasion
_73
const unstableSpaceUri = 'https://unstable-5604.twil.io';
_73
// We'll declare these functions outside of the handler since they have no
_73
// dependencies on other values, and this will tidy up our pRetry calls.
_73
const astronautRequest = () => axios.get(`${unstableSpaceUri}/astros`);
_73
const issRequest = () => axios.get(`${unstableSpaceUri}/iss`);
_73
// Use a common object for retry configuration to DRY up our code :)
_73
const retryConfig = (reqName) => ({
_73
retries: 3,
_73
onFailedAttempt: () => console.log(`Retrying ${reqName}...`),
_73
});
_73
_73
exports.handler = async (context, event, callback) => {
_73
// We need to asynchronously import p-retry since it is an ESM module
_73
const { default: pRetry } = await import('p-retry');
_73
// Create a new voice response object
_73
const twiml = new Twilio.twiml.VoiceResponse();
_73
_73
try {
_73
// Create a promise with retry for each API call that can be made
_73
// independently of each other
_73
const getAstronauts = pRetry(astronautRequest, retryConfig('astros'));
_73
const getIss = pRetry(issRequest, retryConfig('iss'));
_73
// pRetry returns a promise, so we can still use Promise.all to await
_73
// the result of both requests in parallel with retry and backoff enabled!
_73
const [astronauts, iss] = await Promise.all([getAstronauts, getIss]);
_73
_73
const { number, people } = astronauts.data;
_73
const { latitude, longitude } = iss.data.iss_position;
_73
_73
const names = people.map((astronaut) => astronaut.name).sort();
_73
_73
// We can use reverse geocoding to convert the latitude and longitude
_73
// of the ISS to a human-readable location. We'll use positionstack.com
_73
// since they provide a free API.
_73
// Be sure to set your positionstack API key as an environment variable!
_73
const { data: issLocation } = await pRetry(
_73
() =>
_73
axios.get(
_73
`http://api.positionstack.com/v1/reverse?${qs.stringify({
_73
access_key: context.POSITIONSTACK_API_KEY,
_73
query: `${latitude},${longitude}`,
_73
})}`
_73
),
_73
retryConfig('iss location')
_73
);
_73
_73
const { label } = issLocation.data[0] || 'an unknown location';
_73
_73
// Create a list formatter to join the names with commas and 'and'
_73
// so that the played speech sounds more natural
_73
const listFormatter = new Intl.ListFormat('en');
_73
_73
twiml.say(`There are ${number} people in space.`);
_73
twiml.pause({ length: 1 });
_73
twiml.say(`Their names are: ${listFormatter.format(names)}`);
_73
twiml.pause({ length: 1 });
_73
twiml.say(
_73
`Also, the International Space Station is currently above ${label}`
_73
);
_73
// Return the final TwiML as the second argument to `callback`
_73
// This will render the response as XML in reply to the webhook request
_73
// and result in the message being played back to the user
_73
return callback(null, twiml);
_73
} catch (error) {
_73
// In the event of an error, return a 500 error and the error message
_73
console.error(error);
_73
return callback(error);
_73
}
_73
};


Rate this page: