Search code examples
restrestful-architecturehateoas

REST API Design: Where to create Resource that depends from other resource?


If I have two resources where one is created from the other, where should I put the creation endpoint to?

Example:

I have two resources, A and B and I want to create a B.

B is a simple class which references an A and the user who created it, like this

public class B {
    private A a;
    private User user;
}

The user information is send implicitly with the HTTP request, so I dont need any params for that.

Solution 1:

Send a POST without any arguments to /A/123/B and return B. This means the Controller for A is responsible for creating B. Feels strange.

Solution 2:

Send a POST with id 123 to /B. This means I have to check in the Controller for B if an A with id 123 exists. Feels also strange.

What are the pros and cons for both solutions? Am I overthinking the API design?


Solution

  • You need to be clear about dependency.

    Does A being composed of B? In other word does B exist out of A scope?

    1. If the answer is yes, B can be alive without A, it is better to have a separate resources:

      POST ./B
      

    You should avoid resource being place at different location path. Some may argue that REST does not force you to have a single endpoint for one resources but keeping consistency cross different endpoint is not that obvious. What would happen to B if you send a DELETE ./A/{id} ?

    1. If the response is no, meaning that B could not exist unless A exist, then it is better to have B as a sub-resource.

      POST ./A/{id}/B
      

    Speaking of controller, there is nothing that force you from managing B from an other controller. The whole point of REST is that call are not address to the controller but to the resource. Resources that you are creating are independent from the controller.