Reputation: 452
To pass single parameters in the URL I use the following in Postman:
http://localhost:3000/api/prices/:shopId
That works!
Now, What I want to do is, to replace the shopId with List of shopIds.
Do have any ideas about how can I make this happen?
Pseudo Code:
URL for shopId = 1: http://localhost:3000/api/prices/1
URL for shopId = 2: http://localhost:3000/api/prices/2
What should I do to get the both shopId 1 and 2 in single API response?
Upvotes: 5
Views: 8286
Reputation: 1
Adding an alternative answer:
URL: GET http://localhost:3000/api/prices/shopIds?id=1&id=2&id=3&id=4
And then in your express get endpoint:
let ids = req.body.id
However, ids might be a string or a list depending on if there is one or more id in the parameter list. Not sure how to treat this in a good way.
Upvotes: 0
Reputation: 2139
For your requirement, I can think of a couple of alternatives, which I feel are better practices than what you mentioned.
Send it in the body using any of POST
or PUT
.
URL: http://localhost:3000/api/prices/shopIds
Body: { shopIds: [1, 2, 3, 4] }
You can retrieve the IDs like,
const { shopIds } = req.body // shopIds = [1, 2, 3, 4]
or
const shopIds = req.body.shopIds // shopIds = [1, 2, 3, 4]
If you want to use GET
, then use query parameter
URL: POST http://localhost:3000/api/prices/shopIds?ids=1,2,3,4
Here you can retrieve the IDs as a string and then convert them to array,
const ids = req.query.ids.split(','); // ids = [1 ,2, 3, 4]
If you still want to use it the way you mentioned, it's already answered. Use that method!
Hope this helps!
Upvotes: 4
Reputation: 2161
Your best shot is to pass the elements of your array delimited with a character that won't ever be in any of the words (for example, a comma).
Take this snippet for example:
app.get('api/prices/:ids', function(req, res){
var ids = req.params.ids.split(',');
console.log(ids); //['shopId1', 'shopdId2']
})
Endpoint that you reach with a GET request to:
http://localhost:3000/api/prices/shopId1,shopId2
Upvotes: 6