Make an API Call with the RESTAPI Action
The REST API action is one of the preferred methods of calling a REST web service from a Studio script. This page provides a tutorial on how to make a call to a REST API using the REST API action. It guides you through building the request and using the response in your script.
The example on this page builds a script that adds a book to a catalog through a REST endpoint. You can adapt the same pattern for any JSON-based API.
Example Request and Response
The example request is:
json
POST /api/books HTTP/1.1
Host: www.example.com
Content-Type: application/json
Accept: application/json
{
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"year": 1925,
"genre": "Fiction"
}
The example response is:
json
HTTP/1.1 201 Created
Content-Type: application/json
{
"id": 12345,
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"year": 1925,
"genre": "Fiction",
"message": "Book successfully added!" }Before You Begin
You need:
- A Studio script of any supported type, such as generic, phone, or digital.
- The URL, verb, and any authentication requirements for the endpoint you're calling. Test the request in a tool like Postman first, so you know it works before you build it into a script.
This example keeps the JSON body under the 32 KB response limit that applies to the REST API action. If your endpoint returns more data than that, filter the response or request only the fields you need.
Overview of the Script
The finished script has four actions that pertain to the REST call:
- A SNIPPET action that builds the JSON request body.
- A REST API action that sends the request and receives the response.
- A SNIPPET action, connected to the Success branch, that reads values out of the response.
- A SNIPPET action, connected to the Error branch, that reads the error details.
Step 1: Build the Request Payload
In Studio, open your script.
Add a SNIPPET action to the canvas and give it a caption, such as Build Book Request.
In the Data property, add the following code:
DYNAMIC bookRequest
ASSIGN bookRequest.title = "The Great Gatsby"
ASSIGN bookRequest.author = "F. Scott Fitzgerald"
ASSIGN bookRequest.year = 1925
ASSIGN bookRequest.genre = "Fiction"
ASSIGN bookRequestJson = "{bookRequest.asjson()}" Here's what each line does:
- DYNAMIC bookRequest creates a dynamic data object named bookRequest.
- Each ASSIGN line adds a member to the object. The member names (title, author, year, genre) become the keys in the JSON body, so make sure they match what the API expects.
- bookRequest.asjson() converts the object to a JSON string, and the result is stored in the bookRequestJson variable. You pass this variable into the REST API action in the next step.
In a production script, you would replace the hard-coded values with variables that hold real data collected earlier in the script, such as values from a form or a CRM
Third-party systems that manage such things as contacts, sales information, support details, and case histories. look-up.
Step 2: Set the REST API Action's Input Properties
Add a REST API action after the SNIPPET action and connect them. Give REST API a caption, such as Add Book, and set these Input properties:
| Property | Value | Notes |
|---|---|---|
| Verb | POST | Matches the API's documented method. |
| Service Address | https://www.example.com/api/books | The endpoint URL. You can also use a variable here, such as {bookApiUrl}. |
| Headers | {"Accept":"application/json","Content-Type":"application/json"} | Overrides the default headers, which use application/x-www-form-urlencoded by default. Add an Authorization header here if the API requires a bearer token or API key. |
| Parameters | {bookRequestJson} | References the JSON string you built in step 1. Curly brackets tell Studio to substitute the variable's value. |
| Wait Time In Milliseconds | 10000 | The default 10-second timeout. Raise it if the API is slow, up to the 90,000 millisecond maximum. |
Step 3: Set the REST API Action's Output Properties
Still in the REST API action, set the Output properties:
| Property | Suggested Name | What It Holds |
|---|---|---|
| Result Set | bookApiResult | The response body, automatically parsed into a dynamic data object you can reference with dot notation. |
| Error Arg List | bookApiError | Populated only when the request fails. Holds the HTTP status code, status description, and a message. |
You can keep the default names (resultSet and errorArgList) or rename them, as shown here, to something more specific to the call. Use the name you choose to reference the data in later actions.
Step 4: Wire the Branch Conditions
Connect the REST API action's branches to script logic designed to handle each possible response or result from the REST call. The REST API action already includes six result branches, so you don't need a separate branch or decision action.
| Branch | When it Fires |
|---|---|
| Success | The API returns a 2xx status code. |
| Error | The API returns an HTTP error status code. |
| Failure | An internal error prevents the request from completing. |
| InvalidInput | A property, such as Service Address, contains invalid data, or the request times out. |
| Throttle | Too many requests are sent in a short time. |
| Default | No response arrives within 90 seconds. |
For this example, connect Success to a SNIPPET action that processes the response, and connect Error to a SNIPPET action that handles the failure. You can route Failure, InvalidInput, Throttle, and Default to the same error-handling action, or add more granular handling if your script needs it.
Step 5: Use the Result Set in the Next Action
Add a SNIPPET action on the Success branch, with a caption such as Process Book Response. Because bookApiResult is already a dynamic data object, you can read its members directly using the same keys that came back in the JSON response:
ASSIGN newBookId = bookApiResult.id
ASSIGN confirmationMessage = bookApiResult.messageThe newBookId and confirmationMessage variables are now ordinary Studio variables. Pass them into whatever action comes next, such as writing them to a case, sending them in a follow-up API call, or displaying them to an agent. If you're working in a voice script, you could use them in a PLAY action prompt instead:
"%Your book was added with confirmation number" "${newBookId}" Add a second SNIPPET action on the Error branch, with a caption such as Handle Book API Error, to read the error details:
ASSIGN errorCode = bookApiError.httpstatuscode
ASSIGN errorDescription = bookApiError.description
ASSIGN errorMessage = bookApiError.messageThe exact member names on bookApiError will depend on the failure response returned from the web service you call. Check the API's documentation for a list of member names. You can also run a trace on the script and check the Trace Output window after a failed call to confirm the names before you build logic to handle them.
Full Script Example
The code below combines the two SNIPPET actions from steps 1 and 5. Copy each block into the Data property of the matching action in your script, and configure the REST API action's properties as described in steps 2 through 4.
clike
// SNIPPET: Build Book Request (before the REST API action)
DYNAMIC bookRequest
ASSIGN bookRequest.title = "The Great Gatsby"
ASSIGN bookRequest.author = "F. Scott Fitzgerald"
ASSIGN bookRequest.year = 1925
ASSIGN bookRequest.genre = "Fiction"
ASSIGN bookRequestJson = "{bookRequest.asjson()}"
// REST API action properties:
// Verb: POST
// Service Address: https://www.example.com/api/books
// Headers: {"Accept":"application/json","Content-Type":"application/json"}
// Parameters: {bookRequestJson}
// Result Set (out): bookApiResult
// Error Arg List (out): bookApiError
// SNIPPET: Process Book Response (on the Success branch)
ASSIGN newBookId = bookApiResult.id
ASSIGN confirmationMessage = bookApiResult.message
// SNIPPET: Handle Book API Error (on the Error branch)
ASSIGN errorCode = bookApiError.httpstatuscode
ASSIGN errorDescription = bookApiError.description
ASSIGN errorMessage = bookApiError.message