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?

1
  • 2
    What is the resource this API is accessing? Commented Jun 10, 2014 at 1:44

4 Answers 4

13

you need to structure the route like this:

app.get('path/:required/:optional?*, ...)
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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

Comments

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});

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.