How to test the Twilio API
Testing SMS code against real phones is slow and costs money per message. Twilio has a better option: test credentials. Requests made with them go through the same validation as real ones, but no message is sent and nothing is charged, and special "magic" phone numbers let you trigger specific errors on demand.
Step 1: Test credentials
In the Twilio Console, find your test credentials (an Account SID and Auth Token separate from your live ones).
| Variable | Value |
|---|---|
baseUrl | https://api.twilio.com/2010-04-01 |
accountSid | your test Account SID |
authToken | your test Auth Token, marked as secret |
On the collection's Authorization tab, choose Basic auth with username {{accountSid}} and password {{authToken}}.
Step 2: Send a message
Twilio takes form-encoded bodies. In the Body tab, choose x-www-form-urlencoded:
POST {{baseUrl}}/Accounts/{{accountSid}}/Messages.json
From=+15005550006
To=+14155552671
Body=Your verification code is 123456+15005550006 is Twilio's magic number for a valid sender. With test credentials, the message is accepted but never delivered:
const msg = pm.response.json();
pm.test('message accepted', () => {
pm.response.to.have.status(201);
pm.expect(msg.sid).to.match(/^SM/);
pm.expect(msg.status).to.be.oneOf(['queued', 'accepted']);
});Step 3: Trigger errors on purpose
The magic numbers let you check how your code handles failures, without hunting for a broken phone:
| Field | Magic number | Result |
|---|---|---|
To | +15005550001 | Error 21211: invalid To number |
To | +15005550009 | Error 21614: To can't receive SMS |
From | +15005550001 | Error 21212: invalid From number |
From | +15005550007 | Error 21606: number not owned by your account |
pm.test('invalid number is rejected with code 21211', () => {
pm.response.to.have.status(400);
pm.expect(pm.response.json().code).to.equal(21211);
});Twilio's error codes are more useful than the status code: your app can show "this number can't receive SMS" instead of "something went wrong". A data file with one row per magic number covers them all with one request.
Step 4: Wrong credentials
// "Send SMS (wrong token)": Basic auth with a wrong password
pm.test('rejects bad credentials', () => pm.response.to.have.status(401));Step 5: Run it in CI
requestarium run-collection "Twilio" --env TwilioTest \
--env-var accountSid=TWILIO_TEST_SID --env-var authToken=TWILIO_TEST_TOKENBecause test credentials never send or charge, this is safe to run on every pull request.