Using Ember.js to Receive JSON API in Server Response from a Post Request

10,016

I can’t speak authoritatively to ember-data (though I know enough to assert that it certainly supports the HTTP POST verb), except to quote the docs:

Without any configuration, Ember Data can load and save records and their relationships served via a RESTful JSON API, provided it follows certain conventions.

If you need to integrate your Ember.js app with existing JSON APIs that do not follow strong conventions, Ember Data is designed to be easily configurable to work with whatever data your server returns.

See http://emberjs.com/guides/models

The 'certain conventions' that Ember Data refers to above is a bit of a moving target, but the Ember team is close to codifying that definitively (see jsonapi.org).

Also from that doc:

For simple applications, you can get by using jQuery to load JSON data from a server, then use those JSON objects as models.

I’ll demonstrate how to do just that.

The simplest way to get started is to just use Ember’s included jQuery.ajax() method anywhere in your ember codebase:

App.examplePost = function () {
    return Em.$.ajax('http://example.com/api/serviceXYZ', {
        "type": 'POST', // HTTP method
        "dataType": 'JSON', // type of data expected from the API response
        "data": { // Begin data payload
            "auth": {
                "type" : "basic",
                "password": "xxx",
                "username": "someone"
            },
            "requestId" : 15,
            "method": {
                "name": "getUserAvailabilityAndInfo",
                "params": {
                    "userId" : "000",
                    "peopleOnly" : "1"
                }
            }
        }, // End data payload
        "success": function (data, textStatus, jqXHR) {
            return data;
        },
        "error": function (jqXHR, textStatus, errorThrown) {
            window.console.log(jqXHR);
        }
    });
};

(See the standard jquery ajax() docs for more details on the above.)

Some examples of how to actually use something like the above in your ember app:

The "model hook"

In an appropriate route definition, we would override the default model() method:

App.ExamplePostRoute = Ember.Route.extend({
    model: function (params) {
        return App.examplePost();
    }
});

To see the model hook in action, you'd navigate to the route path that maps to the 'examplePost' route state via its associated URL (e.g., http:/myemberapp.example.com/#/examplePost). Because our ajax call executed by App.examplePost() eventually returns the API data on a fulfilled Promise (see the success() function), the model hook knows to use that response as its model object (and it knows how to do this asynchronously using promises).

A "static object" controller

An even more artificial example would be to override the default setupController() method, also in the route definition.

App.ExamplePostRoute = Ember.Route.extend({
    setupController: function (controller, model) {
        return App.examplePost().then(
            function (data) {
                controller.set(model, data);
            }
        );
    }
});

The setupController route method (which is always called, whether or not you transition to a route state via URL or other transition method) does not know about promises, hence the .then() usage above.

Again, you'd not normally statically load a literal model every time you enter a route state, but it's a way to get started, and with the Chrome Ember Inspector, will help you to prove that in fact this can work! Also, jquery and promises are a complicated subject, and in practice if you rolled your own client API code, you'd want to cast jquery's promise object into a standard promise object (see promises.org) via Ember.Deferred.promise(), for example. This is beyond the scope of this question, but FYI for your near-future explorations.

Share:
10,016
Admin
Author by

Admin

Updated on June 07, 2022

Comments

  • Admin
    Admin almost 2 years

    I have an API that I interface with by sending a JSON object in the body of a post request. In return, upon successful authorization the server will respond with a JSON API feed in the body of its post response.

    How can I use Ember.js to receive the payload returned from the server as a result of sending the JSON request? I see that Ember Data, and Ember-model allows for the use of headers, but it doesnt look like theres the ability to send a POST body.

    Here's an example of the JSON I need to send the server in order to receive the JSON API back in the post response.

    {
        "auth": {
            "type" : "basic",
            "password": "xxx",
            "username": "someone"
        },
        "requestId" : 15,
        "method": {
            "name": "getUserAvailabilityAndInfo",
            "params": {
                "userId" : "000",
                "peopleOnly" : "1"
            }
        }
    }