TwilioAmanda Lange, Matthew SetterTutorial
How to Connect Your Twilio Agent to External APIs with PHP
Summary
The tutorial shows how to connect a Twilio voice agent to external REST APIs so an LLM-driven conversation can retrieve live information or support actions such as checking inventory or booking appointments. It builds the example in PHP 8.5 or later with OpenSwoole, Twilio Conversation Relay, OpenAI, and a WebSocket server, using Cat Facts as an unauthenticated API. The application exposes a POST /voice webhook that returns TwiML and connects Conversation Relay to a wss /ws endpoint, while session handling passes caller prompts into the OpenAI service. Tool calling routes the request to the Cat Facts endpoint, parses the JSON fact field, and returns either the fact, “No fact returned.”, or an error when the API response is unsuccessful or unavailable. Testing requires running php server.php, exposing port 8080 with ngrok, and configuring the Twilio number’s incoming webhook to /voice; the conclusion says external HTTP endpoints give agents real-time data.
Approach / What changed
The example creates a PHP project with OpenSwoole, configures environment variables through a .env file, starts an HTTP and WebSocket server, and uses Twilio Conversation Relay for the voice connection. An OpenAI service handles tool calling, while the application requests and parses data from the Cat Facts REST API. The local server is exposed with ngrok and connected to a Twilio phone number through a POST /voice webhook.
Takeaways
Twilio Conversation Relay connects the voice-capable Twilio number to a WebSocket endpoint served by the PHP application.
The Cat Facts example needs no additional API authentication; the OpenAI key is stored in .env, where future external API credentials can also be placed.
The external API response is checked for a successful HTTP status and a string fact field, with separate fallback messages for missing data and request errors.
FAQ
What happens when the Cat Facts API cannot supply a fact?
The code checks the HTTP status and parses the JSON fact field. It returns an error for a non-200 response and uses “No fact returned.” when the expected fact field is unavailable.
What authentication does the example require?
The Cat Facts API requires no additional authentication. The tutorial stores the OpenAI key in .env and says credentials for future authenticated APIs can also be kept there.
Source and freshness
- Source
- twilio.com
- Published
- Added to Yomu
Summaries are generated from the original by a language model. Check the original before relying on it.
Keep reading
Related reading
The Good Stuff
Paid picks we use ourselves. Links carry a referral code — a subscription through one earns us a commission at no extra cost to you.
The best engineering reads, once a week
One useful email. Unsubscribe anytime.