Designing the relationships between resources in your RESTful API

Defining your relations: embed your fields based on query parameters

This is a tricky question. Should you display your relations directly in your resources or not ? Let’s take for example a list of messages shown in a RESTful API in the following way:

{
id: "123456",
subject: "Message 1",
message: "This is my first message",
author: ?
}

Option 1: only ID

The author attribute would only contain the ID of the author. The advantage of this is that it is very easy to implement. The big issue with this however, is that if a client wants to display, for example, the list of messages with the names of the authors, he will have to do many HTTP requests: one to retrieve the list of messages, and then one for each author, to retrieve their names based on their IDs.

Option 2: full resource representation

The author attribute could, instead of showing just an ID, show the full author representation. This will allow a client wanting to display the author’s name along with the messages to do it without extra HTTP requests, but with the following drawbacks:

Option 3: embedded fields based on query parameters

This option is basically a way to allow your clients to choose which fields should be , via a query parameter such as embed or expand. For example, to return the list of messages along with their author name, our client would call:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Guillaume Viguier-Just

Guillaume Viguier-Just

Développeur web et passionné de finances personnelles