Search code examples
json-api

JSON API V1 Creating Nested Resources


I am implementing a JSON API V1 compliant API using Grape API that uses AR as the ORM. I am a little confused on the format to create nested resources / relationships. It looks like we need to create one resource at a time and can link to exisitng resources. But we can't lets say create records for a has many relationship int he same request.

My situation: There is the Donation modal. It has many Splits. A split belong to a Fund. I need to create a donation with multiple splits.

Question: How can I structure the API according to the JSON:API recommendations?

Going through the documentation few times, I am thinking I can't make the donation in one API call and will have to create each resource separately and may be run a final commit to to trigger the donation.

Step 1: Create the donation - assume returns ID 100

POST /api/v1/donations

{ type: "donation", data: { comments: "abc" } }

Step 2: Create Split 1

POST /api/v1/splits

{
  type: "split",
  data: { amount: 100_00 },
  relationships: {
    data: [{ type: "fund", id: 5 }, { type: "donation", id: 100 }]
  }
}

Finally: trigger the donation with some thing like

PATCH /api/v1/donations/100

{
  type: "donation"
  data: { 
    state: "process"
  }
}

Is there a way to create it in one request?


Solution

  • JSON:API specification does not support creating, updating or deleting multiple resources in one request in v1.0, which is the current stable version.

    The upcoming v1.1 is planned to support Extensions, which allow to extend the base specification. There is a proposal of a Atomic Operations extension provided by one of the maintainers of the specification. It's planned to be released with v1.1 as official extension.