Alexa.Presentation.APL Interface Reference

The Alexa.Presentation.APL interface provides directives and requests that display content on a device with a screen, such as an Echo Show.

Alexa.Presentation.APL in supportedInterfaces

When the user's device has a screen that supports APL, the context.System.device.supportedInterfaces object includes [Alexa.Presentation.APL]:

Always check supportedInterfaces before returning the Alexa.Presentation.APL directives. For an example that does this with the ASK SDK, see Make sure the user's device supports APL in Use Alexa Presentation Language with the ASK SDK v2.

RenderDocument directive

Instructs the device to display the APL content provided in the specified document. You can also optionally provide one or more datasources to bind content to document.

The following RenderDocument example sends a document with two Text components and a data source called helloworldData.

{
  "type": "Alexa.Presentation.APL.RenderDocument",
  "token": "helloworldToken",
  "document": {
    "type": "APL",
    "version": "1.4",
    "mainTemplate": {
      "parameters": [
        "payload"
      ],
      "items": [
        {
          "type": "Container",
          "height": "100%",
          "width": "100%",
          "items": [
            {
              "type": "Text",
              "id": "helloTextComponent",
              "text": "${payload.helloworldData.properties.helloText}",
              "textAlign": "center",
              "textAlignVertical": "center",
              "maxLines": 3,
              "grow": 1
            },
            {
              "type": "Text",
              "id": "newHelloTextComponent",
              "text": "${payload.helloworldData.properties.newHelloText}",
              "textAlign": "center",
              "textAlignVertical": "bottom",
              "maxLines": 3,
              "opacity": 0
            }
          ]
        }
      ]
    }
  },
  "datasources": {
    "helloworldData": {
      "type": "object",
      "objectId": "helloworld",
      "properties": {
        "helloText": "Hello world! This APL document displays text from a datasource called helloworldData.",
        "newHelloText": "I hid the original hello text and then displayed this!"
      }
    }
  }
}

You can also save your document with your skill in the authoring tool and then provide a link to it in the RenderDocument directive. The following example assumes that "hello world" document has been saved with the name "helloworld-by-link".

{
  "directives": [
    {
      "type": "Alexa.Presentation.APL.RenderDocument",
      "token": "helloworldToken",
      "document": {
        "src": "doc://alexa/apl/documents/helloworld-by-link",
        "type": "Link"
      },
      "datasources": {
        "helloworldData": {
          "type": "object",
          "objectId": "helloworld",
          "properties": {
            "helloText": "Hello world! This APL document displays text from a datasource called helloworldData.",
            "newHelloText": "I hid the original hello text and then displayed this!"
          }
        }
      }
    }
  ]
}

RenderDocument properties

Property Type Required Description
type String Yes Set to Alexa.Presentation.APL.RenderDocument
token String Yes String that identifies the document. You use this when you issue subsequent directives that refer to the document. For example, you need this token when you send the ExecuteCommands directive.
document Object Yes An object representing the APL document to send to the device.

When document.type is "APL", document must contain the complete JSON document.

When document.type is "Link", document must contain the src property with the reference to the document.
document.type APL | Link Yes Indicates the type of document to send. Set to "APL" when document contains the full document object. Set to "Link" when document.src contains a document link.
document.src URL When document.type is Link The URL that identifies the document in the authoring tool. For APL, the link has the following syntax: doc://alexa/apl/documents/<document-name>. Replace <document-name> with the name you used when saving the document. Don't include this property when document.type is APL.
sources Map of additional documents or references to documents No An object containing named APLA documents or links. These documents can be referenced by the "template" parameter in the aplAudioToSpeech transformer.
datasources Map of data source objects No Object that can contain other objects that you can use to bind data to the APL document.

The document property must always contain either the src property set to the URL for a document, or the JSON for the full document.

For an example showing how you would send RenderDocument with the ASK SDK v2, see Return RenderDocument in your request handler response in Use Alexa Presentation Language with the ASK SDK v2.

Use a linked document with RenderDocument

You can save an APL document in the authoring tool and then use a link to that document in the RenderDocument directive. This means you don't need to export the JSON for your APL document and copy it into your code.

A link to a document in the authoring tool has the following syntax:

doc://alexa/apl/documents/<document-name>

The <document-name> is the name you used when saving the document in the authoring tool.

For details about building and saving a document in the authoring tool, see Construct an APL document with the Authoring Tool.

RenderDocument and other skill directives

  • Your response can combine RenderDocument with any of the of the Dialog directives except for Dialog.Delegate. For example, you can use Dialog.ElicitSlot to ask the user for a slot value, and at the same time display information related to that slot on the screen with RenderDocument.
  • Your response cannot combine RenderDocument with directives from the following interfaces:
    • AudioPlayer
    • Display
    • VideoApp

ExecuteCommands directive

Instructs the device to execute the provided commands on the currently rendered document identified by the token.

The following example sends an ExecuteCommands directive that acts on the document identified with the token helloworldToken. This directive has two commands:

  • The first AnimateItem command changes the opacity of the component helloTextComponent to 0 over 3 seconds to make it fade from view.
  • The second AnimateItem command changes the opacity of the component newHelloTextComponent from 0 to 1 over 3 seconds to make it fade into view.
{
  "type": "Alexa.Presentation.APL.ExecuteCommands",
  "token": "helloworldToken",
  "commands": [
    {
      "type": "AnimateItem",
      "componentId": "helloTextComponent",
      "duration": "3000",
      "easing": "linear",
      "value": [
        {
          "property": "opacity",
          "to": "0.0"
        }
      ]
    },
    {
      "type": "AnimateItem",
      "componentId": "newHelloTextComponent",
      "duration": "3000",
      "easing": "linear",
      "value": [
        {
          "property": "opacity",
          "to": "1.0"
        }
      ]
    }
  ]
}

ExecuteCommands properties

Property Type Required Description
type String Yes Set to Alexa.Presentation.APL.ExecuteCommands
token String Yes A string that identifies the RenderDocument command used to display the document these commands apply to.
commands Array of commands Yes Commands to execute on the rendered document identified by the token. The array of commands behaves like an implicit Sequential command. That is, the commands execute one after the other rather than in parallel.

The ExecuteCommands directive targets the commands against the specific document identified with the token. The token you provide in the ExecuteCommands directive must match the token you provided with the RenderDocument directive that sent the corresponding document.

You can send the RenderDocument and ExecuteCommands directives in the same skill response, or separate responses:

  • When your response includes both directives, the device displays the specified document first, then executes the commands, provided the token matches in both directives.
  • When you return ExecuteCommands in a separate response, the device executes the commands against the document currently displayed on the viewport. The token must match the token used in the earlier RenderDocument directive.

    Before you send ExecuteCommands in this scenario, check the visual context in the request to confirm that the document is currently displayed. You can get the token for the currently displayed document from the context.["Alexa.Presentation.APL"].token property in the request.

In both cases, if the token values do not match between the directives, the commands are not executed.

The following example request shows that the viewport is currently displaying the document with the token helloworldWithButtonToken (for brevity, some parts of this request are omitted).

{
  "version": "1.0",
  "session": {},
  "context": {
    "Alexa.Presentation.APL": {
      "token": "helloworldWithButtonToken",
      "version": "APL_WEB_RENDERER_GANDALF",
      "componentsVisibleOnScreen": [
        {
          "uid": ":1000",
          "position": "1024x600+0+0:0",
          "type": "text",
          "tags": {
            "viewport": {}
          },
          "children": [
            {
              "id": "fadeHelloTextButton",
              "uid": ":1002",
              "position": "270x70+377+450:0",
              "type": "text",
              "tags": {
                "focused": false,
                "clickable": true
              },
              "entities": []
            }
          ],
          "entities": []
        }
      ]
    },
    "System": {},
    "Viewport": {},
    "Viewports": []
  },
  "request": {}
}

For an example that shows how you check for this property and return ExecuteCommands with the ASK SDK, see Return ExecuteCommands in a request handler response in Use Alexa Presentation Language with the ASK SDK v2.

ExecuteCommands and other skill directives

Your response cannot combine ExecuteCommands with directives from the following interfaces:

  • AudioPlayer
  • Dialog
  • Display
  • VideoApp

SendIndexListData directive

Sends a new set of list items to display, in response to a LoadIndexListData request. Include a dynamicIndexList data source with the next set of items to display. Don't include outputSpeech or shouldEndSession in your response.

Property Type Required Description
type Directive Yes Set to Alexa.Presentation.APL.SendIndexListData
token String Yes The presentation token specified in the RenderDocument directive sent to Alexa.
correlationToken String Yes, when sent in response to a LoadIndexListData The correlation token supplied in the LoadIndexListData request. Required when sent in response to a LoadIndexListData. Can be omitted otherwise. See Proactive loading.
listId String Yes The identifier for the list to update with this response.
listVersion Integer No The new version number for the list following the update, used to maintain list consistency between the skill and the device. Required when you also use UpdateIndexListData to update the same list, otherwise not required.
startIndex Integer Yes Index of the first element in the items array.
minimumInclusiveIndex String No The index of the first item in the array. When populated, this value replaces any value specified in a previous interaction. Absence of this property indicates that the minimum index is not yet known and Alexa continues requesting more items as the user scrolls backwards (the list is a backward-scrolling list). When equal to the index of the first item returned, no further backwards scrolling is possible and Alexa stops requesting more items.
maximumExclusiveIndex String No The last valid index of the array plus one. When populated, this value replaces any value specified in a previous interaction. Absence of this property indicates that the maximum index is not yet known and Alexa continues requesting more items as the user scrolls forwards (the list is a forward-scrolling list). When this property is one more than the index of the last item returned then no further forward scrolling is possible and Alexa stops requesting more items.
items Array No Array of objects to add to the list.
{
  "directives": [
    {
      "type": "Alexa.Presentation.APL.SendIndexListData",
      "token": "developer-provided-token",
      "correlationToken": "alexa-provided-correlation-token",
      "listId": "my-list-id",
      "listVersion": 3,
      "startIndex": 11,
      "minimumInclusiveIndex": 11,
      "maximumExclusiveIndex": 21,
      "items": [
        {"primaryText":"item 11"},
        {"primaryText":"item 12"},
        {"primaryText":"item 13"},
        {"primaryText":"item 14"},
        {"primaryText":"item 15"},
        {"primaryText":"item 16"},
        {"primaryText":"item 17"},
        {"primaryText":"item 18"},
        {"primaryText":"item 19"},
        {"primaryText":"item 20"}
      ]
    }
  ]
}

Proactive loading

You must provide the correlationToken when your skill responds to a LoadIndexListData request. Alexa rejects the skill response if the expected correlationToken is not specified in exactly one SendIndexListData directive.

Omit the correlationToken when you send a set of list items not in response to a LoadIndexListData request.

UpdateIndexListData directive

Send a set of data operations to Alexa to insert, set, and delete list items in a data source that has already been sent to the device in a RenderDocument directive. You can include multiple changes in a single directive.

Property Type Required Description
type Directive Yes Set to Alexa.Presentation.APL.UpdateIndexListData
token String Yes The presentation token specified in the RenderDocument directive sent to Alexa.
listId String Yes The identifier for the list to update with this response.
listVersion Integer Yes The new version of the list following the update, used to maintain list consistency between the skill and Alexa.
operations Array Yes Individual operations to apply to the list, in array order. Alexa applies each item in it's entirety before processing the next operation in the array. Fully applying an operation includes making the change and updating the index locations of surrounding items. If a failure occurs when processing an operation, Alexa discards later operations in the array AND discards further directives which attempt to update the items in the target datasource.
{
  "directives": [
    {
      "type": "Alexa.Presentation.APL.UpdateIndexListData",
      "token": "developer-provided-token",
      "listId": "my-list-id",
      "listVersion": 3,
      "operations": [
        {
          "type": "InsertItem",
          "index": 10,
          "item": {
            "primaryText": "new item 9.5, inserted before item 10"
          }
        },
        {
          "type": "InsertMultipleItems",
          "index": 12,
          "items": [
            {"primaryText":"first of three new items, inserted before item 12"},
            {"primaryText":"second of three"},
            {"primaryText":"third of three"}
          ]
        },
        {
          "type": "SetItem",
          "index": 14,
          "item": {"primaryText":"Replacement text for item 14"}
        },
        {
          "type": "DeleteItem",
          "index": 16
        },
        {
          "type": "DeleteMultipleItems",
          "index": 17,
          "count": 2
        }
      ]
    }
  ]
}

listVersion

The new version of the list following the update, used to maintain list consistency between the skill and Alexa. Alexa assumes all lists start at version 0, so the first UpdateIndexListData directive issued for a particular list sets listIndex to 1. Alexa buffers any UpdateIndexListData directives specifying an out-of-sequence listVersion until the missing or intermediate directives are received and processed.

This field is required for UpdateIndexListData but optional for SendIndexListData in some cases:

  • When you don't do any insert, set, or delete updates on the list, you don't need to populate this value.
  • When you do perform insert, set, or delete operations on the list, you must populate this value for all SendIndexListData directives.

Therefore, for a particular list, Alexa discards the following:

  • All UpdateIndexListData directives received after a SendIndexListData directive which didn't specify a listVersion.
  • All SendIndexListData directives that don't specify a listVersion after receipt of a UpdateIndexListData directive.

operations

Enumeration of possible update operations.

InsertItem

Inserts a single item into the data source at the specified index.

You can insert items within the range of the list or add the items to the end of the list. Attempts to insert items at non-adjacent indexes results in an error. For example, if the current indexes range from M to N, you can insert items into in the range M to N+1.

Field Type Required Description

index

Integer

Yes

The index at which to insert the item in the existing list. All existing list items at indexes greater or equal to the insert index increase by one. If defined, the value of maximumExclusiveIndex in the data source also increases by one.

item

Object

Yes

The item data to include at the specified list index.

For example, the initial data source had 10 items with indexes 0-9. An InsertItem operation with index set to 5 does the following:

  • Inserts the new item at position 5.
  • Updates the index for the existing items 5-9 to 6-10. The original item 5 becomes 6, the original 6 becomes 7, and so on.
  • Updates the maximumExclusiveIndex property for the data source from 10 to 11.

InsertMultipleItems

Inserts an array of items at the specified index.

You can insert items within the range of the list or add the items to the end of the list. Attempts to insert items at non-adjacent indexes results in an error. For example, if the current indexes range from M to N, you can insert items into in the range M to N+1.

Field Type Required Description

index

Integer

Yes

The index at which to insert the first of the specified items in the existing list, with the rest of the items inserted at sequentially increasing indexes. All existing list items at indexes greater or equal to the insert index increase by the length of the items array. If defined, the value of maximumExclusiveIndex in the data source also increases by the items array length.

items

Array

Yes

The array of item data to include at the specified list index.

For example, the initial data source had 10 items with indexes 0-9. An InsertMultipleItem operation with index set to 5 and 2 new items in items does the following:

  • Inserts the two new items at positions 5 and 6.
  • Adds 2 to the index for the original items 5-9. The original item 5 becomes 7, the original item 6 becomes item 8, and so on.
  • Updates the maximumExclusiveIndex property for the data source from 10 to 12.

SetItem

Replace the item at the specified index with the provided item.

Field Type Required Description

index

Integer

Yes

The index of the item to replace in the existing list. The definition and indexes of all other items in the list are unchanged. An attempt to set an item at an unpopulated index results in an error.

item

Object

Yes

The new item data for the specified list index.

For example, the initial data source had 10 items with indexes 0-9. A SetItem operation with index set to 5 does the following:

  • Replaces the existing item at position 5 with the new item.

DeleteItem

Delete the item at the specified index.

Field Type Required Description

index

Integer

Yes

The index of the item to delete in the existing list. All existing list items at indexes greater than the delete index decrease by one. If defined, the value of maximumExclusiveIndex in the data source also decreases by one. Any attempt to delete an item at an unpopulated index results in an error.

For example, the initial data source had 10 items with indexes 0-9. A DeleteItem operation with index set to 5 does the following:

  • Deletes the existing item at position 5.
  • Updates the index for the existing items 6-9 to 5-8. The original item 6 becomes 5, the original item 7 becomes 6, and so on.
  • Updates the maximumExclusiveIndex property for the data source from 10 to 9.

DeleteMultipleItems

Delete the specified count of items from the data source, beginning at the specified index.

Field Type Required Description

index

Integer

Yes

The index of the first item to delete in the existing list, with the rest of the items deleted at sequentially increasing indexes. All existing list items at indexes greater than those which have are deleted decrease their index by the count. If defined, the value of maximumExclusiveIndex also decreases by the count. Any attempt to delete an item at an unpopulated index results in an error.

count

Integer

Yes

The number of items at sequentially increasing indexes to delete.

For example, the initial data source had 10 items with indexes 0-9. A DeleteMultipleItems operation with index set to 5 and count set to 2 does the following:

  • Deletes the original items at positions 5 and 6.
  • Subtracts 2 from the index for the original items 7-9. The original item 7 gets a new index of 5, the original item 8 becomes item 6, and and the original item 9 becomes 7.
  • Updates the maximumExclusiveIndex property for the data source from 10 to 8.

Error Cases

When an error occurs, your skill receives a RuntimeError request.

The following table summarizes the possible error cases.

Error description Exception Reason System response
UpdateIndexListData has a missing required field N/A Alexa rejects the incoming directive.
The directive payload, or any list item exceeds the maximum permitted length N/A The platform rejects the incoming directive.
UpdateIndexListData has an unrecognized token or listId INVALID_PRESENTATION_TOKEN or INVALID_LIST_ID Alexa discards the incoming directive.
UpdateIndexListData or SendIndexListData specifies a listVersion which is greater than expected N/A The directive is sent to Alexa where it is buffered until intermediate directives are received & processed.
The directive is buffered longer than a specified duration. MISSING_LIST_VERSION Alexa continues to buffer the directive.
Alexa is unable or unwilling to buffer further out-of-order directives, e.g. due to insufficient memory MISSING_LIST_VERSION Alexa discards the buffered directive with the greatest listVersion.
UpdateIndexListData or SendIndexListData specifies a listVersion which is lower than expected DUPLICATE_LIST_VERSION Alexa discards the incoming directive.
Skill returns an UpdateIndexListData with an unrecognized operation type INVALID_OPERATION Alexa discards the incoming directive and places list in 'failed' state where it accepts no further updates.
Skill returns an insert, set or delete operation with index outside of the range of permitted values. LIST_INDEX_OUT_OF_RANGE Alexa discards the incoming directive and places list in 'failed' state where it accepts no further updates.
A list receives an UpdateIndexListData directive after a SendIndexListData directive which did not specify a listVersion. MISSING_LIST_VERSION_IN_SEND_DATA Alexa discards the incoming directive and places list in 'failed' state where it accepts no further updates.
A list receives a SendIndexListData directive which does not specify a listVersion after a UpdateIndexListData directive. MISSING_LIST_VERSION_IN_SEND_DATA Alexa discards the incoming directive and places list in 'failed' state where it accepts no further updates.

LoadIndexListData request

Alexa sends your skill a LoadIndexListData request to ask for more list items for a dynamicIndexList data source. For example, your skill gets this request when the user scrolls near the end of the previously-loaded items.

Property Type Required Description
type String Yes Set to Alexa.Presentation.APL.LoadIndexListData
token String Yes The presentation token specified in the RenderDocument directive sent to Alexa.
correlationToken String Yes An Alexa-generated identifier used to correlate requests with their corresponding response directives. Include this when you respond with a SendIndexListData directive.
listId String Yes The identifier of the list for which to fetch items.
startIndex String Yes The lowest index of the items to fetch (inclusive)
count Integer Yes The number of items to fetch.
{
  "request": {
    "type": "Alexa.Presentation.APL.LoadIndexListData",
    "requestId": "amzn1.echo-api.request.1",
    "timestamp": "2020-03-12T19:47:02Z",
    "locale": "en-US",
    "token": "developer-provided-token",
    "correlationToken": "101",
    "listId": "my-list-id",
    "startIndex": 20,
    "count": 10
  }
}

Valid responses

You can respond to a LoadIndexListData request with a SendIndexListData directive.

RuntimeError request

Sent to notify the skill about any errors that happened during APL processing. This request is for notification only. The skill can't return a response to a RuntimeError request.

Property Type Required Description
type String Yes Set to Alexa.Presentation.APL.RuntimeError
token String Yes The presentation token specified in the RenderDocument directive sent to Alexa.
errors Array Yes An array of reported errors.
{
  "type": "Alexa.Presentation.APL.RuntimeError",
  "token": "developer-provided-token",
  "errors": [
    {
      "type": "LIST_ERROR",
      "reason": "LIST_INDEX_OUT_OF_RANGE",
      "listId": "my-list-id",
      "listVersion": 3,
      "operationIndex": 3,
      "message": ""
    }
  ]
}

errors

Property Type Required Description
type String Yes Polymorphic error type indicator.
reason String Yes Describes the type of error which occurred.
message String Yes A human-readable description of the error.

type

Polymorphic error type indicator. Every type could have specific parameters.

Possible values:

Property Description
LIST_ERROR Errors related to processing a dynamicIndexList data source.

reason

Error type specific failure reasons. Generic values available for any type:

  • INTERNAL_ERROR – unexpected issue in the Alexa service.
LIST_ERROR

For possible reasons see: Error cases.

Field Type Required Description
listId String Yes Contains the identifier of the list which encountered the error.
listVersion String No Contains the listVersion specified by the update which encountered the error (when known)
operationIndex Integer No Contains the index of the operation which caused the error (when known)

UserEvent request

Alexa sends your skill an Alexa.Presentation.APL.UserEvent request when an event on the device triggers the SendEvent command. This lets your skill service receive messages in response to the user's actions on the device. You can use event handlers on components in your document to trigger SendEvent. For example, the TouchWrapper component has an onPress event handler. You can set this handler to the SendEvent command to get a UserEvent request when a user touches the component on the viewport.

The UserEvent request includes information about the component and the event that triggered the SendEvent command. When you define SendEvent in a component's event handler, you can specify the information you want to get in the corresponding UserEvent request. Use this in your event handler in your code.

UserEvent properties

Property Type Description
type String Always set to Alexa.Presentation.APL.UserEvent
token String Token provided with the RenderDocument or ExecuteCommands directive that sent this UserEvent.
arguments Array of values Array of values specified in the arguments property of the SendEvent command that triggered this request.
source Object Information about the APL component and event handler (if applicable) that was the source of this event.
components Object Value of each component identified in the components property of the SendEvent command that triggered this request.

The following example shows part of an APL document that sends an event to a skill when the user presses one of the TouchWrapper components rendered by the Sequence component via touch or a d-pad on a remote control.

{
  "type": "Sequence",
  "id": "myCustomSequence",
  "height": "100vh",
  "data": "${payload.templateData.properties.animalList}",
  "numbered": true,
  "item": {
    "type": "TouchWrapper",
    "id": "animalListTouchWrapper",
    "item": {
      "type": "Text",
      "text": "${data.textToShow}"
    },
    "onPress": [
      {
        "type": "SendEvent",
        "arguments": [
          "listItemPressed",
          "${ordinal}",
          "${data.dataToSend}"
        ]
      }
    ]
  }
}

The Sequence uses a data source called templateData to display a series of items in the Sequence and define the data to include in the UserEvent. The following example illustrates this data source.

{
  "templateData": {
    "properties": {
      "animalList": [
        {
          "textToShow": "Aardvark",
          "dataToSend": "animalKey123"
        },
        {
          "textToShow": "Aardwolf",
          "dataToSend": "animalKey124"
        },
        {
          "textToShow": "Baboon",
          "dataToSend": "animalKey202"
        }
      ]
    }
  }
}

In the above example, the arguments array for the SendEvent command specifies three items:

  • The static text "listItemPressed"
  • The ordinal property from the data-binding context. This property is available since the TouchWrapper is a child component of a Sequence.
  • The value of the item's dataToSend property, from the data source.

Therefore, when the user selects the second item ("Aardwolf"), the skill gets a UserEvent request that looks like the following.

{
  "version": "1.0",
  "session": {},
  "context": {},
  "request": {
    "type": "Alexa.Presentation.APL.UserEvent",
    "requestId": "amzn1.echo-api.request.1",
    "token": "token-provided-with-RenderDocument",
    "timestamp": "2020-01-17T16:48:11Z",
    "locale": "en-US",
    "arguments": [
      "listItemPressed",
      2,
      "animalKey124"
    ],
    "components": {},
    "source": {
      "type": "TouchWrapper",
      "handler": "Press",
      "id": "animalListTouchWrapper"
    },
  }
}

Get component data in the UserEvent

In addition to the data provided in the source and arguments properties, you can also get information about other components displayed on the viewport. To do this, assign each component an identifier with the id property. Then include the id for each component you want in the components array in your SendEvent command.

For example, each component has a checked state that can be true or false. You can use the SetValue command to change the checked state in response to user interaction. The following AlexaButton example toggles the checked state and changes the button text when the user selects the button.

{
  "type": "AlexaButton",
  "id": "idForTheToggleButton",
  "buttonText": "Toggle button: false",
  "primaryAction": [
    {
      "type": "SetValue",
      "componentId": "idForTheToggleButton",
      "property": "checked",
      "value": "${!event.source.value}"
    },
    {
      "type": "SetValue",
      "componentId": "idForTheToggleButton",
      "property": "buttonText",
      "value": "Toggle button: ${!event.source.value}"
    }
  ],
  "spacing": "@spacingSmall",
  "alignSelf": "center"
}

Then, a separate TouchWrapper in the document triggers SendEvent and includes the button ID idForTheToggleButton in the components array, as shown in the following example.

{
  "type": "TouchWrapper",
  "id": "idForTheTouchWrapper",
  "spacing": "@spacingSmall",
  "alignSelf": "center",
  "onPress": [
    {
      "type": "SendEvent",
      "arguments": [
        "textWasPressed",
        "Send this data to the skill"
      ],
      "components": [
        "idForTheToggleButton",
        "idForTheTextComponent"
      ]
    }
  ],
  "item": {
    "type": "Text",
    "id": "idForTheTextComponent",
    "color": "@colorAccent",
    "text": "Click to send a UserEvent to the skill."
  }
}

The user can select the toggle button repeatedly to flip its state between true and false. When the user then selects the "Click to send…" text, your skill receives the following UserEvent. Note that components includes idForTheToggleButton with its current checked state:

{
  "type": "Alexa.Presentation.APL.UserEvent",
  "requestId": "amzn1.echo-api.request.1",
  "timestamp": "2020-01-20T22:46:04Z",
  "locale": "en-US",
  "arguments": [
    "textWasPressed",
    "Send this data to the skill"
  ],
  "components": {
    "idForTheTextComponent": "Click to send a UserEvent to the skill.",
    "idForTheToggleButton": true
  },
  "source": {
    "type": "TouchWrapper",
    "handler": "Press",
    "id": "idForTheTouchWrapper"
  },
  "token": "token-provided-with-RenderDocument"
}

For an additional example that illustrates how you could create a handler for UserEvent with the ASK SDK, see Handle a UserEvent request in Use Alexa Presentation Language with the ASK SDK v2.

Valid response types

Your skill can respond to the UserEvent request with a standard response. You can include any custom skill directives except for Dialog.Delegate.

Viewport object in the skill request

Every request sent to your skill includes information about the supported viewports for the user's device. You can use this information in your code to craft appropriate responses.

For a device with a screen, the viewport information is in the context.Viewport object.

Viewport information is also available in the data-binding context in the viewport property. The specific information available in the data-binding context differs from the information available in the skill request. For details, see Viewport Object in the Data-binding Context.

  • Use the context.Viewport object in the skill request when you need viewport information in your skill code.
  • Use the viewport property in the data-binding context when you need viewport information in your APL document, such as for creating a when condition to show a particular component only on certain viewports. See Viewport Object in the Data-binding Context

This example shows a skill request with the context.Viewport object, with some details removed for brevity:

{
  "version": "1.0",
  "session": {},
  "context": {
    "System": {},
    "Viewport": {
      "experiences": [
        {
          "arcMinuteWidth": 282,
          "arcMinuteHeight": 141,
          "canRotate": false,
          "canResize": false
        }
      ],
      "shape": "RECTANGLE",
      "pixelWidth": 960,
      "pixelHeight": 480,
      "dpi": 160,
      "currentPixelWidth": 960,
      "currentPixelHeight": 480,
      "touch": [
        "SINGLE"
      ],
      "keyboard": [
        "DIRECTION"
      ],
      "video": {
        "codecs": [
          "H_264_41"
        ]
      }
    },
    "Viewports": [
      {
        "type": "APL",
        "id": "main",
        "shape": "RECTANGLE",
        "dpi": 160,
        "presentationType": "STANDARD",
        "canRotate": false,
        "configuration": {
          "current": {
            "video": {
              "codecs": [
                "H_264_41"
              ]
            },
            "size": {
              "type": "DISCRETE",
              "pixelWidth": 960,
              "pixelHeight": 480
            }
          }
        }
      }
    ]
  },
  "request": {}
}

Viewport properties

The following properties are defined in the Viewport object.

Property Type/Values Description
experiences Array of experience objects Different modes in which the customer is expected to interact with the viewport.
shape ROUND or RECTANGLE Shape of the viewport.
pixelHeight Integer Height of the viewport in pixels.
pixelWidth Integer Width of the viewport in pixels.
currentPixelWidth Integer Width of the viewport in pixels that is currently in use.
currentPixelHeight Integer Height of the viewport in pixels that is currently in use.
dpi Integer Pixel density of the viewport.
touch Array of strings Touch events that the viewport supports.
keyboard Array of strings Input mechanisms for interacting with the viewport.
video Object Specification of which technologies are available for playing video on a device

Experiences

The experiences property contains a list of experience types supported by the device. The experience types depend on the modes supported by a viewport. You can use this information to optimize your skill's behavior for a specific experience. For example, a tablet device might have two different experiences: one for when it is docked and the other for when the customer is holding it. In these cases the skill's visual response should be optimized for both experiences, as the device owner can arbitrarily switch between the experiences.

experience properties

Property Type/Values Description
canRotate Boolean Whether the viewport can be rotated through 90, 180, and 270 degrees.
canResize Boolean Whether the viewport can be resized.

Pixel height and width

The pixelHeight and pixelWidth properties represent the number of pixels present in the viewport at its maximum height and width. These values assume a static device orientation, and express the entire viewport size regardless of whether areas of the viewport are currently in use by other applications.

Current pixel width and height

The currentPixelWidth and currentPixelHeight properties represent the number of horizontal and vertical pixels that are available for Alexa to render an experience. These values also assume a static device orientation.

Shape

The shape of the screen is set to either ROUND or RECTANGLE.

dpi

The display-independent pixel (dp) measurement of a screen is an artificial value that represents the visual size of the screen assuming that the screen is held at a mobile-phone viewing distance and has a pixel density of approximately 160 pixels per inch. Two screens viewed at the same distance with the same physical size have approximately the same dp dimensions regardless of the actual pixel density of the screen.

The dots-per-inch (dpi) of a viewport is an artificial value that reflects the visual size of a point or pixel relative to the observer, and it does not match the actual pixels-per-inch size of the screen. The formula for dpi is:

dpi = 160 * (pixelSize / dpSize)

For simplicity, dpi values are simplified to fall into consistent buckets of 120, 160, 240, 320, and so forth.

Touch

The touch property represents what kind of touch inputs the device supports. The touch array can contain the following values:

  • SINGLE - indicates that the device supports single-touch inputs

Keyboard

The keyboard property represents physical button input mechanisms that can be used to interact with the viewport. The keyboard array can contain the following values:

  • DIRECTION - there are inputs for the up/down/left/right directions as well as a button to select whatever is at the current location

Video

The video property details which technologies are available for playing video on a device. Use the video properties to determine what types of video resources to send in an APL response. For example, your skill's APL response could return video resources with different encodings depending on the video codec level that a device supports.

Note that some devices with screens do not support video playback. In this case, the video property is not present. If your skill includes video, be sure to check for this property and provide an appropriate experience for devices that do not support video. If you send a Video to a device that does not support video, the component remains on the screen, but displays no content so users will see a blank area on the screen.

video properties

Property Type/Values Description
codecs Array of Strings

The video codecs that the output device supports. Supported values:

  • H_264_41: H.264 at a maximum resolution of 1080p @ 30fps (codec level 4.1) and supporting the main- and high-capability profiles (MP and HP).
  • H_264_42: H.264 at a maximum resolution of 1080p @ 60fps (codec level 4.2) and supporting the main- and high-capability profiles (MP and HP).

H_264_41 is a subset of H_264_42. All skill requests that specify H_264_42 will also specify H_264_41. All video-capable devices support the MPEG-4 Part-14 container (MP4), along with AAC and MP3 audio codecs.

Access the viewport information in your code

The Alexa Skills Kit SDKs include helper functions for getting viewport information from the skill request. The getViewportProfile method checks multiple criteria within context.Viewport to return a value that corresponds to the viewport profiles available in the viewport profiles package:

  • HUB-ROUND-SMALL
  • HUB-LANDSCAPE-SMALL
  • HUB-LANDSCAPE-MEDIUM
  • HUB-LANDSCAPE-LARGE
  • TV-LANDSCAPE-XLARGE
  • UNKNOWN-VIEWPORT-PROFILE

Copied to clipboard.

This sample code uses the Alexa Skills Kit SDK for Node.js (v2). For a complete working sample that includes this code, see: APL Pager Karaoke sample.

In a handler, access getViewportProfile like this:

const Alexa = require('ask-sdk-core');

//...Other code. 

const viewportProfile = Alexa.getViewportProfile(handlerInput.requestEnvelope);

// returns a ViewportProfile such as HUB-LANDSCAPE-MEDIUM.

Copied to clipboard.

This sample code uses the Alexa Skills Kit SDK for Python. For a complete working sample that includes this code, see: APL Pager Karaoke sample.

In a handler, access get_viewport_profile like this:

from ask_sdk_core.utils import viewport

# other code...

viewport.get_viewport_profile 

# Returns a ViewportProfile such as viewport.ViewportProfile.HUB_LANDSCAPE_MEDIUM

Copied to clipboard.

This sample code uses the Alexa Skills Kit SDK for Java. For a complete working sample that includes this code, see: APL Pager Karaoke sample.

Use the ViewportUtils static class to get viewport information. The following code returns value from the ViewportProfile enumeration.

ViewportProfile viewportProfile = ViewportUtils
    .getViewportProfile(input.getRequestEnvelope());

Service Interface Reference (JSON)

Request Format and Standard Request Types:

Interfaces: