# Make a Call

> \[!WARNING]
>
> To avoid potential issues, we highly suggest that you [update your twilio dependency to the latest version](/docs/serverless/functions-assets/functions/dependencies#staying-up-to-date) before running any of these code samples.

All Functions execute with a pre-initialized instance of the Twilio Node.js SDK available for use. This means you can access and utilize any Twilio SDK method in your Function. For example, you can use a Function to make outbound phone calls via [Programmable Voice](/docs/voice) as we'll show in the following example snippets.

These examples are not exhaustive, and we encourage you to peruse the [Programmable Voice](/docs/voice) documentation for more inspiration on what you can build.

## Prerequisites

Before you start, be sure to complete the following prerequisites. You can skip to "[Create and host a Function](/docs/serverless/functions-assets/quickstart/make-a-call#create-and-host-a-function)" if you've already completed these steps and need to know more about Function deployment and invocation, or you can skip all the way to "[Make an outbound call](/docs/serverless/functions-assets/quickstart/make-a-call#make-an-outbound-call)" if you're all ready to go and want to get straight to the code.

* **A [Twilio account](https://www.twilio.com/try-twilio).**
* **A voice-enabled [Twilio Phone number](https://www.twilio.com/console/phone-numbers/search).**

## Create and host a Function

Before you run any of the examples on this page, create a Function and paste the example code into it. You can create a Function in the Twilio Console or by using the [Serverless Toolkit](/docs/labs/serverless-toolkit).

## Console

If you prefer a UI-driven approach, complete these steps in the Twilio Console:

1. Log in to the [Twilio Console](https://1console.twilio.com) and navigate to **Develop > Functions & Assets**. If you're using the *legacy* Console, open the [**Functions** tab](https://www.twilio.com/console/functions/overview).
2. Functions are contained within **Services**. Click **[Create Service](https://www.twilio.com/console/functions/overview/services)** to create a new **[Service](/docs/serverless/functions-assets/functions/create-service)**.
3. Click **Add +** and select **Add Function** from the dropdown.
4. The Console creates a new [protected](/docs/serverless/functions-assets/visibility) Function that you can rename. The filename becomes the URL path of the Function.
5. Copy one of the example code snippets from this page and paste the code into your newly created Function. You can switch examples by using the dropdown menu in the code rail.
6. Click **Save**.
7. Click **Deploy All** to build and deploy the Function. After deployment, you can access your Function at `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) lets you develop locally, deploy projects, and perform other tasks through the [Twilio CLI](/docs/twilio-cli/quickstart).

1. From the CLI, run `twilio serverless:init <YOUR-SERVICE-NAME> --empty` to bootstrap your local environment.
2. Go to your new project directory using `cd <YOUR-SERVICE-NAME>`.
3. In the `/functions` directory, create a JavaScript file whose name reflects 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. Add the code example of your choice to the file and save it. Note that a Function can only export a single handler. You need to create separate files to run or deploy multiple examples at once.

After you save the Function code, you can test it locally (and optionally tunnel requests to it using a tool like [ngrok](https://ngrok.com/)), or deploy it.

### Run your Function in local development

Run `twilio serverless:start` from your CLI to start the project locally. The Function(s) in your project are 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 automatically generates 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 to test with [Twilio Voice](/docs/voice).
* If your code does *not* connect to Twilio Voice or Messages as a webhook, 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 deploys 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`

You can now invoke your Function with HTTP requests, configure it as the [webhook](/docs/usage/webhooks/getting-started-twilio-webhooks) for a Twilio phone number, call it from a Twilio Studio [**Run Function** Widget](/docs/studio/widget-library/run-function), and more.

## How to invoke your Function

Functions that you create in the UI are [protected](/docs/serverless/functions-assets/visibility) by default. Set Functions that you deploy with the Serverless Toolkit to `protected` as well by adding "protected" before the file extension, for example, "send-sms.protected.js". This configuration helps secure your Function and prevents unauthorized access. However, it also adds an extra step when you want to invoke and test the Function manually, as shown in the examples on this page.

To call a protected Function, provide a valid `X-Twilio-Signature` header in the request. See the documentation for details about the [request-validation process](/docs/usage/security#validating-requests).

### Generate a valid X-Twilio-Signature header

Though you can generate the header manually with [HMAC-SHA1](/docs/usage/security#a-note-on-hmac-sha1), use the convenience utilities exported by [Twilio's SDKs](/docs/libraries) instead. Download the SDK for your preferred language from the [libraries page](/docs/libraries).

After you install the SDK, complete these steps:

1. Set your Auth Token as an [environment variable](/docs/usage/secure-credentials).
2. If you use the Node.js example, update the request URL to reference your Service and any query parameters you plan to pass. For other languages, see the examples [here](/docs/usage/security#test-the-validity-of-your-webhook-signature).
3. Run the script and copy the generated `X-Twilio-Signature` value for use in the next step.

The following sections show how to generate a signature for a `POST` request with a JSON body and for a `GET` request that passes data as query parameters:

## With a JSON body

```javascript
const { getExpectedTwilioSignature } = require('twilio/lib/webhooks/webhooks');

// Retrieve your auth token from the environment instead of hardcoding
const authToken = process.env.TWILIO_AUTH_TOKEN;

// Use the Twilio helper to generate your valid signature!
// The 1st argument is your Twilio auth token.
// The 2nd is the full URL of your Function.
// The 3rd is any application/x-www-form-urlencoded data being sent, which is none!
const xTwilioSignature = getExpectedTwilioSignature(
  authToken,
  'https://example-4321.twil.io/sms/send',
  {} // <- Leave this empty if sending request data via JSON
);

// Print the signature to the console for use with your
// preferred HTTP client
console.log('xTwilioSignature: ', xTwilioSignature);

// For example, the output will look like this:
// xTwilioSignature: coGTEaFEMv8ejgNGtgtUsbL8r7c=
```

### Create a valid request

After you generate a valid `X-Twilio-Signature` value, include it as a header in the request to your Function. You can use tools such as [curl](https://curl.se/) or [Postman](https://www.postman.com/). Make sure to do the following:

* Set the full URL of the Function, including the root of your Service and the full path to the deployed Function.
* Set the `X-Twilio-Signature` header and content type header (`application/json`) for your request.
* Define the JSON body that you're sending to the Function

Using curl, the request looks like this:

```bash
curl -X POST 'http://test-4321.twil.io/sms/send' \
  -H 'X-Twilio-Signature: coGTEaFEMv8ejgNGtgtUsbL8r7c=' \
  -H 'Content-Type: application/json' \
  --data-raw '{
    "Body": "Hello, there!"
  }'
```

## With Query Parameters

```javascript
const { getExpectedTwilioSignature } = require('twilio/lib/webhooks/webhooks');

// Retrieve your auth token from the environment instead of hardcoding
const authToken = process.env.TWILIO_AUTH_TOKEN;

// Use the Twilio helper to generate your valid signature!
// The 1st argument is your Twilio auth token.
// The 2nd is the full URL of your Function including query params.
// The 3rd is any application/x-www-form-urlencoded data being sent, which is none!
const xTwilioSignature = getExpectedTwilioSignature(
  authToken,
  'https://example-4321.twil.io/sms/send?Body=hello',
  {} // <- Leave this empty
);

// Print the signature to the console for use with your
// preferred HTTP client
console.log('xTwilioSignature: ', xTwilioSignature);

// For example, the output will look like this:
// xTwilioSignature: a610Oi5WiDIHNrUsQYUvNCxKv7A=
```

### Create a valid request

Once you've generated a valid `X-Twilio-Signature` value, use this as a header in a request to your Function. You can do so using a variety of tools, such as [curl](https://curl.se/), [Postman](https://www.postman.com/), and more. Be sure to:

* Set the URL of the Function, including the root of your Service, the full path to the deployed Function, and your query parameters.
* Set the `X-Twilio-Signature` header for your request.

Using curl, the request looks like this:

```bash
curl -X GET 'http://test-4321.twil.io/sms/send?Body=hello' \
  -H 'X-Twilio-Signature: a610Oi5WiDIHNrUsQYUvNCxKv7A='
```

## Make an outbound call

> \[!WARNING]
>
> For any Function using the built-in Twilio client, the "Add my Twilio Credentials (ACCOUNT\_SID) and (AUTH\_TOKEN) to ENV" option on the **Settings > Environment Variables** tab *must* be enabled.

You can use a Function to make a call from your Twilio phone number via [Programmable Voice](/docs/voice). The `to` and `from` parameters of your call must be specified to successfully send, and valid [TwiML](/docs/glossary/what-is-twilio-markup-language-twiml) must be provided either via the `url` or `twiml` parameters.

You'll tell Twilio which phone number to use to make this call by either providing a `From` value in your request, or by omitting it and replacing the placeholder default value in the example code with your own Twilio phone number.

Next, specify yourself as the call recipient by either providing a `To` value in your request, or by omitting it and replacing the default value in the example code with your personal number. The resulting `from` and `to` values both must use [E.164 formatting](/docs/glossary/what-e164) ("`+`" and a country code, e.g., `+16175551212`).

Finally, the `url` or `twiml` value determines the contents of the call that is being sent. As with the other values, either pass in the respective value in your request to this Function or override the default in the example to your own custom value.

Once you've made any modifications to the sample and have deployed your Function for testing, go ahead and make some test HTTP requests against it to get a call to your phone! Example code for [invoking your Function](/docs/serverless/functions-assets/quickstart/make-a-call#how-to-invoke-your-function) is described earlier in this document.

```js title="Make an outbound call" description="Twilio will retrieve the TwiML from the provided URL and use it to handle the call"
exports.handler = function (context, event, callback) {
  // The pre-initialized Twilio client is available from the `context` object
  const twilioClient = context.getTwilioClient();

  // Query parameters or values sent in a POST body can be accessed from `event`
  const from = event.From || '+15017122661';
  const to = event.To || '+15558675310';
  // Note that TwiML can be hosted at a URL and accessed by Twilio
  const url = event.Url || 'http://demo.twilio.com/docs/voice.xml';

  // Use `calls.create` to place a phone call. Be sure to chain with `then`
  // and `catch` to properly handle the promise and call `callback` _after_ the
  // call is placed successfully!
  twilioClient.calls
    .create({ to, from, url })
    .then((call) => {
      console.log('Call successfully placed');
      console.log(call.sid);
      // Make sure to only call `callback` once everything is finished, and to pass
      // null as the first parameter to signal successful execution.
      return callback(null, `Success! Call SID: ${call.sid}`);
    })
    .catch((error) => {
      console.error(error);
      return callback(error);
    });
};
```

```js title="Make an outbound call" description="Directly provide TwiML instructions for how to handle the call"
exports.handler = function (context, event, callback) {
  // The pre-initialized Twilio client is available from the `context` object
  const twilioClient = context.getTwilioClient();

  // Query parameters or values sent in a POST body can be accessed from `event`
  const from = event.From || '+15017122661';
  const to = event.To || '+15558675310';
  // Note that the provided TwiML can be serialized as a string and sent!
  const twiml = event.Twiml || '<Response><Say>Ahoy there!</Say></Response>';

  // Use `calls.create` to place a phone call. Be sure to chain with `then`
  // and `catch` to properly handle the promise and call `callback` _after_ the
  // call is placed successfully!
  twilioClient.calls
    .create({ to, from, twiml })
    .then((call) => {
      console.log('Call successfully placed');
      console.log(call.sid);
      // Make sure to only call `callback` once everything is finished, and to pass
      // null as the first parameter to signal successful execution.
      return callback(null, `Success! Call SID: ${call.sid}`);
    })
    .catch((error) => {
      console.error(error);
      return callback(error);
    });
};
```

## Record an outbound call

When making an outgoing call, you can tell Twilio to record the entire call from beginning to end. Add the `record` argument to your call to `calls.create()`, set it to `true`, and Twilio will record the full call on your behalf.

Once the call is complete, you can listen to your recordings either in the [Twilio Console](https://www.twilio.com/console/voice/logs/recordings), or access them directly via the REST API for [Recordings](/docs/voice/api/recording).

```js title="Record an outbound call"
exports.handler = function (context, event, callback) {
  // The pre-initialized Twilio client is available from the `context` object
  const twilioClient = context.getTwilioClient();

  // Query parameters or values sent in a POST body can be accessed from `event`
  const from = event.From || '+15017122661';
  const to = event.To || '+15558675310';
  // Note that TwiML can be hosted at a URL and accessed by Twilio
  const url = event.Url || 'http://demo.twilio.com/docs/voice.xml';

  // Use `calls.create` to place a phone call. Be sure to chain with `then`
  // and `catch` to properly handle the promise and call `callback` _after_ the
  // call is placed successfully!
  // Note the addition of the `record` configuration flag for `calls.create`
  twilioClient.calls
    .create({ to, from, record: true, url })
    .then((call) => {
      console.log('Call successfully placed');
      console.log(call.sid);
      // Make sure to only call `callback` once everything is finished, and to pass
      // null as the first parameter to signal successful execution.
      return callback(null, `Success! Call SID: ${call.sid}`);
    })
    .catch((error) => {
      console.error(error);
      return callback(error);
    });
};
```
