Adapters

How Ember Data Talks to Your Backend

Adapters

An adapter formats requests for your API. JSONAPIAdapter is the default, RESTAdapter handles REST-shaped backends.

4 min read Level 3/5 #ember#ember-data#adapters
What you'll learn
  • Subclass JSONAPIAdapter or RESTAdapter
  • Override host, namespace, and headers
  • Customize a URL with the urlForX hooks

An adapter is the HTTP brain of Ember Data. It decides URLs, methods, headers, and how to send/receive payloads. The default is JSONAPIAdapter.

Application Adapter

Configure shared settings in app/adapters/application.js:

import JSONAPIAdapter from '@ember-data/adapter/json-api';
import { service } from '@ember/service';

export default class ApplicationAdapter extends JSONAPIAdapter {
  @service session;

  host = 'https://api.example.com';
  namespace = 'v1';

  get headers() {
    const token = this.session.token;
    return token ? { Authorization: `Bearer ${token}` } : {};
  }
}

Now every request goes to https://api.example.com/v1/... with the auth header attached.

REST Backends

If your API uses nested objects rather than JSON-API, use RESTAdapter:

import RESTAdapter from '@ember-data/adapter/rest';

export default class ApplicationAdapter extends RESTAdapter {
  host = 'https://api.example.com';
}

Per-Type Override

Need a different URL or behavior for one model? Create app/adapters/post.js:

import ApplicationAdapter from './application';

export default class PostAdapter extends ApplicationAdapter {
  namespace = 'v2/blog';

  urlForFindAll() {
    return `${this.host}/feed`;
  }
}

Common Hooks

  • urlForFindRecord(id, type) — single resource URL
  • urlForFindAll(type) — collection URL
  • urlForQuery(query, type) — query URL
  • urlForCreateRecord / urlForUpdateRecord / urlForDeleteRecord
  • pathForType(type) — pluralization rules

Override only what you need. Defaults are sensible for JSON-API.

Serializers →