Dependent resources

I see lot of examples with independent resources in the spec. Where we can add each resource independently and there form a relationship if needed.

But what happens with dependant resource, say:

  1. Resource A has a one to many relationship with Resource B.
  2. Resource B cannot exist without a relationship to A, meaning B is not independent and can never be accessed without A.
  3. Hence, When creating Resource A we should have the ability to create Resource A, an array of Resource B and their relation together.

How is this possible?

This is handled at the application level.

Some ideas on how this could be handled:

  • When A is created, the server automatically creates the necessary Bs.
  • When creating B without providing an ID for A, return an error.
  • Allow the client to create Bs before creating an A.

If that is not clear, can you provide us with a real world example?

@maark Thank you for the response. Let me give you an example, I’m considering. Consider two resources,

  1. Load - Parent entity
  2. Stop - A load has (to be delivered to) multiple stops (one to many). Hence, all stops are tied to a load (reference)

Assume a sort of supply chain problem wherein a load has to be delivered to multiple stops along a route. Hence, Load Resource has information like reference numbers which are used to find this load, whereas the stop Resource has address information like street, area, state, country etc. and every stop is tied to a load.

Thus from your given solutions.

When A is created, the server automatically creates the necessary Bs.

I don’t think this is possible as the stop level information has to be sent along with the load information. Hence, stops cannot be automatically created.

When creating B without providing an ID for A, return an error.

This is possible but will need two calls. First to create a Load and then to create all its stops. Is this the best way for dealing with this problem?

Allow the client to create Bs before creating an A.

I cannot allow to create stops before creating a load as then, there can be failure scenarios, like:

  • If creating stop(s) succeed, but creation of load failed, I cannot rollback directly as they are separate API calls.

  • Also, it may not be possible to cleanup these dead stops, which no reference to a load. I will need need to use the stop IDs (primary key) returned from the first API call (to create stops) and then use it delete those created stops if load creation failed. But this adds unnecessary complexity to the code.

With this in mind, can you possible me an example (if possible) wherein:

  1. There is only API call to create a load and its stops.
  2. A sample jsonapi create request body for the best approach you suggest.