Say I am building an API with a call that returns a collection of cities, each of which has a relationship to a state. A state has many cities, but a city has only one state.
I can imagine flattening the relationship and obscuring the underlying structure of the data like this,
{ cities : [
{ id: 1,
name: "Los Angeles",
state: "CA" }
]}
Or I can imagine structuring the JSON such that the relationship between cities and states is apparent,
{ cities : [
{ id: 1,
name: "Los Angeles",
state: { id: 1,
name: "CA" }
]}
The consumer of the API, as of now, only ever needs to know the name of the state. He does not need to know its ID or a way to get more information about the state. What are the pros and cons in structuring the JSON in either way?
That depends on the other consumers. Do you have any? Are you planning to?
An API is a machine interface, it is equally easy for the consumer’s developer to use both structures. If the “state” entity is not a compound entity(no usable properties except name), it might me a good idea to show just the name, not a structure with the id.
If there is a possibility that state id might be useful in future, or a possibility that a new property is going to be added to state entity, then you should use the second approach from the start. Changing API in any way breaks the software already written, so changing it will make you support two different versions. Change between approaches 1 and 2 is not backward-compatible.
I would go with approach 2. It is not much more complex than 1 and leaves a possibility to extend state entity.
There is also a third approach. But it is noticeably more complex(and more extendable). Return state id only and create a method for state entity retrieval.