Services like Twilio and [MailSlurp](/api/) offer phone number and SMS APIs that can be used to build SMS routing functionality for automation and testing.

## Create phone numbers

Create a phone number for a given region in the MailSlurp [dashboard](https://app.mailslurp.com/).

![phone number api](/assets/create-phone-number-api.jpg)

You can then access and control the phone number using the [MailSlurp API client](/docs/).



```typescript
const mailslurp = new MailSlurp({ apiKey });
// fetch a phone number (must create phone numbers in the dashboard first)
const { content } = await mailslurp.phoneController.getPhoneNumbers({
  size: 1,
  phoneCountry: GetPhoneNumbersPhoneCountryEnum.US,
});
const phoneNumber = content!![0]!!;
expect(phoneNumber.phoneNumber).toEqual("+19108074451");
```



### Redirect SMS with webhooks

Create a webhook for your phone number to route incoming SMS messages to your endpoint of choice, be that a server, slack, or lambda function.



```typescript
// create a webhook for a phone number to have new SMS sent to your server
const webhook = await mailslurp.webhookController.createWebhookForPhoneNumber({
  phoneNumberId: phoneNumber.id,
  createWebhookOptions: {
    eventName: CreateWebhookOptionsEventNameEnum.NEW_SMS,
    url: "https://myserver.com",
    name: "Process SMS",
  },
});
```



### Wait for arrival of SMS

In tests or automation logic you can hold a connection open until an expected SMS txt message is received:



```typescript
// wait for the latest unread sms
const [sms] = await mailslurp.waitController.waitForSms({
  waitForSmsConditions: {
    count: 1,
    unreadOnly: true,
    phoneNumberId: phoneNumber.id,
    timeout: 30_000,
  },
});
// extract a code from body with regex
expect(sms.body).toContain("Your code: 123");
const [, code] = /.+:\s([0-9]{3})/.exec(sms.body)!!;
expect(code).toEqual("123");
```



### Reading text messages in code

Extract SMS message content like so:



```typescript
// fetch a message
const txtMessage = await mailslurp.smsController.getSmsMessage({
  smsId: sms.id,
});
expect(txtMessage.read).toEqual(true);
expect(txtMessage.fromNumber).toEqual("+13252527014");
// delete all messages in phone number
await mailslurp.smsController.deleteSmsMessages({
  phoneNumberId: sms.phoneNumber,
});
```



## Other links

- [Developer documentation](/docs/)
- [Example projects](/examples/)
- [Getting started guide](/guides/getting-started/)
