Always Use a Top Level Key

Learn why we should always use a top-level key.

We'll cover the following

The example code we’ve seen thus far looks like this:

render json: { widget: widget }

Why didn’t we write only render json: widget?

Doing that would result in a JSON object like so:

{
  "id": 1234,
  "name": "Stembolt",
  "price_cents": 12345
}

There are two minor problems with this as the way our API renders JSON.

  • The first is that we cannot look at this JSON and know what it is without knowing what produced it. That’s not a major issue, but when debugging, it’s really nice to have more explicit context if it’s not too much hassle to provide.

  • The second problem is if we end up needing to include metadata like page numbers, related links, or other stuff that’s particular to our app and not something that should go into an HTTP header. In that case, we’d need to merge the object’s keys and values with those of our metadata. This will be confusing and potentially cause conflicts.

A better solution is to include a top-level key for the object that contains the object’s data. Our code does that by rendering { widget: widget }, which produces this:

Get hands-on with 1200+ tech skills courses.