How to match up a resource present in the relationship/included key?

I have a simple one-to-many relationship between User and Post. I’d like to leave the option when retrieving a post from /api/v1/posts to include the user data. The way I understand this would be done is with /api/v1/posts?include=user.

I originally thought that I could just include the User resource inside of the relationships key, but realized it has to go in the included key, and a relationship must be present for it, right? So would this be the appropriate response to an api call like /api/v1/posts?include=user?

{
  "data": {
    "id": "1",
    "type": "posts",
    "attributes": {
      "body": "Foo body"
    },
    "relationships": {
      "user": {
        "data": {
          "id": "1",
          "type": "users"
        },
      }
    }
  },
  "included": [
    {
      "id": "1",
      "type": "users",
      "attributes": {
        "name": "John Doe"
      }
    }
  ]
}

How do people usually get the data from included if it’s an array? I’m assuming the relationship object needs to be mapped to the included object somehow.

Am I following correctly?

This looks good to me.

So before when I was incorrectly putting the user data inside of the relationships key I was getting the name like response.data.relationships.user.data.attributes.name. What would be the way to grab the user’s name from the included array?

To answer my own question, it looks like https://www.npmjs.com/package/json-api-merge will do the trick!

There are a number of roughly equivalent libraries available in several languages; it’s just the usual matter of what makes the most sense in your application & environment.

I looked at a number of the Node offerings, and wasn’t particularly impressed with them, but I’m not a Node or JS developer.

I’m glad you found something that works for you.