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.
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
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.
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?
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.
I could fetch the data recursively. For example, if the user requests a
Resource with a particular ID, I could perform the following steps.
- Fetch all the modules.
- For each module, fetch its categories
- 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.
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.
- 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