Designing the relationships between resources in your RESTful API

Article 9 in the series of “ Pragmatic decisions for your RESTful API”, this post talks about designing 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: ?

The author attribute is obviously a relation from the message to its author. But what should it contain ?

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:

If the user representation is large, there will be a lot of data transferred which will not be used by the client

If you decide to display the full resource representation for each of your resources, you can quickly run into the N+1 issue: for example, if your users have a relation to, say, an organization resource, retrieving a list of messages would then show the user resource in the author attribute, and the organization resource in the author.organization attribute, ending up with a huge JSON reply to a simple request to retrieve a list of messages.

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 /messages?

This is the best option of all 3, and the one I recommend you to use.

If you want to read all of the articles of the series “ Pragmatic decisions for your RESTful API”, you can start here. The next article will focus on defining sub-resources in your RESTful API.

This series of articles about Restful API design is also available as an eBook on Amazon, if you need it in a handy format.

Originally published at on April 3, 2018.



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