Search code examples
apiweb-servicesresthateoas

Make efficient REST-API calls with HATEOAS


I think I basically understand what HATEOAS is and why you should use it. However, I have some problems with applying this to a real world scenario.

For example:

I would like to display a list of appointments in my client application. An appointment consists of a date, a location and a person. All of this information should be displayed in a table.

My API's response currently looks something like this:

{
  "id": 1,
  "date": "2020-01-01",
  "location": {
    "name": "my office",
    "address": "my street 22"
  },
  "person": {
    "name": "john",
  } 
},   
{
  "id": 2,
  "date": "2020-01-22",
  "location": {
    "name": "your office",
    "address": "your street 30"
  },
  "person": {
    "name": "peter",
  } ​
}

Each appointment object therefore also contains all related objects. This makes fetching the data from the REST API efficient from my point of view, since I only need one API call. For example:

api.com/appointments

With HATEOAS the API response would probably look something like this:

{
  "id": 1,
  "date": "2020-01-01",
  "location": {
    "url": "api.com/location/{id}",
  },
  "person": {
    "url": "api.com/person/{id}",
  } 
},    
{
  "id": 2,
  "date": "2020-01-22",
  "location": {
    "url": "api.com/location/{id}",
  },
  "person": {
    "url": "api.com/person/{id}",
  } ​
}

I would have to get the related objects through additional API calls.

Let us now assume the following:

I would like to display a list of 100 appointments. Each appointment is assigned to a different person and a different location. So I would need an API call to get all appointments, another 100 API calls to get all locations and another 100 API calls to get all person. That is a total of 202 API calls.

That doesn't sound very efficient to me. Do I have a mistake here or how would HATEOAS work in such a scenario?


Solution

  • You confuse REST with a database. You can expand nested resources if that's what your clients want to. HATEOAS is more about adding useful operations to your resources, so you can search, read, paginate, modify, create, delete them if you want to. As of the REST API, you should look at it as if it was a webpage. If you want to see all the appointments in a table along with the edit or delete buttons, then you send back a view model for that table along with the links for edit or delete. The REST client normally runs on server side and the application that uses it is a consumer of the REST service. So the REST service is normally not in direct contact with the user and the REST client does not run in the browser though it can be used this way too with single page JS applications, but it was not designed for this usage.