Using REST API

This section contains some recommendations on consuming third-party REST APIs.

Fetch API

index.html generated by CUBA Studio contains a polyfill for Fetch API because it’s used by CUBA Polymer components.

So, you can easily use fetch in your own code.

src/recipes/ajax/fetch-example.html
<link rel="import" href="../../../bower_components/polymer/polymer-element.html">

<dom-module id="fetch-example">
  <template>

    <!-- Some code here -->

  </template>
  <script>
    class FetchExample extends Polymer.Element {
      static get is() {
        return 'fetch-example';
      }

      connectedCallback() {
        super.connectedCallback();

        fetch('http://www.there-could-be-your-url.com/some-important-resource', {
          method: 'GET',
          headers: {
            accept: 'application/json'
          }
        })
        // 'fetch' returns a promise
          .then(function(response) {
            if (response.status !== 200) {
              // Do something there if a error response came from the server
            }
            // 'json()' returns a promise
            return response.json();
          })
          .then(function(jsonObject) {
            // Do something there with the response.
          });
      }
    }

    customElements.define(FetchExample.is, FetchExample);
  </script>
</dom-module>

Read this article to learn more about Fetch API.

iron-ajax

iron-ajax component is an another convenient option to perform AJAX requests.

src/recipes/ajax/iron-ajax-example.html
<link rel="import" href="../../../bower_components/polymer/polymer-element.html">
<link rel="import" href="../../../bower_components/iron-ajax/iron-ajax.html">

<dom-module id="iron-ajax-example">
  <template>

    <iron-ajax
      auto
      url="http://www.very-important-resources.org/required-resource"
      params='{"company": "Haulmont"}'
      handle-as="json"
      on-response="_onImportantDataLoaded"></iron-ajax>

  </template>
  <script>
    class IronAjaxExample extends Polymer.Element {
      static get is() {
        return 'iron-ajax-example';
      }

      _onImportantDataLoaded(event, request) {
        const response = request.response;
        // Some actions with the response there
      }
    }

    customElements.define(IronAjaxExample.is, IronAjaxExample);
  </script>
</dom-module>