My backend manages one entity (EntityA) containing a second one that it stores as an embedded document (EntityB).
What is the best approach when it comes to design a REST API for consuming EntityA?
Let's we have an endpoint like
/api/entities-a/:id
that returns resources of type EntityA.
What should be contained inside the JSON (for example) returned by the backend? The embedded EntityB or its id (the hyperlink)?
First, in terms of API design how things are stored in your persistence layer shouldn't be a concern in terms of API design. Your data model isn't your object model, your object model isn't your API model.
So to generalize the question, you have some entity that is strongly related to another entity - the strength of that relation being indicated by the fact that you store one embedded in the other.
How to present that via the API really depends on your API client. Is your client interested in both entities all the time? If so, why model it as two entities when the client would be better off to consider it as one? Whatever layer transforms your data into an API response can just transform both entities into a single API resource representation.
Does your client only care about the related entity some of the time? If so then model it as a single entity with a link to the related entity. That allows the client to fetch additional data as needed.
If you use a simple hypermedia format like HAL, you could also leverage _embedded
data to provide both entities when that's advantageous to the client. But if it's always advantageous to the client just model your API that way regardless of how the data is persisted, and give the client a single entity.