Path and Query Parameters in Express.js
Learn about path and query parameters and how to access them in Express.js.
We'll cover the following
Overview
Path and query parameters play a big role in API development. Here's how we often use these parameters:
Path parameters in an API let us find a specific resource. This is known as resource identification. Query parameters let us organize resources based on our choices. For example, in an online learning app like Educative.io, a path parameter might find a course by its ID. Query parameters sort courses by category or cost.
Large amounts of information can be made manageable using path parameters. These path parameters divide the information into smaller, digestible parts. Query parameters then organize this split data by unique characteristics. Think about an online shopping app such as Amazon or eBay. A path parameter sets the page number and returns per page. Query parameters sort items by popularity or cost.
In case of searching, path parameters can help point out what resource we're looking for, whereas query parameters can refine our search using certain requirements. Say we're using an app to order food online. A path parameter can show the type of food (like ingredients, where the restaurant is, or delivery time), while query parameters can sift through search results based on food component or dietary 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 ofuserId
will be a path (route) parameter.The API will accept another GET request to list the details of
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 parameters get lifted from the URL. They use the params
property found in the request object. This object is funnefunnelledled into the callback function as a parameter. 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.