API Endpoints and same origin policy

Hi Alex,

You can return JSONP from endpoints created with a SmartApp or device type (see our Web Services Developer’s Guide for the basics). The trick is to set the response’s content type to something other than JSON (the default). For example, adding the following sections to a SmartApp will define an endpoint that will return a JSONP response that calls the JavaScript function specified in the callback parameter:

preferences {
    section("Title") {
        input "switches", "capability.switch", title: "Lights & Switches", multiple: true
    }
}

mappings {
  path("/switches") {
    action: [
      GET: "listSwitches"
    ]
  }
}

def listSwitches() {
    render contentType: "application/javascript", data: "${params.callback}(${switches.collect{[id: it.id, name: it.displayName, status: it.currentValue('switch')]}.encodeAsJSON()})"
}

When called with callback=parseResponse it returns:

parseReponse([{"id":"8b32b68b-1234-44d8-a493-4402acabc372","name":"Table Lamp","status":"on"},{"id":"a2af0bd4-4567-4f2f-93b0-1e0bcd7f53c4","name":"Kitchen Ceiling","status":"off"}])

We currently don’t support setting response headers, so CORS support is not currently possible, but we will consider adding that ability in an upcoming release.

3 Likes