June 17, 2024

Express Route Parameters - Creating Dynamic URL

A very common scenario while creating REST APIs is to send user input as a part of URL means creating a dynamic URL in your express application. For example, user wants to search a user by ID and userID is passed as part of the URL (Like this- http://ROOT_URL/api/user/1, here 1 is the userId). In this post, you'll learn how to create dynamic routes in Express.js application using route parameters and how to retrieve route parameters.

Route parameters in Express.js

Route parameters act as a placeholder in route definitions and you can create them by using colon (:) which is followed by a meaningful name. For example, if you want to pass userId as part of the URL and you want it to be a dynamic URL then route definition for the same can be defined as-

app.get('/api/users/:userId', (req, res) => {
  const userId = req.params.userId;
  // Logic for finding the user with the passed userId
});

In the route definition '/api/users/:userId', :userId is the route parameter which acts as a placeholder for any passed userId.

If user makes a get request with http://ROOT_URL/api/users/1 then userId parameter will have the value 1.

If user makes a get request with http://ROOT_URL/api/users/112 then userId parameter will have the value 112.

Passing multiple route parameters

There can be multiple route parameters in a route definition.

app.get('api/authors/:authorId/posts/:postId', (req, res) => {
  const authorId = req.params.authorId;
  const postId  = req.params.postId;
  ...
  ...
})

If user makes a get request with http://ROOT_URL/api/authors/3/posts/127 then authorId will have the value 3 and postId will have the value 127.

Retrieving Route parameters

The values passed for the route parameters are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.

For example, if the route definition is- 'api/authors/:authorId/posts/:postId' and user makes a get request with http://ROOT_URL/api/authors/3/posts/127 then req.params object would look like as given below-

req.params: { "authorId ": "3", "postId": "127" }

Route parameters Express.js example

This example shows the use of route parameter in Express.js by having a dynamic URL where the userId part is dynamic. Application should search for the user with the passed userId and send back user data as response.

To keep it simple user data is hardcoded in a file.

data\userdata.js

const users = [
    { id: 1, name: 'Anil' },
    { id: 2, name: 'Stevens' },
    { id: 3, name: 'Roberto' },
    { id: 4, name: 'Preeti' }
]

module.exports = users;

Route definitions are created in a separate file using Express.router() to keep routing separate.

routes\users.js

const express = require('express');
const router = express.Router();

const users = require('../data/userdata');

router.get('/', function(req, res, next) {
  res.send('Visit /api/users/:userId to get user data');
});

router.get('/api/users/:userId', (req, res) => {
  console.log(req.params);
  const userId = parseInt(req.params.userId);
  console.log(users);
  const user = users.find(user => user.id === userId);
  if (!user) {
    return res.status(404).send('User not found')
  }
  res.json(JSON.stringify(user));
});

module.exports = router;

As you can see route parameter 'userId' is used in this route definition- '/api/users/:userId'. So userId acts as a placeholder which is replaced by the actual userId.

Route parameters are of type string by default so it should be converted to an integer, that's why parseInt() function is used.

const userId = parseInt(req.params.userId);

Once the userId is retrieved, find() method of the array is used to find the user with the matching id, if found then the user data is sent as JSON data. If user data is not found then status code '404' is sent with a custom message.

Finally, the app.js file which uses the router definition.

const express = require('express');
const app = express();

const port = 3000;

const usersRouter = require('./routes/users');
app.use(usersRouter);


app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

module.exports = app;

After running the app if you access URL- http://localhost:3000/api/users/4 you will get the user data for the user with id as 4.

{"id":4,"name":"Preeti"}

If you access - http://localhost:3000/api/users/2

{"id":2,"name":"Stevens"}

If you access- http://localhost:3000/api/users/10 (userId which doesn't exist)

User not found

If you access root URL- http://localhost:3000/

Visit /api/users/:userId to get user data

It is because of the following route definition in routes\users.js

router.get('/', function(req, res, next) {
  res.send('Visit /api/users/:userId to get user data');
});

That's all for the topic Express Route Parameters - Creating Dynamic URL. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment