I'm learning how to make a good REST API. So, suppose I have the following models:
Post
has title, body, publish_date
has_many comments, authors
Comment
has author, publish_date
So, if I call GET /post
, to get all posts, how it's comments should be returned? I'm thinking in something like:
{
'post/1': {
'title': 'My first post',
'body': 'a big body',
'publish_date': '20121120',
'comments': 'post/1/comments',
'authors': 'post/1/authors'
},
'post/2': {
'title': 'Another post',
'body': 'a REALLY BIG body',
'publish_date': '20121121',
'comments': 'post/2/comments',
'authors': 'post/2/authors'
}
}
I'm also thinking in put each comments' resources direct in /post
response, like
'comments': {
'post/1/comment/1',
'post/1/comment/2',
'post/1/comment/3'
}
So, what's the best approach?
If each post "owns" its comments, you could simply send the comment data with the post data:
{
'post/1': {
'title': 'My first post',
'body': 'a big body',
'publish_date': '20121120',
'comments': [/* comment data here */],
'authors': 'post/1/authors'
},
'post/2': {
'title': 'Another post',
'body': 'a REALLY BIG body',
'publish_date': '20121121',
'comments': [/* comment data here */],
'authors': 'post/2/authors'
}
}
You might want to do the same with authors. Rule of thumb: as a consumer of your API, I don't want to have to keep making API calls to get all of the relevant data. If response size/time is a concern, at least give me the option to get post-relevant fields; also consider response pagination.