JuliusvM
JuliusvM

Reputation: 335

Node.js same uri but different parameters

I'm doing a simple library API with Node.js and express. To fetch a specific book with ISBN or books within a specific genre, I have the following functions:

/api/books/isbn

router.get('/:isbn', function (req, res) 
{
  var isbn = req.params.isbn
})

/api/books/query

router.get('/:genre', function (req, res) 
{
  var genre = req.params.isbn
})

So first of all, this will not work because it will only go to the first function regardless of what the input is. Another thing I tried and that worked, was to make only one function that extracts the query parameters:

router.get('/', function (req, res) 
{
  var isbn = req.query.isbn
  var genre = req.query.genre
})

Using this approach I could get the different values by doing calls like /api/books?genre=Adventure or /api/books?isbn=1231230912

But I feel it would make more sense to do it the first way, i.e /api/books/adventure or /api/books/isbn.

So, which way is the 'right' way? And if it's the first one, how can I design the functions so that they can extract the right values?

Upvotes: 2

Views: 170

Answers (3)

Ishwar Patil
Ishwar Patil

Reputation: 1736

I think the second approach you tried should also be ok.

However, if you asked me to do this. I will create below apis:

  1. /api/books/genre/Adventure
  2. /api/books/isbn/1231230912

This helps to have clear distinctions between the apis and makes them maintainable and readable for future.

To save the time of writing 2 route handlers, you can write only one route handler function and pass either genre or isbn as parameter.

Upvotes: 2

Jeremy M.
Jeremy M.

Reputation: 1164

You could do like so :

// /api/

router.get('/isbn/:isbn', function (req, res) 
{
  var isbn = req.params.isbn
})

// /api/books/query

router.get('/genre/:genre', function (req, res) 
{
  var genre = req.params.genre
})

This will work and this is the most used format.

And if you wan't to have only one uri then do like so :

// /api/books/isbn

router.get('/', function (req, res) 
{
    var isbn = req.query.isbn
    var genre = req.query.genre
    if (isbn)
        res.redirect('/isbn/' + isbn);
    else if (genre)
        res.redirect('/genre/' + genre);
})

Upvotes: 1

Laurens Mäkel
Laurens Mäkel

Reputation: 815

Try using one route, and by trying to parse the parameter to a number you can check if it's an isbn or genre.

If NaN then genre else isbn

Upvotes: 1

Related Questions