This question is related to a simillar one posted on RESTful design: when to use sub-resources? but it doesnt mention this case.
I have this example
/cars/{carid}
{
"id": 1,
"brand": "something"
"engine":
{
"horse_power": 100,
"type": "hybrid"
}
}
What would be a proper reasoning that could help me decide if this example should be split into a sub-resource to look like this
/cars/{carid}
{
"id": 1,
"brand": "something"
}
/cars/{carid}/engine
"engine":
{
"horse_power": 100,
"type": "hybrid"
}
Maybe splitting the main resource into multiple sub-resources makes sense if the main resource is a complex entity with many arrays and other related entities.
However, if you are concerned about performance issues, bear in mind that premature optimization is the root of all evil. You shouldn't optimize until you have a performance problem and you have proven that the performance problem comes from sending a large representation of the resources.
For the situation mentioned in the question, supporting a sub-resource like /cars/{id}/engine
could be useful when replacing the whole engine of the car, as following:
PUT /cars/1/engine HTTP/1.1
Host: example.org
Content-Type: application/json
{
"horse_power" : 110,
"type" : "eletric"
}
HTTP/1.1 204 No Content
When requesting /cars/1
, a full representation of the car, including the engine, would be returned:
GET /cars/1 HTTP/1.1
Host: example.org
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json
{
"id" : 1,
"brand" : "something",
"engine" : {
"horse_power" : 110,
"type" : "eletric"
}
}
To return a partial representation of the resource, consider the approaches mentioned in this answer.
When requesting /cars/1/engine
, the representation of the engine would be returned:
GET /cars/1/engine HTTP/1.1
Host: example.org
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json
{
"horse_power" : 110,
"type" : "eletric"
}