How to use Curl and Json from the Asterisk Dialplan to control call flow
TweetIt's very common that we want to use external services from our Asterisk Dialplan, and many times those external services are accessible via HTTP (such as a REST HTTP API).
In this article we are going to see how we can use cURL to query an external HTTP service and read a response in JSON format and take action on the values returned to control the call flow in our dialplan.
Using cURL to query an HTTP API from the Asterisk Dialplan
Asterisk has the CURL dialplan function that can be used to issue HTTP requests from the dialplan.
Once the request is done we can access the result (the body of the request) in the variable CURL_RESULT, by using the dialplan Set Application to set the variable value.
Using HTTPS to query REST APIs from the dialplan
In case you need to access an HTTPS endpoint with a self signed certificate or other SSL issues that may fail the HTTPS request, you can use the CURLOPT dialplan function to disable the ssl_verifypeer in cURL before doing the request:
Using the HTTP request result to fork in the Asterisk Dialplan
By using the GotoIf application of the Asterisk Dialplan one can take action depending on the value returned by the HTTP request:
The code above will issue a request for the file test.txt, and depending on the exact value will fork the execution to either the label result1 or result2, which is quite useful! Remember that we are checking the exact value (content) of the request, which in this case is the content of the test.txt file.
Using res_json in the Asterisk Dialplan to process a JSON string
It's quite common for APIs to return a JSON payload, and we can use res_json in our dialplan to parse the contents we get as a result of an HTTP request and act accordingly. This can be achieved by compilling and installing res_json according to the instructions and then from the dialplan:
We can test this by having the following contents for test.json:
Conclusion
Without too much effort we are now able to call HTTP APIs that return plain text or JSON strings and process them in our Asterisk dialplans to take decisions. Enjoy!