Jonathan Scion
Jonathan Scion

Reputation: 111

Express: defining REST API with sub-resources?

I implemented a REST API via Express. I got a list of suppliers, and for each one list of inventory. the URL went: /Supplier/Inventory{supplierId} (e.g http://MyServer/Supplier/Inventory/237 to get inventory list of supplier 237)

So... pretty standard stuff: in my server.js I use: (and I simply here but you guys get the idea)

const routeInventory = require('./routes/Inventory');
...
app.use('/api/Supplier/Inventory', routeInventory);

and in routes file:

outer.route('//:id').get(ShowInventory); 

and the function would be something like:

exports. ShowInventory=  (req, res, next) => { 
    const iSupplierId=req.params.id;
    console.log('ShowInventory for SupplierId:' + iSupplierId);
...
}

very simple. req.params.id gives me the param I need from the URL. So far so good. But! somebody here insists that since Inventory is a sub-entity of supplier, the URL should be:

/Supplier/{supplierId}/Inventory

so two questions:

  1. Are they correct? is that the standard?
  2. no matter how much I play with the express code, I can't get the {supplierId} parameter when its in the middle of the URL... how is that done?

Thanks Much

Upvotes: 0

Views: 452

Answers (1)

Anatoly
Anatoly

Reputation: 22768

Yes, if you request subresources of a certain resource then you should indicate an id of a resource and only after that indicate subresource name:

/supplier/{supplierId}/inventory

As of routing this can be achived like this:

router.get('/supplier/:supplierId/inventory', ShowInventory)

that way you can access supplierId like this:

const supplierId = req.params.supplierId

Upvotes: 1

Related Questions