Best practices to handle with API nested data

My user will send something like this to my endpoint:

{
  "user": {
    "name": "John",
    "age": 24,
    "address": {
      "street": "Another street",
      "number": 543
    }
  }
}

Then, I need to:

  • Create a row on user’s table
  • Create a row on address’ table
  • Return the user with the address nested, basically in the same way above
{
  "data": {
    "id": 10,
    "name": "John",
    "age": 24,
    "address": {
      "id": 45,
      "street": "Another street",
      "number": 543
    }
  }
}

Some questions:

  1. How is the best way to get this from controller’s params and create the record? Just accessing params.address and calling Address.create_address?

  2. How can I get this from the database and return back to the user? In the nested format above

You can actually do something easier with Ecto.

Checking out Ecto.Changeset.cast_assoc/3 is a good start

2 Likes