Search code examples
restapi-design

Should I return id of associated entity or whole entity


OK, lets assume we have two entities: Profile, consisting of id, name and ~10 irrelevant fields, and Post, consisting of text, title, and it's author (Profile). Also, there is resource /feed that returns feed containing posts from different profiles.

So I have two options:

  1. Send full Profile entity in author
  2. Send author's id (there is a way to request Profiles separately)

Which way is faster (in terms on using it on front end) and more convenient (RESTy, if you like).


Solution

  • Obviously just sending the id of Profile is faster because the response length is smaller.

    The important question, however, do you need the full Profile object with each Post? If you want to, for example, print out the name of the author for each Post then sending the full object makes more sense. But if you want to just supply a link to the author with each Post (in the front end) then the id should be enough.

    For other services that query yours for Posts just send the id and have them make a second call if they need. They can always cache the data on their end if needed.

    Try to build your service so that each call/endpoint returns the bare minimum amount of data needed to make sense of the response. This might mean that a Post contains a lean Profile object where only the name is included but all the other, "irrelevant", fields are excluded. But when you query a Profile directly, you get the full object.

    You can also have an optional query parameter where the caller can specify whether they want just the id or the full Profile, this is a strategy Atlassian JIRA uses to preserve bandwidth and improve speed.

    Also check out the hal+json specification, it can give you good ideas about how to design a more usable and transparent REST service.

    MOST IMPORTANT! Your endpoints should only return data that the outside world can actually use and make sense of. So that means if Profile has a field/fields which values are only used in your back-end (like, for example, the user's password) then you should never leak those out.