Best Practices for Developing On Twilio

Here’s a summary of a number of best practices we’ve found that work well in the development of your Twilio applications.

Using TwiML

This section covers pro tips related to handling inbound Twilio requests and responding to them with TwiML.

  • Use a helper library to generate your TwiML and avoid simple typo errors.
  • Make use of Fallback URLs for phone numbers and TwiML apps to prevent your users from hearing the dreaded “We’re sorry - an application error has occurred.”
  • If you’re looking to maintain any state around calls, be sure to leverage Status Callback URLs to get asynchronous notifications of completed calls.

Using the REST API

Here we cover a few helpful tips for using the REST API for outbound Twilio requests like placing calls or sending text messages.

  • Make use of the exceptions available in your helper library to prevent malformed phone numbers or missing permissions from causing fatal errors. Try/catching all outbound REST requests against these exceptions give you an easy way to handle errors gracefully and log for debugging later.
  • If making a large number of requests - like when sending text messages to a group of contacts - make use of a task queue like Celery to send asynchronously.
  • Use the new Usage API to reduce API calls for summary statistics on Twilio usage.

Using Twilio Client

Twilio Client for JavaScript, iOS and Android are excellent ways to stay in touch with your users.

  • Be sure to include a visual cue for first time users to click “Allow” in the pop-up permissions dialog.
  • Set your token expiration to a value that makes sense for your use case. By default, this is an hour.
  • Use the parameters property to surface important details to your users like who is calling and what is dialed.

Security

Security is critical to telephony applications - here’s some tips on using Twilio safely.

  • Never bundle your AccountSid and AuthToken in a client-side application, even if it is compiled.
  • Always generate Twilio Client capability tokens server-side.
  • Use Digest Authentication and SSL in concert for your TwiML URLs to make Twilio authenticate with your web server.
  • Use Request Validation to further confirm that requests are legitimately coming from Twilio.

Testing

Testing your apps before you go into production is always wise. Here are a few tips to make sure your tests work well.

  • If mocking the Twilio REST Client, be sure mock the resource instead of the client itself for best effect.
  • Simulate Twilio in your test web client by matching the parameters found in a Twilio request.
  • Test early, test often. It’s good for you!