Is it more beneficial to categorize REST-based modules/controllers by resource or by specific action/feature?

I'm facing a scenario that goes like this:

Endpoint 1: Retrieve all books in the United States owned by John with a GET Request to /country/us/person/john/books

Endpoint 2: Get all books owned by John in every country with a GET Request to /person/john/books

Endpoint 3: Fetch all books across all countries using a GET Request to /country/books

I am planning on creating a rest server using NestJS (although not directly related to this question) which leverages the concept of modules for organizing controllers.

In this context, should I create:

  • A single module named books containing one controller managing three routes. Or,
  • Split it into two modules, namely booksByCountry and booksByPerson

Is there a best practice or recommendation when approaching this situation?

Answer №1

When setting up your API, the approach you take will depend on how you want to structure it in a meaningful way.
Consider your specific use cases and resource access requirements. For example, if you need to retrieve books by person and/or country, here are a couple of options:

Initial Approach:

API1: Retrieve all books in the US owned by John:
Make a GET Request to

/books/person/{personName}/country/{countryName}

API2: Get all books owned by John in every country:
Access via a GET Request to /books/person/{personName}

API3: Fetch all books across all countries:
Utilize a GET Request to /books

Alternative Perspective:

API1: Retrieve all books in the US owned by John:
Issue a GET Request to

/persons/{personName}/books?country={countryName}

API2: Get all books owned by John in every country:
Access through a GET Request to

/persons/{personName}/books?country=all
(or simply /persons/{personName}/books without specifying all as a query parameter value)

API3: Fetch all books across all countries:
Retrieve using a GET Request to /books

In Summary:

The choice between these approaches hinges on the semantic clarity of your URIs and how you prefer to manage your path and query parameters. Whether your API is intended for public consumption or internal usage only, ensure that the exposure of your resources is straightforward and logical so that users can easily navigate the documentation and utilize the API.

If this explanation has been helpful, feel free to share your thoughts and insights on this topic!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Javascript to dynamically populate dropdown options based on radio button selection

I am in the process of developing a basic form that allows users to input the frequency of a specific report. Initially, users were only able to enter days of the week. However, due to changes in demand for certain reports, options such as workday and day ...

Top location for Cordova/Phonegap events in AngularJS

Currently, I am working on an AngularJS Cordova app and so far everything is progressing smoothly. My next objective is to integrate Cordova plugins into the application, specifically the Cordova Connect plugin, which will allow me to monitor network conne ...

Issue with jQuery AJAX error callback not triggering upon encountering an error

I'm currently facing an issue with implementing the management of an HTTP 413: Request entity too large error from my server. I've made the following attempt to address it: $.ajax({ url: "submit.php", data: { "data": POSTData ...

Ways to verify if a string is a number without using isNaN and with specified criteria

I am trying to determine if a string represents a valid number without relying on the isNaN function. The reason for this is that I need to be able to accept the ',' character, which isNaN ignores. Additionally, I do not want to allow negative nu ...

A mysterious JavaScript snippet that automatically scrolls down when the webpage is loaded

Recently, I encountered an issue with a mysterious JavaScript script that automatically scrolls down when entering the page (I suspect it's JavaScript). I've tried to investigate using Firebug, examining the code, deleting scripts, and even remov ...

Webpack is unable to locate a specific custom JavaScript file

Currently, we are in the process of transitioning from grunt to webpack for our project. Within our project, we have a JS file named boiler that is used to define the core classes which are frequently accessed. __boiler__.js define(function (require) { ...

Issue encountered with sortable table in list.js

Encountering a puzzling error while implementing list.js and tabletop for a sortable table sourced from a Google Doc. The error message reads: "Uncaught TypeError: Cannot read property 'childNodes' of undefined," pinpointing the first line in lis ...

Improving the display of events with fullcalendar using ajax requests

I have integrated the fullcalendar plugin from GitHub into my project. I am looking to implement a feature where I can retrieve more events from multiple server-side URLs through Ajax requests. Currently, the initial event retrieval is functioning proper ...

"Despite being higher in position, the z-index is causing the element to be placed below

I am currently facing an issue with a dropdown menu that I am trying to add to a WordPress site using Visual Composer. The problem arises when I attempt to place the dropdown on top of a parallax section below it. Despite setting the z-index of the paralla ...

What is the significance of receiving an error in Internet Explorer when running the code below?

function checkStepValidity(isValid, dataModel) { if (isValid) { updatedDataModel = mergeObjects(this.updatedDataModel, dataModel); } }, The code above encounters the following error in Internet Explorer / Edge browse ...

Exploring an Array in Javascript derived from a PHP Array

I have a PHP variable named $TillArray that contains an array. I am trying to pass this array to a Javascript function in order to display an Alert message for each item within the array. Below is the code I have been using: <script type="text/javasc ...

unable to use 'await' keyword to delay the code execution until a function finishes

I'm encountering an issue where I need to wait for the result of a local function before proceeding further. Here is the code for the local function: var Messagehome = (req, res) => { user.find().exec(async (err, user) => { if (err) ret ...

Completing a submission on a bootstrap form, using innerHTML and displaying an alert

I am currently having an issue with navigating to the home page after submitting a form in Bootstrap. Although I have successfully implemented an alert message upon submission, the page does not redirect to the home page as expected. Instead, it redirects ...

What are some secure methods for integrating iframes into an Angular 7 project?

Is there a secure method to set the URL for an iframe without bypassing security measures like using this.domsanitizer.bypassSecurityTrustResourceUrl(url)? While this approach may be flagged as a high vulnerability by tools such as Veracode, is there a w ...

What is the best way to define a custom route in react-router-dom?

My goal is to have the URL display "/login" in the address bar when I am on the login page. // App.js <Routes> {isLoggedIn ? ( <Route path="/" element={<Root onLogout={handleLogout} />}> <Route index e ...

Is there a way to identify when a Tween.js animation has completed?

Is there a completed or finished event available when using this code for animating the camera in a scene with tween.js? tween : function (target){ var position = camera.position; var tween = new TWEEN.Tween(p ...

leveraging express.js middleware alongside jwt and express-jwt for secured authentication in express framework

I am encountering an issue while using the express-jwt to create a custom middleware. The error message persists as follows: app.use(expressJwt({ secret: SECRET, algorithms: ['HS256']}).unless({path: ['/login', '/']})); ...

What could be causing my div element to remain stationary despite the movement functions I have implemented?

I am attempting to move my div element by using key presses to adjust the CSS attributes of the HTML elements. However, despite implementing the necessary code, the mover refuses to budge and nothing appears when I inspect the elements or their attributes. ...

Is it possible to incorporate async await with SetState in React?

Is there a way to properly setState when needing async/await data inside it? I know it's not recommended, but I'm struggling with getting data before setting the state. Any suggestions? codesanbox: https://codesandbox.io/s/infallible-mendeleev-6 ...

How to set textboxes as read-only depending on the drop-down choice?

After developing some scripts to automatically populate the data-length and data-width in textboxes based on a dropdown selection, I now face the challenge of making the .width and .length textboxes readonly depending on the selected dropdown option. Is t ...