Accessing our API with ember-data
Ember is a client side framework and so when we have data that we want to persist we need a back-end API. We want an API to serve up our blog posts and allow users to view and submit comments.
We could use fixtures or a mock API but some friendly back-end developers have already made a working API for us so let's use that.
Our API is setup at https://ember-101-api.herokuapp.com supporting the following endpoints
Verb | path | Description |
---|---|---|
GET | /blog-posts | List of blog posts |
GET | /blog-posts/:id | Retrieve a post |
PUT | /blog-posts/:id | Update a post |
DELETE | /blog-posts/:id | Delete a post |
GET | /comments | List of blog comments |
POST | /comments | Add a blog comment |
GET | /comments/:id | Retrieve a comment |
PUT | /comments/:id | Update a comment |
DELETE | /comments/:id | Delete a comment |
Our API uses snake_case
in the JSON it sends, the convention for Ruby on Rails APIs. Ember expects everything to be camelCase
, so how can we connect these two nicely? Fortunately, we can use an Ember Data adapter to consumer our API and adapt it to the style we use in Ember.
Application Adapter
We can set up an adapter at the level of an individual model, but since we'll be using the same API for all our models, let's set one up for the entire application:
$ ember generate adapter application
version: 0.2.2
installing
create app/adapters/application.js
installing
create tests/unit/adapters/application-test.js
Let's open up that adapter and see what is there:
import JSONAPIAdapter from 'ember-data/adapters/json-api';
export default JSONAPIAdapter.extend({
});
We're using an Ember Data built-in adapter called the JSONAPIAdapter. Building a custom adapter isn't too hard, but we don't need to because we're going to use the default.
Finally, to point our Ember app at the API we've set up, let's go back to our server, hit CTRL-C
to stop it, and restart ember serve
using the proxy option to point Ember to the API we want to access:
$ ember serve --proxy https://ember-101-api.herokuapp.com
Proxying to https://ember-101-api.herokuapp.com
Livereload server on http://localhost:49152
Serving on http://localhost:4200/