# Use Twilio REST APIs from Apex

The Twilio for Salesforce package includes an [Apex](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dev_guide.htm) helper class that reduces the amount of code needed to interact with Twilio APIs. The Lightning components in the package focus only on SMS, so the helper class provides you with a way to write custom Apex to interact with any of Twilio's APIs, such as Voice and Chat.

> \[!NOTE]
>
> Code samples are written in Apex, but are labeled as Java for syntax highlighting purposes.

## Send Outbound SMS

```java
//Post Example
TwilioSF.TwilioApiClient api = new TwilioSF.TwilioApiClient();
api.addUrlPart('Accounts');
api.addUrlPart('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
api.addUrlPart('Messages.json');

api.addParam('To','+15558675310');
api.addParam('From','+15017122661');
api.addParam('Body','Here is my message');
TwilioSF.TwilioApiClientResponse response = api.doPost();

//Example with key value pairs
String sid = response.getTwilioJsonParser().get('sid').getString();
Integer totalSegments = response.getTwilioJsonParser().get('num_segments').getInteger();

//Example a key with object
String media = response.getTwilioJsonParser().get('subresource_uris').get('media').getString();

```

Twilio will verify that you've included a valid Twilio phone number in the `From` parameter, then either queue the call or return an error.

Check out the Messages API reference for the [full list of parameters](/docs/messaging/api/message-resource) you can include in your request. You can add these using the `addUrlPart` method. You can also find the [properties you can expect in the response from Twilio](/docs/messaging/api/message-resource).

## Send Message with Error Handling

```java
//Put Example with failures
TwilioSF.TwilioApiClient client = new TwilioSF.TwilioApiClient();
//Switch for throwing exceptions,=.
//client.setThrowExceptionsOnFailedResponses();
client.addUrlPart('Accounts');
client.addUrlPart('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
client.addUrlPart('Messages.json');

client.addParam('To','+15017122661');
client.addParam('From','+15558675310');
client.addParam('Body','Here is my message');


TwilioSF.TwilioApiClientResponse response = client.doPut();
system.debug(response.hasError());
system.debug(response.getErrorMessage());

```

Use `TwilioApiClientResponse` to retrieve the status code and error message from your request.

## Get Messages with no Params

```java
//Get Messages No Params
TwilioSF.TwilioApiClient client = new TwilioSF.TwilioApiClient();
client.addUrlPart('Accounts');
client.addUrlPart('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
client.addUrlPart('Messages');
client.addUrlPart('.json');
TwilioSF.TwilioApiClientResponse response = client.doGet();

system.debug(response.getTwilioJsonParser().get('first_page_uri').getString());
system.debug(response.getTwilioJsonParser().get('previous_page_uri').getString());
system.debug(response.getTwilioJsonParser().get('end').getInteger());
system.debug(JSON.serializePretty(response.toMap()));

```

This example shows you how to pull a list of messages from Twilio. By default, this method will return 50 results. The maximum number of records in a single request is [1000](/docs/usage/twilios-response). You can set how many results are returned using the `pageSize` param.

See the ["get messages with pagination" examples](#get-messages-with-pagination---example-1) for retrieving larger groups of messages.

## Get Messages with Params

```java
//Get Messages with Params
TwilioSF.TwilioApiClient client = new TwilioSF.TwilioApiClient();
client.addUrlPart('Accounts');
client.addUrlPart('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
client.addUrlPart('Messages');
client.addUrlPart('.json');

client.addParam('To','+15558675310');
client.addParam('PageSize','5');
client.addParam('DateSent','2018-06-01','>=');
TwilioSF.TwilioApiClientResponse response = client.doGet();

system.debug(response.getTwilioJsonParser().get('previous_page_uri').getString());
system.debug(response.getTwilioJsonParser().get('page_size').getInteger());
system.debug(JSON.serializePretty(response.toMap()));

String messagesString = response.getTwilioJsonParser().get('messages').getString();
List<TwilioJsonParser> messagesArray = response.getTwilioArrayJsonParser(messagesString);
for(TwilioJsonParser p:messagesArray){
   system.debug(p.get('sid').getString());
}

```

This example demonstrates how to retrieve a list of messages that match specified criteria. See [this documentation](/docs/messaging/api/message-resource#read-multiple-message-resources) to view additional options for filtering messages.

## Get Messages with Pagination - Example 1

```java
//Pagination
TwilioSF.TwilioApiClient client = new TwilioSF.TwilioApiClient();
client.addUrlPart('Accounts');
client.addUrlPart('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
client.addUrlPart('Messages');
client.addUrlPart('.json');


TwilioSF.TwilioApiClientResponse response = client.doGet();
String nextPage  = response.getTwilioJsonParser().get('next_page_uri').getString();
client.setNextUrl(nextPage);
while (client.hasNextPage()) {
    response = client.doGetNext();
    if(response.responseBody != null){
        nextPage  = response.getTwilioJsonParser().get('next_page_uri').getString();
        client.setNextUrl(nextPage);
    }
}

```

Get all messages in your Twilio account using pagination. In this example, you get the next page URL if it exists, and then call it in your Twilio client.

## Get Messages with Pagination - Example 2

```java
//Pagination Example
TwilioSF.TwilioApiClient client = new TwilioSF.TwilioApiClient();
client.addUrlPart('Accounts');
client.addUrlPart('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
client.addUrlPart('Messages');
client.addUrlPart('.json');


TwilioSF.TwilioApiClientResponse response = client.doGet();
String nextPage  = response.getTwilioJsonParser().get('next_page_uri').getString();
client.setNextUrl(nextPage);
if(client.hasNextPage()){
   response = client.doGetNext();

   String previousPage = response.getTwilioJsonParser().get('previous_page_uri').getString();
   client.setPreviousUrl(previousPage);

   if(client.hasPreviousPage()){
       response = client.doGetPrevious();
       system.debug(response.getTwilioJsonParser().get('uri').getString());
   }
}

```

## Delete Message

```java
//Delete Example
TwilioSF.TwilioApiClient client = new TwilioSF.TwilioApiClient();

client.addUrlPart('Accounts');
client.addUrlPart('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
client.addUrlPart('Messages');
client.addUrlPart('SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json');

TwilioApiClientResponse response = client.doDelete();
system.debug(response.getHtttpStatusCode());

```

## Get Messaging Services

```java
//Get Messages Services
TwilioSF.TwilioApiClient client = new TwilioSF.TwilioApiClient();
TwilioSF.TwilioApiClientResponse response = client.doGet('https://messaging.twilio.com/v1/Services');
system.debug(JSON.serializePretty(response.toMap()));

```

A messaging service is a pool of phone numbers that properly encodes your message body, matches the recipient's area code, and distributes SMS across multiple numbers. You can read more about messaging services here.

This code example demonstrates how to get a list of Messaging Services in your account.

## Update Messaging Services

```java
TwilioSF.TwilioApiClient client = new TwilioSF.TwilioApiClient();
client.setBaseUrl('https://messaging.twilio.com/');
client.setApiVersion('v1');
client.addUrlPart('Services');
client.addUrlPart('MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');

client.addParam('FriendlyName','Dev Org1');
TwilioSF.TwilioApiClientResponse response = client.doPost();

system.debug(response.getTwilioJsonParser().get('friendly_name').getString());
system.debug(response.getTwilioJsonParser().get('area_code_geomatch').getBoolean());
system.debug(response.getTwilioJsonParser().get('links').get('phone_numbers').getString());
system.debug(JSON.serializePretty(response.toMap()));

```

This example shows you how to update the friendly name of a messaging service using the Twilio API.

## Get Taskrouter Reservations

```java
//Task Router Get Reservations
TwilioSF.TwilioApiClient client = new TwilioSF.TwilioApiClient();
client.setBaseUrl('https://taskrouter.twilio.com/');
client.setApiVersion('v1');
client.addUrlPart('Workspaces');
client.addUrlPart('WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
client.addUrlPart('Workers');
client.addUrlPart('WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
client.addUrlPart('Reservations');

TwilioSF.TwilioApiClientResponse response = client.doGet();
system.debug(response.getTwilioJsonParser().get('meta').get('first_page_url').getString());
system.debug(JSON.serializePretty(response.toMap()));
String messagesString = response.getTwilioJsonParser().get('reservations').getString();
List<TwilioJsonParser> messagesArray = response.getTwilioArrayJsonParser(messagesString);
for(TwilioJsonParser p:messagesArray){
   system.debug(p.get('worker_sid').getString());
   system.debug(p.get('date_updated').getDatetime());
   system.debug(p.get('links').get('task').getString());
}

```

[Taskrouter](/docs/taskrouter) is an API for tracking the availability of call center workers and routing tasks to the appropriate worker. In this example, we pull the current list of open ("reserved") tasks for an individual worker.
