Imagine we need to populate some JavaScript models (e.g. backbone.js models) using a JSON response from a server like the one below:
{
"todo": {
"title": "My todo",
"items": [
{ "body": "first item." },
{ "body": "second item"}
]
}
}
This data lacks type information, so we're unsure which model to populate when we encounter the "todo"
key.
One option is to define a custom standard that links keys in the JSON response object to client-side models, like this:
{
"todo": {
"_type": "Todo",
"title": "My todo",
...
}
}
However, when it comes to lists, things get complicated:
"items": {
"_type": "TodoItem",
"_value": [
{ "body": "first item." },
{ "body": "second item"}
]
}
Before implementing custom rules, some questions arise:
Are there any RESTful guidelines for including client-side type information in response data?
If not, is it advisable to include client-side type information in the response JSON?
Aside from populating models as described, what are other alternatives?
Edit
Although the model type can be obtained from the URL (e.g. /todo
and /user
), the issue with this approach is that initializing N models would require N HTTP requests.
Instead, initial population could come from a single comprehensive tree with just 1 request, but sacrificing the model type information in the URL.