restify optional route parameters restify optional route parameters node.js node.js

restify optional route parameters


You need to add restify.pre.sanitizePath() somewhere near the beginning of your code:

var restify = require('restify');var server = restify.createServer();server.pre(restify.pre.sanitizePath()); // Add this line

For more details, look at this Github Issue. The original paper on ReST indicates the slash has a special meaning, however, ReST is NOT a standard, only a guide. Thus, the use/omission of a slash is a matter of the API designer's preference and the semantics of the API. Consistency is the ONLY thing that matters.

I mocked and tested your setup and this is confirmed to fix your problem as described:

var restify = require('restify');var server = restify.createServer();server.pre(restify.pre.sanitizePath());var users = [  { id: 1, name: 'Sean' },  { id: 2, name: 'Bob' },  { id: 3, name: 'Ana' }]server.get('/users', function (req, res, next) {  console.log(req.query());  res.send(users);});server.get('/users/:id', function (req, res, next) {  var user = users.filter(function (user) {    return user.id === req.params.id;  });  res.send(user);});server.listen(8080, function() {  console.log('%s listening at %s', server.name, server.url);});

HTTP tests:

$ curl localhost:8080/users <- Returns all users$ curl localhost:8080/users/ <- Returns all users$ curl localhost:8080/users/1 <- Returns user with id 1$ curl localhost:8080/users?name=sean <- Logs querystring$ curl localhost:8080/users/?name=sean <- Logs querystring


Restify has added support as of v4+ for optional parameters in requests following the same outline as express:

router.get('/user/:id?', async (req, res, next)=>{    // Do Stuff})

Which means if we were to run a get request to /user/ the above route would still be called.