API Endpoints and same origin policy

Hi there,

Need a little help here:

I’m trying to hit an endpoint from JavaScript. How can I enable the API to allow cross-domain AJAX calls with JSONP or CORS? Am I missing something?



(20 chars)

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.


Thank you so much @bflorian and @urman!

render is the piece that I was missing. I read over that piece of documentation at some point, but it didn’t stick. I wish there was more emphasis on this function.

I’m exited to continue coding!

1 Like