Send simple HTTP requests
Let us take a deep dive into the request method. Using this method, you can send HTTP requests to
a web server open to internet. It is a simple but powerful way to add all kinds of external functionality to
SWML scripts.
We will start by pulling a random dad joke from the internet and reading it out loud to the user.
The following points should be noted:
-
After
answering the phone call andplaying a short welcome message, we request a joke from the website icanhazdadjoke.com. -
We specifically state that we want the response to be in JSON format using the
Acceptheader. -
We have set the
save_variablesoption to betrue. SWML can parse the JSON response for you and save all the response objects into a variable namedrequest_response. -
The server gives back a JSON object in the form:
We read aloud the
jokeproperty of the response JSON using theplaymethod.
Sending POST request
Let us send some information to the server using a POST request.
Using your own server
So far, we have used publicly available test REST API. You can also write your own web server, and
interact with that using the request method.
An example server in Flask (Python) and Express (Node.js) is presented below:
Python/Flask
JavaScript/Express
If you need help opening up this web server from your localhost to the wider internet where SWML execution system can find it, consider using a tool like ngrok to expose your localhost.
Once this web server is up, you can write SWML to access this service.