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

* [axios](https://www.npmjs.com/package/axios)
* [got](https://www.npmjs.com/package/got)
* [node-fetch](https://www.npmjs.com/package/node-fetch)

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

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](/docs/labs/serverless-toolkit) as explained below:

## Console

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](https://www.twilio.com/console/functions/overview). If you need an account, you can sign up for a free Twilio account [here](https://www.twilio.com/try-twilio)!
2. Functions are contained within **Services**. Create a **[Service](/docs/serverless/functions-assets/functions/create-service)** by clicking the **[Create Service](https://www.twilio.com/console/functions/overview/services)** 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](/docs/serverless/functions-assets/visibility) 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`.

## Serverless Toolkit

The [Serverless Toolkit](/docs/labs/serverless-toolkit) enables you with local development, project deployment, and other functionality via the [Twilio CLI](/docs/twilio-cli/quickstart). To get up and running with these examples using Serverless Toolkit, follow this process:

1. From the CLI, run `twilio serverless:init <your-service-name> --empty` to bootstrap your local environment.
2. Navigate into your new project directory using `cd <your-service-name>`
3. In the `/functions` directory, create a new JavaScript file that is named respective to the purpose of the Function. For example, `sms-reply.protected.js` for a [Protected](/docs/serverless/functions-assets/visibility) Function intended to handle incoming SMS.
4. Populate the file using the code example of your choice and save. **Note** A Function can only export a single handler. You will want to create separate files if you want to run and/or deploy multiple examples at once.

Once your Function(s) code is written and saved, you can test it either by running it locally (and optionally tunneling requests to it via a tool like [ngrok](https://ngrok.com/)), or by deploying the Function and executing against the deployed url(s).

### Run your Function in local development

Run `twilio serverless:start` from your CLI to start the project locally. The Function(s) in your project will be accessible from `http://localhost:3000/sms-reply`

* If you want to test a Function as a [Twilio webhook](/docs/usage/webhooks/getting-started-twilio-webhooks), run: `twilio phone-numbers:update <your Twilio phone number> --sms-url "http://localhost:3000/sms-reply"`\
  This will automatically generate an ngrok tunnel from Twilio to your locally running Function, so you can start sending texts to it. You can apply the same process but with the `voice-url` flag instead if you want to test with [Twilio Voice](/docs/voice).
* If your code does *not* connect to Twilio Voice/Messages as a webhook, you can start your dev server and start an ngrok tunnel in the same command with the `ngrok` flag. For example: `twilio serverless:start --ngrok=""`

### Deploy your Function

To deploy your Function and have access to live url(s), run `twilio serverless:deploy` from your CLI. This will deploy your Function(s) to Twilio under a development environment by default, where they can be accessed from:

`https://<service-name>-<random-characters>-dev.twil.io/<function-path>`

For example: `https://incoming-sms-examples-3421-dev.twil.io/sms-reply`

Your Function is now ready to be invoked by HTTP requests, set as the [webhook](/docs/usage/webhooks/getting-started-twilio-webhooks) of a Twilio phone number, invoked by a Twilio Studio **[Run Function Widget](/docs/studio/widget-library/run-function)**, and more!

## Set a Function as a webhook

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

![Setting a Function as a Messaging webhook using the webhook dropdown option.](https://docs-resources.prod.twilio.com/bf4eae4ac40fe7d47003a93bca295d5c232e0b372358e73ceff931fee3ccdc4f.png)

## Make a single API request

Before you can make an API request, you'll need to install `axios` as a [Dependency](/docs/serverless/functions-assets/functions/dependencies) 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.

```js title="Make a single API request"
const axios = require('axios');

exports.handler = async (context, event, callback) => {
  // Create a new voice response object
  const twiml = new Twilio.twiml.VoiceResponse();

  try {
    // Open APIs From Space: http://open-notify.org
    // Number of people in space
    const response = await axios.get(`http://api.open-notify.org/astros.json`);
    const { number, people } = response.data;

    const names = people.map((astronaut) => astronaut.name).sort();
    // Create a list formatter to join the names with commas and 'and'
    // so that the played speech sounds more natural
    const listFormatter = new Intl.ListFormat('en');

    twiml.say(`There are ${number} people in space.`);
    twiml.pause({ length: 1 });
    twiml.say(`Their names are: ${listFormatter.format(names)}`);
    // Return the final TwiML as the second argument to `callback`
    // This will render the response as XML in reply to the webhook request
    // and result in the message being played back to the user
    return callback(null, twiml);
  } catch (error) {
    // In the event of an error, return a 500 error and the error message
    console.error(error);
    return callback(error);
  }
};
```

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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat) 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](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous) 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](http://callbackhell.com/) or lengthy `then` chains. You can learn more about this [async/await syntax](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await) 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

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).

```js title="Make sequential API requests"
const axios = require('axios');
const qs = require('qs');

exports.handler = async (context, event, callback) => {
  // Create a new voice response object
  const twiml = new Twilio.twiml.VoiceResponse();
  // A pre-initialized Twilio client is available from the `context` object
  const twilioClient = context.getTwilioClient();

  try {
    // Open APIs From Space: http://open-notify.org
    // Number of people in space
    const response = await axios.get(`http://api.open-notify.org/astros.json`);
    const { number, people } = response.data;

    const names = people.map((astronaut) => astronaut.name).sort();

    // Select a random astronaut
    const astronautName = names[Math.floor(Math.random() * names.length)];
    // Search Wikipedia for any article's about the astronaut
    const { data: wikipediaResult } = await axios.get(
      `https://en.wikipedia.org/w/api.php?${qs.stringify({
        origin: '*',
        action: 'opensearch',
        search: astronautName,
      })}`
    );
    // Attempt to select the first relevant article from the nested result
    const article = wikipediaResult[3] ? wikipediaResult[3][0] : undefined;
    // Create a list formatter to join the names with commas and 'and'
    // so that the played speech sounds more natural
    const listFormatter = new Intl.ListFormat('en');

    twiml.say(`There are ${number} people in space.`);
    twiml.pause({ length: 1 });
    twiml.say(`Their names are: ${listFormatter.format(names)}`);
    // If there's a defined article for the astronaut, message the link to the user
    // and tell them they've been sent a message
    if (article) {
      // Use `messages.create` to send a text message to the user that
      // is separate from this call and includes the article
      await twilioClient.messages.create({
        to: event.From,
        from: context.TWILIO_PHONE_NUMBER,
        body: `Learn more about ${astronautName} on Wikipedia at: ${article}`,
      });

      twiml.pause({ length: 1 });
      twiml.say(
        `We've just sent you a message with a Wikipedia article about
         ${astronautName}, enjoy!`
      );
    }

    // Return the final TwiML as the second argument to `callback`
    // This will render the response as XML in reply to the webhook request
    // and result in the message being played back to the user
    return callback(null, twiml);
  } catch (error) {
    // In the event of an error, return a 500 error and the error message
    console.error(error);
    return callback(error);
  }
};
```

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](/docs/serverless/functions-assets/functions/dependencies) so that we can make an API request that includes [search parameters](https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams). Also, for the text messaging to work, you'll need to set your Twilio phone number as an [environment variable](/docs/serverless/functions-assets/functions/variables) 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

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 `await`ing their results in parallel using a built-in method, such as [`Promise.all`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all).

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](/docs/serverless/functions-assets/functions/dependencies) installed for previous examples, you will want to get a free API key from [positionstack](https://positionstack.com/). This will enable you to perform reverse geolocation on the [International Space Station](https://en.wikipedia.org/wiki/International_Space_Station) or ISS. Set the value of the API key to an [environment variable](/docs/serverless/functions-assets/functions/variables) named `POSITIONSTACK_API_KEY`.

```js title="Make parallel API requests"
const axios = require('axios');
const qs = require('qs');

exports.handler = async (context, event, callback) => {
  // Create a new voice response object
  const twiml = new Twilio.twiml.VoiceResponse();

  try {
    // Open APIs From Space: http://open-notify.org
    const openNotifyUri = 'http://api.open-notify.org';
    // Create a promise for each API call which can be made
    // independently of each other

    // Number of people in space
    const getAstronauts = axios.get(`${openNotifyUri}/astros.json`);
    // The current position of the ISS
    const getIss = axios.get(`${openNotifyUri}/iss-now.json`);

    // Wait for both requests to be completed in parallel instead of sequentially
    const [astronauts, iss] = await Promise.all([getAstronauts, getIss]);

    const { number, people } = astronauts.data;
    const { latitude, longitude } = iss.data.iss_position;

    const names = people.map((astronaut) => astronaut.name).sort();

    // We can use reverse geocoding to convert the latitude and longitude
    // of the ISS to a human-readable location. We'll use positionstack.com
    // since they provide a free API.
    // Be sure to set your positionstack API key as an environment variable!
    const { data: issLocation } = await axios.get(
      `http://api.positionstack.com/v1/reverse?${qs.stringify({
        access_key: context.POSITIONSTACK_API_KEY,
        query: `${latitude},${longitude}`,
      })}`
    );

    const { label: location } = issLocation.data[0] || 'an unknown location';

    // Create a list formatter to join the names with commas and 'and'
    // so that the played speech sounds more natural
    const listFormatter = new Intl.ListFormat('en');

    twiml.say(`There are ${number} people in space.`);
    twiml.pause({ length: 1 });
    twiml.say(`Their names are: ${listFormatter.format(names)}`);
    twiml.pause({ length: 1 });
    twiml.say(
      `Also, the International Space Station is currently above ${location}`
    );
    // Return the final TwiML as the second argument to `callback`
    // This will render the response as XML in reply to the webhook request
    // and result in the message being played back to the user
    return callback(null, twiml);
  } catch (error) {
    // In the event of an error, return a 500 error and the error message
    console.error(error);
    return callback(error);
  }
};
```

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

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](https://www.twilio.com/blog/handling-high-volume-inbound-sms-and-webhooks-with-twilio-functions-and-amazon-sqs.html) 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

```js title="Make a write request to an external API"
const axios = require('axios');

exports.handler = async (context, event, callback) => {
  // Create a new message response object
  const twiml = new Twilio.twiml.MessagingResponse();

  // Just for this example, we'll use the first digit of the incoming phone
  // number to identify the call. You'll want to use a more robust mechanism
  // for your own Functions, such as the full phone number.
  const postId = event.From[1];

  // Since we're making multiple requests, we'll create an instance of axios
  // that includes our API's base URL and any custom headers we might want to
  // send with each request. This will simplify the GET and POST request paths.
  // JSONPlaceholder is a fake REST API that you can use for testing and prototyping
  const instance = axios.create({
    baseURL: 'https://jsonplaceholder.typicode.com',
    headers: { 'X-Custom-Header': 'Twilio' },
  });

  try {
    // Get the post based on the derived postId
    // If the postId was 1, this is effectively making a GET request to:
    // https://jsonplaceholder.typicode.com/posts/1
    const { data: post } = await instance.get(`/posts/${postId}`);

    const newCount = (post.messageCount || 0) + 1;

    // Use a POST request to "save" the update to the API
    // In this case, we're merging the new count and message into the
    // existing post object.
    const update = await instance.post('/posts/', {
      ...post,
      messageCount: newCount,
      latestMessage: event.Body,
    });

    console.log(update.data);

    // Add a message to the response to let the user know that everything worked
    twiml.message(
      `Message received! This was message ${newCount} from your phone number. 🎉`
    );
    return callback(null, twiml);
  } catch (error) {
    // As always with async functions, you need to be sure to handle errors
    console.error(error);
    // Add a message to the response to let the user know that something went wrong
    twiml.message(`We received your message, but something went wrong 😭`);
    return callback(error);
  }
};
```

## Make a write request in other formats

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 an [SDK](/docs/libraries), is `Content-Type: application/x-www-form-urlencoded`. As detailed in the `axios` [documentation](https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format) 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.

```js title="Make a write request using x-www-form-urlencoded format"
const axios = require('axios');
const qs = require('qs');

exports.handler = async (context, event, callback) => {
  // Create a new message response object
  const twiml = new Twilio.twiml.MessagingResponse();

  // Just for this example, we'll use the first digit of the incoming phone
  // number to identify the call. You'll want to use a more robust mechanism
  // for your own Functions, such as the full phone number.
  const postId = event.From[1];

  // Since we're making multiple requests, we'll create an instance of axios
  // that includes our API's base URL and any custom headers we might want to
  // send with each request. This will simply be our GET and POST request paths.
  // JSONPlaceholder is a fake REST API that you can use for testing and prototyping
  const instance = axios.create({
    baseURL: 'https://jsonplaceholder.typicode.com',
    headers: { 'X-Custom-Header': 'Twilio' },
  });

  try {
    // Get the post based on the derived postId
    // If the postId was 1, this is effectively making a GET request to:
    // https://jsonplaceholder.typicode.com/posts/1
    const { data: post } = await instance.get(`/posts/${postId}`);

    const newCount = (post.messageCount || 0) + 1;

    // Like before, we're merging the new count and message into the
    // existing post object
    // In order to send this data in the application/x-www-form-urlencoded
    // format, the payload must be encoded via a utility such as qs
    const data = qs.stringify({
      ...post,
      messageCount: newCount,
      latestMessage: event.Body,
    });

    // Use a POST request to "save" the update to the API
    const update = await instance.post('/posts/', data);

    console.log(update.data);

    // Add a message to the response to let the user know that everything worked
    twiml.message(
      `Message received! This was message ${newCount} from your phone number. 🎉`
    );
    return callback(null, twiml);
  } catch (error) {
    // As always with async functions, you need to be sure to handle errors
    console.error(error);
    // Add a message to the response to let the user know that something went wrong
    twiml.message(`We received your message, but something went wrong 😭`);
    return callback(error);
  }
};
```

## Handling unstable APIs

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](https://dzone.com/articles/understanding-retry-pattern-with-exponential-back)). You could implement this yourself, or use a module such as [p-retry](https://www.npmjs.com/package/p-retry) 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]
>
> V5 and newer versions of `p-retry` are exported as [ES Modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules), 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports) *inside* of your handler method, as highlighted in the following examples.

```js title="Configure retries for an API request"
// !mark(12,15,16,17,18,19,20,21,22,23,24,25,26,3,37,38,39,40,41,6,7)
const axios = require('axios');

const getAstronauts = () => axios.get('https://unstable-5604.twil.io/astros');

exports.handler = async (context, event, callback) => {
  // We need to asynchronously import p-retry since it is an ESM module
  const { default: pRetry } = await import('p-retry');
  // Create a new voice response object
  const twiml = new Twilio.twiml.VoiceResponse();

  try {
    let attempts = 1;
    // Open APIs From Space: http://open-notify.org
    // Number of people in space
    const response = await pRetry(getAstronauts, {
      retries: 3,
      onFailedAttempt: ({ attemptNumber, retriesLeft }) => {
        attempts = attemptNumber;
        console.log(
          `Attempt ${attemptNumber} failed. There are ${retriesLeft} retries left.`
        );
        // 1st request => "Attempt 1 failed. There are 3 retries left."
        // 2nd request => "Attempt 2 failed. There are 2 retries left."
        // …
      },
    });
    const { number, people } = response.data;

    const names = people.map((astronaut) => astronaut.name).sort();
    // Create a list formatter to join the names with commas and 'and'
    // so that the played speech sounds more natural
    const listFormatter = new Intl.ListFormat('en');

    twiml.say(`There are ${number} people in space.`);
    twiml.pause({ length: 1 });
    twiml.say(`Their names are: ${listFormatter.format(names)}`);
    // If retries were necessary, add that information to the response
    if (attempts > 1) {
      twiml.pause({ length: 1 });
      twiml.say(`It took ${attempts} attempts to retrieve this information.`);
    }
    // Return the final TwiML as the second argument to `callback`
    // This will render the response as XML in reply to the webhook request
    // and result in the message being played back to the user
    return callback(null, twiml);
  } catch (error) {
    // In the event of an error, return a 500 error and the error message
    console.error(error);
    return callback(error);
  }
};
```

```js title="Configure retries for parallel API requests"
// !mark(11,12,13,14,17,18,25,26,40,41,42,43,44,45,46,47,48,49,8,9)
const axios = require('axios');
const qs = require('qs');

// The root URL for an API which is known to fail on occasion
const unstableSpaceUri = 'https://unstable-5604.twil.io';
// We'll declare these functions outside of the handler since they have no
// dependencies on other values, and this will tidy up our pRetry calls.
const astronautRequest = () => axios.get(`${unstableSpaceUri}/astros`);
const issRequest = () => axios.get(`${unstableSpaceUri}/iss`);
// Use a common object for retry configuration to DRY up our code :)
const retryConfig = (reqName) => ({
  retries: 3,
  onFailedAttempt: () => console.log(`Retrying ${reqName}...`),
});

exports.handler = async (context, event, callback) => {
  // We need to asynchronously import p-retry since it is an ESM module
  const { default: pRetry } = await import('p-retry');
  // Create a new voice response object
  const twiml = new Twilio.twiml.VoiceResponse();

  try {
    // Create a promise with retry for each API call that can be made
    // independently of each other
    const getAstronauts = pRetry(astronautRequest, retryConfig('astros'));
    const getIss = pRetry(issRequest, retryConfig('iss'));
    // pRetry returns a promise, so we can still use Promise.all to await
    // the result of both requests in parallel with retry and backoff enabled!
    const [astronauts, iss] = await Promise.all([getAstronauts, getIss]);

    const { number, people } = astronauts.data;
    const { latitude, longitude } = iss.data.iss_position;

    const names = people.map((astronaut) => astronaut.name).sort();

    // We can use reverse geocoding to convert the latitude and longitude
    // of the ISS to a human-readable location. We'll use positionstack.com
    // since they provide a free API.
    // Be sure to set your positionstack API key as an environment variable!
    const { data: issLocation } = await pRetry(
      () =>
        axios.get(
          `http://api.positionstack.com/v1/reverse?${qs.stringify({
            access_key: context.POSITIONSTACK_API_KEY,
            query: `${latitude},${longitude}`,
          })}`
        ),
      retryConfig('iss location')
    );

    const { label } = issLocation.data[0] || 'an unknown location';

    // Create a list formatter to join the names with commas and 'and'
    // so that the played speech sounds more natural
    const listFormatter = new Intl.ListFormat('en');

    twiml.say(`There are ${number} people in space.`);
    twiml.pause({ length: 1 });
    twiml.say(`Their names are: ${listFormatter.format(names)}`);
    twiml.pause({ length: 1 });
    twiml.say(
      `Also, the International Space Station is currently above ${label}`
    );
    // Return the final TwiML as the second argument to `callback`
    // This will render the response as XML in reply to the webhook request
    // and result in the message being played back to the user
    return callback(null, twiml);
  } catch (error) {
    // In the event of an error, return a 500 error and the error message
    console.error(error);
    return callback(error);
  }
};
```
