Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 39 ยท Ember Data and Models

Adapters and Serializers

Connect Ember Data to your own API with adapters (URLs, headers, hosts) and serializers (key names, payload shape, ids), including REST and JSON:API styles, with runnable stand-ins.

Ember Data's defaults assume an API that speaks JSON:API with dasherized, plural URLs. Real APIs differ: a different host, an Authorization header, snake_case keys, payloads wrapped in { "post": { ... } }, or uuid instead of id. Instead of reshaping the app, you teach Ember Data about your API in two small classes. The adapter decides how to talk (URLs, methods, headers). The serializer decides how to translate (payload shape and key names).

Real versus stand-in. Adapter and serializer code is real Ember Data, read-only here. The runnable blocks reimplement URL building and payload normalization in plain JavaScript so you can see exactly what these classes do.

Adapters: URLs and headers

An application-wide adapter lives in app/adapters/application.js:

JavaScript
// 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() {
    return this.session.isAuthenticated
      ? { Authorization: `Bearer ${this.session.token}` }
      : {};
  }
}

With that, store.findRecord('post', 1) calls GET https://api.example.com/v1/posts/1 with the header. Settings you will use most:

Setting Purpose
host Server origin (leave empty for same origin).
namespace Path prefix such as api/v1.
headers Extra headers, for example authentication. Declared as a getter so it reads fresh state.
pathForType(type) Maps a model name to a path segment.
buildURL(...) Full control over every URL.

For one model, add app/adapters/post.js; it overrides the application adapter for post only:

JavaScript
export default class PostAdapter extends ApplicationAdapter {
  pathForType() {
    return 'articles'; // post records live at /articles
  }
}

Choose the adapter family that matches your API: JSONAPIAdapter for JSON:API, RESTAdapter for the older Ember REST convention, and a custom class extending either for unusual APIs. Adapters also handle errors: override handleResponse(status, headers, payload) to turn a 401 into a logout, for instance.

JS Stand-in: building URLs like an adapter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Serializers: changing the payload

The serializer sits between the raw JSON and the store. It works in two directions:

  • Normalizing (response): turn the server's JSON into the standard JSON:API document the store understands.
  • Serializing (request): turn a record into the JSON body your server expects.

Suppose your API returns snake_case keys, wraps the result in a root key and calls the id uuid:

JSON
{ "post": { "uuid": "a1", "post_title": "Hello", "created_at": "2026-03-01T09:00:00Z" } }

A RESTSerializer handles the root key; you add the key mapping:

JavaScript
// app/serializers/application.js
import RESTSerializer from '@ember-data/serializer/rest';
import { underscore } from '@ember/string';

export default class ApplicationSerializer extends RESTSerializer {
  primaryKey = 'uuid';

  keyForAttribute(attr) {
    return underscore(attr); // createdAt -> created_at
  }

  keyForRelationship(key) {
    return `${underscore(key)}_id`;
  }
}

When an attribute name differs unpredictably, map it per model:

JavaScript
// app/serializers/post.js
export default class PostSerializer extends ApplicationSerializer {
  attrs = {
    title: 'post_title',
    body: { key: 'content' },
  };
}

For anything else override normalizeResponse (or the finer-grained normalize) and serialize:

JavaScript
normalize(modelClass, resourceHash) {
  // fix the server's quirks, then delegate
  const copy = { ...resourceHash, title: resourceHash.title?.trim() };
  return super.normalize(modelClass, copy);
}

serialize(snapshot, options) {
  const json = super.serialize(snapshot, options);
  delete json.created_at; // the server sets this itself
  return json;
}
JS Stand-in: normalize and serialize

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Which side does what?

sequenceDiagram
  participant C as Component
  participant S as Store
  participant A as Adapter
  participant Z as Serializer
  participant API as Server
  C->>S: record.save()
  S->>Z: serialize(snapshot)
  Z-->>S: JSON body
  S->>A: updateRecord(...)
  A->>API: PATCH /v1/posts/1 + headers
  API-->>A: JSON response
  A->>Z: normalizeResponse
  Z-->>S: standard document
  S-->>C: updated record

The adapter owns HTTP. The serializer owns the payload shape.

A handy rule: if the problem is in the URL, verb, host or headers, change the adapter. If it is in the JSON keys or structure, change the serializer.

Working without conventions: a plain fetch

You do not have to bend Ember Data to a very unusual API. A service that calls fetch and returns plain objects (or builds records with store.push) is perfectly acceptable:

JavaScript
// app/services/weather.js
export default class WeatherService extends Service {
  async forecast(city) {
    const response = await fetch(`/api/weather?city=${encodeURIComponent(city)}`);
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return response.json();
  }
}

Reserve Ember Data for the entities it models well (see Services in Ember for the service pattern).

Mock servers during development

While the real API is unfinished, tools such as Mirage (ember-cli-mirage) or MSW intercept requests inside the browser and answer with fake data defined in code, and the same fakes can be used in tests. The adapter and serializer see ordinary HTTP responses, so nothing else in the app changes.

Common mistakes

  • Editing the model to match the API. Keep models in your app's vocabulary; do the translation in the serializer.
  • Hard-coding a token in headers. Read it from a service so it stays current after login and logout.
  • Forgetting to match the adapter and serializer family. A RESTAdapter with a JSONAPISerializer mismatches payload shapes.
  • Changing application-wide classes for a one-model quirk. Put per-model differences in app/adapters/<model>.js.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where would you set an Authorization header for all requests?

    Headers, host and namespace are the adapter's responsibility.
  2. 2. Your API returns created_at but your model has createdAt. What should handle it?

    Key names and payload shape are the serializer's job.
  3. 3. How do you make post records use /articles in URLs?

    pathForType maps a model name to the URL segment used by the adapter.
  4. 4. When is it reasonable to skip Ember Data for a request?

    A service with fetch is fine for one-off calls; Ember Data shines for shared entities and relationships.

Summary

  • Adapters decide URLs, verbs, hosts and headers; serializers decide payload shape and key names.
  • Set app-wide behavior in application.js and override per model in adapters/<model>.js.
  • Use primaryKey, keyForAttribute and attrs for the common mismatches, and normalize or serialize for the rest.
  • Mock servers let you develop and test before the API exists.
  • A plain fetch in a service is a legitimate alternative for unusual calls.

Next: Querying and Caching