How to make initial request for nested resource from self describing REST API

By Chathan Driehuys

Background:

I have a single page application that pulls data from a REST API. The API is designed such that the only URL necessary is the API root, ie https://example.com/api which provides URLs for other resources so that the client doesn’t need to have any knowledge of how they are constructed.

API Design

The API has three main classes of data:

  • Module: Top level container
  • Category: A sub-container in a specific module
  • Resource: An item in a category

SPA Design

The app consuming the API has views for listing modules, viewing a particular module’s details, and viewing a particular resource. The way the app works is it keeps all loaded data in a store. This store is persistent until the page is closed/refreshed.

The Problem:

My question is, if the user has navigated to a resource’s detail view (example.com/resources/1/) and then they refresh the page, how do I load that particular resource without knowing its URL for the API?

Potential Solutions:

Hardcode URLs

Hardcoding the URLs would be fairly straightforward since I control both the API and the client, but I would really prefer to stick to a self describing API where the client doesn’t need to know about the URLs.

Recursive Fetch

I could fetch the data recursively. For example, if the user requests a Resource with a particular ID, I could perform the following steps.

  1. Fetch all the modules.
  2. For each module, fetch its categories
  3. Find the category that contains the requested resource and fetch the requested resource’s details.

My concern with this is that I would be making a lot of unnecessary requests. If we have 100 modules but the user is only ever going to view 1 of them, we still make 100 requests to get the categories in each module.

Descriptive URLs

If I nested URLs like example.com/modules/123/categories/456/resources/789/, then I could do 3 simple lookups since I could avoid searching through the received data. The issue with this approach is that the URLs quickly become unwieldy, especially if I also wanted to include a slug for each resource. However, since this approach allows me to avoid hardcoding URLs and avoid making unnecessary network requests, it is currently my preferred option.

Notes:

  • I control both the client application and the API, so I can make changes in either place.
  • I am open to redesigning the API if necessary

Any ideas for how to address this issue would by greatly appreciated.

Source: Stack Overflow

    

Share it with your friends!

    Fatal error: Uncaught Exception: 12: REST API is deprecated for versions v2.1 and higher (12) thrown in /home/content/19/9652219/html/wp-content/plugins/seo-facebook-comments/facebook/base_facebook.php on line 1273