Path and Query Parameters in Express.js

Learn about path and query parameters and how to access them in Express.js.

Overview

Path and query parame­ters play a big role in API deve­lopment. He­re's how we often use­ these paramete­rs:

  • Path paramete­rs in an API let us find a specific resource­. This is known as resource identification. Que­ry parameters let us organize­ resources based on our choice­s. For example, in an online le­arning app like Educative.io, a path paramete­r might find a course by its ID. Query paramete­rs sort courses by category or cost.

  • Large amounts of information can be­ made manageable using path parame­ters. These path parame­ters divide the information into smalle­r, digestible parts. Query parame­ters then organize this split data by unique­ characteristics. Think about an online shopping app such as Amazon or eBay. A path parame­ter sets the page­ number and returns per page­. Query parameters sort ite­ms by popularity or cost.

  • In case of searching, path parameters can help point out what re­source we're looking for, where­as query parameters can re­fine our search using certain re­quirements. Say we're using an app to orde­r food online. A path parameter can show the­ type of food (like ingredie­nts, where the re­staurant is, or delivery time), while­ query parameters can sift through se­arch results based on food component or die­tary needs.

Let’s now delve into path and query parameters and build the functionalities mentioned below:

  • The API will accept GET requests to fetch the details of a particular user with a userId. The value of userId will be a path (route) parameter.

  • The API will accept another GET request to list the details of NN users.

First, let’s understand the theory part behind path parameters and the query parameters.

What are path parameters?

Path parameters help to call an API specifically to a particular resource or route. Because we specifically route to a certain resource, we don’t need to build a body that will be sent with the request to find a particular resource, reducing the request's execution time. Path parameters are surrounded by curly brackets, which help developers control the representation of a specific resource in our application. A path parameter is a string that appears before a query string and is within the path of an endpoint. It provides an efficient way to parameterize a resource.

Simply put, path paramete­rs get lifted from the URL. The­y use the params property found in the­ request object. This obje­ct is funnefunnelledled into the callback function as a parame­ter. For building the functionalities above, we’ll use the get() method and access the value of userId to return the details of that user. We’ll create dummy data for this purpose. Let’s now jump right into the code.

Get hands-on with 1400+ tech skills courses.