Let's say I have two entities
public class Container {
UUID id;
String name;
@OneToMany
List<Element> elements
}
and
public class Element {
UUID id;
String name;
@ManyToOne
Container container;
}
What would be the best approach to designing a REST API for these entities? For example should Elements be added to the container via a Container endpoint or via Element endpoint? Or when creating a new container should the Elements be created with the Container in a single request or in a separate request and subsequently added to the Container in another request? Should I have an endpoint to create multiple elements at once?
It depends on your business need and use case.
If elements are known and should be created on container creation, then it's better to include elements creation at the same API request. You can also pass it as an empty array if no elements to be created for some containers so that you make your API dynamic for both cases. Of course in this case you will also need an element creation API if there is a possibility that elements will not be all added at the time of container creation.
However, if always elements will be added later then create create 2 separate APIs without including elements in the container creation API.
And for the elements creation API it's best practice to always make it an array, and in case you will add only one element, then the array will contain only one item.