Introduction
What is the Query Parameter in the URL?
A query parameter is a key-value pair that is appended to the end of the URL in an HTTP request. Query parameters are used to modify the behavior of an API, such as filtering or sorting data, or to specify search criteria. For example, in a URL like https://example.com/api/users?role=admin, the role parameter is a query parameter that specifies the role of the users to retrieve.
Query parameters are especially useful when building APIs because they allow clients to specify exactly what data they want to receive from the server. This can help reduce the amount of data transferred over the network, which can improve the performance of the API.
In addition to simple key-value pairs, query parameters can also be used to pass more complex data, such as arrays or nested objects. For example, in a URL like https://example.com/api/products?category[]=electronics&category[]=accessories&price[from]=100&price[to]=500, the category parameter is an array of categories to include, and a price parameter is a nested object that specifies the range of prices to include.
How to use Query Parameter in Express?
To access query parameters in an Express application, you can use the req.query object. This object contains key-value pairs of all the query parameters in the request URL.
Here is an example of how to use query parameters in an Express application:
import express from "express";
const app = express();
app.get("/api/users", (req, res) => {
const role = req.query.role; // retrieve the 'role' query parameter
const page = req.query.page || 1; // retrieve the 'page' query parameter or default to 1
// use the query parameters to filter and paginate data from the database
// ...
res.send(filteredData);
// filteredData is not defined in this example, don't copy this code, it won't work
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
Here we are retrieving the role and page query parameters from the request URL. If the page query parameter is not specified, we default to page 1. Then we use the query parameters to filter and paginate data from the database.
What's Next?
I am going to show you how to do pagination and filter using a query in Express.