0

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?

Lucas Sampaio
  • 1,568
  • 2
  • 18
  • 36

1 Answers1

0

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.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • So, it's ok to bundle related data in a single response, if all are related, right? I don't want to force my API clients to make several requests too, though. – Lucas Sampaio Nov 21 '12 at 18:20
  • 1
    _"So, it's ok to bundle related data in a single response, if all are related, right?"_ You're designing the API. Whatever you allow is "okay" by definition. Doing this seems reasonable, though. It's exactly what my answer suggests. _"I don't want to force my API clients to make several requests too, though." – I don't see what you're getting at. Bundling related data in a single response _reduces_ the number of requests clients would have to make. – Matt Ball Nov 21 '12 at 18:24