Search code examples
node.jsjsonrestrestful-url

How can I parse parameters to a RESTful API


I am trying to make a basic RESTful API which works for the most part, but I would like to parse it url parameters such that I can apply multiple filters in one call

I have the following code:

app.get('/api/products/:id',(req, res) => {
  let sql = "SELECT * FROM products WHERE id="+req.params.id;
  let query = conn.query(sql, (err, results) => {
    if(err) throw err;
    res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
  });
});

which I can use to apply one filter when I send a request like this:

localhost/api/products/1

but I would like to get all products with a name and their categories:

IE I would like to send a request like this: localhost/api/products?name=stier&category=hammer I would also like it to accept requests like this localhost/api/products?category=hammer

Is that possible and how can I adapt my code to do that.

Thank you in advance


Solution

  • You can pass query parameters to that endpoint exactly as you mentioned. You can access those parameters using req.query

    for: localhost/api/products?name=stier&category=hammer, req.query will contain:

    {
       name: 'stier',
       category: 'hammer'
    }
    

    For that URL, you'll have to add a route for: /api/products and leave /api/products/:id for fetching a single product.