How to make parameters Optional in node JS rest API
Asked Answered
F

4

5

We need to Expose REST endpoint. There are three parameters, how to make those optional. Requirement is it should work with any one of those parameters.

e.g. http://server:port/v1/api/test-api/userId/UnameName/userEmail

app.get('v1/api/test-api/:userId/:userName/:userEmail', function(req, res){

});

When we call by passing all three parameters it works fine. But we want to make it work by passing only userId or any of these three parameters. When we pass less parameters its giving error Cannot GET /v1/api/test-api/test5/123

How to make parameters optional while exposing endpoint?

Floria answered 10/6, 2014 at 0:35 Comment(1)
What is the resource this API is accessing?Leven
U
13

you need to structure the route like this:

app.get('path/:required/:optional?*, ...)
Unleavened answered 10/6, 2014 at 0:58 Comment(0)
L
8

A better solution would be to use GET parameters, e.g. a call to

http://server:port/v1/api/test-api?userId=123&userName=SomeKittens&userEmail=kittens%40example.com

You can then define your routes like:

app.get('v1/api/test-api', function(req, res){
  var userName = req.query.userName;
  var userEmail = req.query.userEmail;
  var userId = req.query.userId;

  // Do stuff
});

Don't forget to include body-parser (example)

Leven answered 10/6, 2014 at 1:32 Comment(0)
D
1

Trying to add more clarity to @thebiglebowsy's answer, you could use:

required -> required1/required2/...

optional -> ?optional/?optional2/..

But, my advice is to generate a route per every posibility:

v1/api/test-api/:userId/

v1/api/test-api/:userId/:userName

v1/api/test-api/:userId/:userName/:userEmail

I had several issues using with optional routes

Duffer answered 23/3, 2015 at 7:20 Comment(0)
C
1

Alternate way, you can check whether what you have received in your input request parameters and put validations or capture values accordingly..

app.post('/v1/api/test-api', function(req, res) {
    var parameters = [];
    if(req.body.userName !== undefined) {
         //DO SOMEHTING
         parameters.push({username: req.body.userName});
    }
    if(req.body.userId !== undefined) {
        //DO SOMEHTING

       parameters.push({userId: req.body.userId});
   }
   if(req.body.userEmail !== undefined) {
      //DO SOMEHTING
      parameters.push({userEmail: req.body.userEmail});
   }

   res.json({receivedParameters: parameters});

});
Capapie answered 16/9, 2015 at 10:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.