When building APIs with Express.js, one of the first HTTP methods you'll work with is:
GET
A GET request is commonly used when we want to retrieve data from a server.
For example:
GET /api/users
GET /api/products
GET /api/blogs
But as applications become more complex, simply creating a GET route isn't enough.
We often need to retrieve a specific resource:
GET /api/users/10
Or filter and sort data:
GET /api/users?role=admin
Or combine multiple filters:
GET /api/products?category=mobile&sort=price
This is where route parameters and query parameters become important.
In this article, we'll learn:
-
What the Express.js GET method is
-
How to create GET routes
-
What route parameters are
-
How to use
req.params -
What query parameters are
-
How to use
req.query -
The difference between route parameters and query parameters
-
How to combine both
-
Common mistakes
-
Real-world API examples
Let's start from the basics.
What Is the GET Method?
GET is an HTTP method used to request data from a server.
For example:
GET /api/users
means:
"Give me the users."
Another example:
GET /api/products
means:
"Give me the products."
A typical request-response flow looks like this:
Client
|
| GET /api/users
↓
Express Server
|
| Find matching route
↓
Route Handler
|
| Fetch data
↓
JSON Response
|
↓
Client
Creating a Basic GET API
Let's create a simple Express application.
If you already have an Express project, you can use your existing project.
Otherwise:
mkdir express-get-api
cd express-get-api
npm init -y
npm install express
Create:
server.js
Add:
const express = require("express");
const app = express();
const PORT = 3000;
app.get("/api/users", (req, res) => {
res.json([
{
id: 1,
name: "John"
},
{
id: 2,
name: "Jane"
}
]);
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Start the server:
node server.js
Now visit:
http://localhost:3000/api/users
You'll receive:
[
{
"id": 1,
"name": "John"
},
{
"id": 2,
"name": "Jane"
}
]
We've created our first GET API.
Understanding app.get()
The important part is:
app.get("/api/users", (req, res) => {
// logic
});
Let's break it down.
app
↓
get()
↓
Route
↓
Request Handler
app
This is our Express application.
get()
This tells Express that we want to handle an HTTP GET request.
/api/users
This is the route.
(req, res)
These represent:
req → request
res → response
What Is req?
req represents the incoming HTTP request.
It contains information sent by the client.
For example:
app.get("/api/users", (req, res) => {
console.log(req.method);
console.log(req.url);
res.json({
message: "Users fetched successfully"
});
});
For:
GET /api/users
you could access:
GET
/api/users
The request object also gives us access to:
req.params
req.query
req.body
req.headers
req.method
req.url
In this article, we'll focus mainly on:
req.params
req.query
What Is res?
res represents the response that Express sends back to the client.
For example:
app.get("/api/users", (req, res) => {
res.json({
message: "Users fetched successfully"
});
});
The client receives:
{
"message": "Users fetched successfully"
}
You can also send a status code:
res.status(200).json({
message: "Users fetched successfully"
});
For a successful GET request, 200 OK is the common status code.
What Are Route Parameters?
Now suppose we have this API:
GET /api/users/10
We want to retrieve the user whose ID is 10.
We could create separate routes:
/api/users/1
/api/users/2
/api/users/3
/api/users/4
...
That obviously doesn't make sense.
Instead, we use a route parameter.
app.get("/api/users/:id", (req, res) => {
res.json({
userId: req.params.id
});
});
The :id part is a route parameter.
Now these URLs all match the same route:
/api/users/1
/api/users/2
/api/users/10
/api/users/100
Accessing Route Parameters with req.params
Let's look at this again:
app.get("/api/users/:id", (req, res) => {
console.log(req.params);
res.json({
userId: req.params.id
});
});
If we request:
GET /api/users/25
then:
req.params
contains:
{
"id": "25"
}
And:
req.params.id
returns:
"25"
Notice something important:
Route parameter values are strings by default.
So if you need a number:
const userId = Number(req.params.id);
Now:
"25"
becomes:
25
Building a Real User API
Let's create some sample users:
const users = [
{
id: 1,
name: "John",
role: "admin"
},
{
id: 2,
name: "Jane",
role: "user"
},
{
id: 3,
name: "David",
role: "user"
}
];
Now create:
app.get("/api/users/:id", (req, res) => {
const userId = Number(req.params.id);
const user = users.find((user) => user.id === userId);
if (!user) {
return res.status(404).json({
message: "User not found"
});
}
res.json(user);
});
Now request:
GET /api/users/2
Response:
{
"id": 2,
"name": "Jane",
"role": "user"
}
If we request:
GET /api/users/100
we get:
{
"message": "User not found"
}
with HTTP status:
404 Not Found
This is a much more realistic API.
Why Do We Need Route Parameters?
Route parameters are useful when the value identifies a specific resource.
For example:
/api/users/10
/api/products/50
/api/blogs/25
/api/orders/1001
The number represents a specific resource.
A useful mental model is:
Route parameter
↓
"Which resource?"
For example:
GET /api/users/10
↑
Which user?
Multiple Route Parameters
You can have multiple route parameters.
For example:
GET /api/users/10/orders/500
The route could be:
app.get("/api/users/:userId/orders/:orderId", (req, res) => {
res.json({
userId: req.params.userId,
orderId: req.params.orderId
});
});
Request:
GET /api/users/10/orders/500
Response:
{
"userId": "10",
"orderId": "500"
}
Now:
req.params
contains:
{
"userId": "10",
"orderId": "500"
}
This can be useful for nested resources.
What Are Query Parameters?
Now let's say we don't want one specific user.
Instead, we want to filter users.
For example:
GET /api/users?role=admin
Here:
role=admin
is a query parameter.
Unlike route parameters, query parameters come after:
?
in the URL.
For example:
/api/users?role=admin
The query string is:
role=admin
Accessing Query Parameters with req.query
In Express:
app.get("/api/users", (req, res) => {
console.log(req.query);
res.json(req.query);
});
Request:
GET /api/users?role=admin
Then:
req.query
contains:
{
"role": "admin"
}
And:
req.query.role
returns:
admin
Query Parameters Are Usually Used for Filtering
Let's use our users array again:
const users = [
{
id: 1,
name: "John",
role: "admin"
},
{
id: 2,
name: "Jane",
role: "user"
},
{
id: 3,
name: "David",
role: "user"
}
];
Now create:
app.get("/api/users", (req, res) => {
const { role } = req.query;
if (!role) {
return res.json(users);
}
const filteredUsers = users.filter(
(user) => user.role === role
);
res.json(filteredUsers);
});
Now:
GET /api/users
returns all users.
But:
GET /api/users?role=user
returns:
[
{
"id": 2,
"name": "Jane",
"role": "user"
},
{
"id": 3,
"name": "David",
"role": "user"
}
]
This is a common real-world use of query parameters.
Multiple Query Parameters
You can have multiple query parameters.
For example:
GET /api/users?role=user&name=Jane
Express gives you:
req.query
as:
{
"role": "user",
"name": "Jane"
}
You can access them:
const { role, name } = req.query;
Now you can use them for filtering.
Query Parameters for Searching
Query parameters are commonly used for search functionality.
For example:
GET /api/products?search=laptop
Express:
app.get("/api/products", (req, res) => {
const { search } = req.query;
console.log(search);
res.json({
search
});
});
Request:
GET /api/products?search=laptop
Response:
{
"search": "laptop"
}
In a real application, you would use the search value to query a database.
Query Parameters for Pagination
Query parameters are also commonly used for pagination.
For example:
GET /api/products?page=2&limit=10
Then:
app.get("/api/products", (req, res) => {
const page = Number(req.query.page) || 1;
const limit = Number(req.query.limit) || 10;
res.json({
page,
limit
});
});
Request:
GET /api/products?page=2&limit=10
Response:
{
"page": 2,
"limit": 10
}
This is a very common pattern in production APIs.
Query Parameters for Sorting
We can also use query parameters for sorting.
For example:
GET /api/products?sort=price
or:
GET /api/products?sort=name
Express:
app.get("/api/products", (req, res) => {
const { sort } = req.query;
console.log("Sort by:", sort);
res.json({
sort
});
});
The backend can then apply the appropriate sorting logic.
Route Parameters vs Query Parameters
This is one of the most important concepts to understand.
Consider these two URLs:
GET /api/products/100
and:
GET /api/products?category=mobile
They have different purposes.
Route Parameter
/api/products/100
The 100 identifies a specific product.
req.params.id
Query Parameter
/api/products?category=mobile
The category is used to filter or modify the result.
req.query.category
A simple mental model:
Route parameter
→ Identify a resource
Query parameter
→ Filter, search, sort, paginate, or customize a collection
A Practical Comparison
Consider:
GET /api/products/101
This means:
Give me product 101.
Whereas:
GET /api/products?category=mobile
means:
Give me products belonging to the mobile category.
And:
GET /api/products?category=mobile&sort=price
means:
Give me mobile products and sort them by price.
Can We Use Both?
Yes.
We can use route parameters and query parameters together.
For example:
GET /api/users/10/orders?status=completed
Here:
10
is a route parameter.
And:
status=completed
is a query parameter.
Express route:
app.get("/api/users/:userId/orders", (req, res) => {
const { userId } = req.params;
const { status } = req.query;
res.json({
userId,
status
});
});
Request:
GET /api/users/10/orders?status=completed
Response:
{
"userId": "10",
"status": "completed"
}
This pattern is very common in real applications.
Route Parameter Is Required
Consider:
app.get("/api/users/:id", (req, res) => {
// ...
});
The id parameter is required.
This URL matches:
/api/users/10
But:
/api/users
does not match this route.
If you want /api/users to work, you need another route:
app.get("/api/users", (req, res) => {
// Return all users
});
Query Parameters Are Optional
Consider:
GET /api/users?role=admin
The query parameter role is optional.
This route:
app.get("/api/users", (req, res) => {
// ...
});
can handle both:
/api/users
and:
/api/users?role=admin
That's one major difference between route parameters and query parameters.
Handling Optional Query Parameters
Suppose we support:
GET /api/products?category=mobile&sort=price&page=2
But the client might send only:
GET /api/products
We can provide defaults:
app.get("/api/products", (req, res) => {
const {
category,
sort = "name",
page = 1,
limit = 10
} = req.query;
res.json({
category,
sort,
page,
limit
});
});
Now the API can work even when the client doesn't provide every query parameter.
Query Parameter Values Are Strings
This is another important detail.
Suppose we request:
GET /api/products?page=2&limit=20
Then:
req.query.page
is generally:
"2"
not:
2
So when you need numbers, convert them:
const page = Number(req.query.page) || 1;
const limit = Number(req.query.limit) || 10;
This is especially important for:
-
Pagination
-
IDs
-
Numeric filters
-
Price ranges
-
Limits
A Complete Example
Let's build a small API that supports:
-
Get all products
-
Get a product by ID
-
Filter by category
-
Search products
-
Pagination
Start with:
const express = require("express");
const app = express();
const PORT = 3000;
const products = [
{
id: 1,
name: "iPhone",
category: "mobile",
price: 800
},
{
id: 2,
name: "MacBook",
category: "laptop",
price: 1500
},
{
id: 3,
name: "Samsung Galaxy",
category: "mobile",
price: 700
},
{
id: 4,
name: "Dell XPS",
category: "laptop",
price: 1200
}
];
Now create the GET API:
app.get("/api/products", (req, res) => {
const {
category,
search,
page = 1,
limit = 10
} = req.query;
let result = products;
// Filter by category
if (category) {
result = result.filter(
(product) => product.category === category
);
}
// Search by product name
if (search) {
result = result.filter(
(product) =>
product.name
.toLowerCase()
.includes(search.toLowerCase())
);
}
// Pagination
const pageNumber = Number(page);
const limitNumber = Number(limit);
const startIndex =
(pageNumber - 1) * limitNumber;
const paginatedProducts = result.slice(
startIndex,
startIndex + limitNumber
);
res.json({
page: pageNumber,
limit: limitNumber,
total: result.length,
data: paginatedProducts
});
});
Now we can make different requests.
Get All Products
GET /api/products
Returns all products.
Filter by Category
GET /api/products?category=mobile
Returns mobile products.
Search Products
GET /api/products?search=iphone
Returns products matching the search term.
Pagination
GET /api/products?page=1&limit=2
Returns the first two products.
Next page:
GET /api/products?page=2&limit=2
This demonstrates how query parameters can make a single GET endpoint much more flexible.
Get a Specific Product
Now let's create a route parameter:
app.get("/api/products/:id", (req, res) => {
const productId = Number(req.params.id);
const product = products.find(
(product) => product.id === productId
);
if (!product) {
return res.status(404).json({
message: "Product not found"
});
}
res.json(product);
});
Now:
GET /api/products/2
returns:
{
"id": 2,
"name": "MacBook",
"category": "laptop",
"price": 1500
}
Here:
:id
is a route parameter.
And:
req.params.id
contains its value.
Complete Example
Our complete server can now look like this:
const express = require("express");
const app = express();
const PORT = 3000;
const products = [
{
id: 1,
name: "iPhone",
category: "mobile",
price: 800
},
{
id: 2,
name: "MacBook",
category: "laptop",
price: 1500
},
{
id: 3,
name: "Samsung Galaxy",
category: "mobile",
price: 700
},
{
id: 4,
name: "Dell XPS",
category: "laptop",
price: 1200
}
];
// Get all products
// Supports filtering, searching and pagination
app.get("/api/products", (req, res) => {
const {
category,
search,
page = 1,
limit = 10
} = req.query;
let result = products;
// Filter by category
if (category) {
result = result.filter(
(product) => product.category === category
);
}
// Search by name
if (search) {
result = result.filter(
(product) =>
product.name
.toLowerCase()
.includes(search.toLowerCase())
);
}
// Pagination
const pageNumber = Number(page);
const limitNumber = Number(limit);
const startIndex =
(pageNumber - 1) * limitNumber;
const paginatedProducts = result.slice(
startIndex,
startIndex + limitNumber
);
res.json({
page: pageNumber,
limit: limitNumber,
total: result.length,
data: paginatedProducts
});
});
// Get product by ID
app.get("/api/products/:id", (req, res) => {
const productId = Number(req.params.id);
const product = products.find(
(product) => product.id === productId
);
if (!product) {
return res.status(404).json({
message: "Product not found"
});
}
res.json(product);
});
// Start server
app.listen(PORT, () => {
console.log(
`Server running on http://localhost:${PORT}`
);
});
Understanding the API Design
At this point, we have:
GET /api/products
Used for:
Get all products
Filter products
Search products
Paginate products
And:
GET /api/products/:id
Used for:
Get one specific product
This is a clean REST API design.
Common Mistakes
Mistake 1: Using Query Parameters to Identify a Resource
You might see:
GET /api/products?id=10
This isn't necessarily wrong, but when the intention is specifically to identify one resource, this is usually clearer:
GET /api/products/10
The route itself communicates:
"I want product 10."
Mistake 2: Forgetting to Convert Numbers
Remember:
req.params.id
is generally a string.
So this can cause problems:
const product = products.find(
(product) => product.id === req.params.id
);
because:
product.id
might be:
10
while:
req.params.id
is:
"10"
They have different types.
Instead:
const productId = Number(req.params.id);
const product = products.find(
(product) => product.id === productId
);
Mistake 3: Assuming Query Parameters Are Always Present
Don't assume:
const { page, limit } = req.query;
will always contain values.
The client might simply request:
GET /api/products
Provide sensible defaults:
const page = Number(req.query.page) || 1;
const limit = Number(req.query.limit) || 10;
Mistake 4: Putting Everything in Route Parameters
You don't want URLs like:
/api/products/mobile/price/ascending/page/2/limit/10
That's difficult to read and maintain.
Query parameters are much better for optional filtering and configuration:
/api/products?category=mobile&sort=price&page=2&limit=10
Mistake 5: Not Validating Parameters
Never blindly trust values coming from the client.
For example:
GET /api/products/hello
If your API expects a numeric ID, validate it:
const productId = Number(req.params.id);
if (Number.isNaN(productId)) {
return res.status(400).json({
message: "Invalid product ID"
});
}
Similarly, pagination values should be validated.
For example:
const page = Number(req.query.page);
if (page < 1) {
return res.status(400).json({
message: "Page must be greater than 0"
});
}
Validation becomes especially important when your API starts interacting with a database.
A Simple Rule to Remember
When designing a GET API, ask yourself:
Am I identifying a specific resource?
Use a route parameter.
GET /api/users/10
Am I filtering or customizing a collection?
Use a query parameter.
GET /api/users?role=admin
Do I need both?
Use both.
GET /api/users/10/orders?status=completed
This simple rule will help you design cleaner APIs.
Final Thoughts
The Express.js GET method is one of the most important building blocks when creating REST APIs.
At first, a route may look as simple as:
app.get("/api/users", (req, res) => {
res.json(users);
});
But as your API grows, you'll need ways to identify specific resources and customize the data being returned.
That's where route parameters and query parameters come in.
Remember:
Route Parameter
→ Identify a specific resource
GET /api/users/10
↑
req.params
And:
Query Parameter
→ Filter, search, sort, paginate, or customize data
GET /api/users?role=admin
↑
req.query
And they can work together:
GET /api/users/10/orders?status=completed
↑ ↑
req.params req.query
Once you understand these three concepts:
GET
req.params
req.query
you have a strong foundation for building REST APIs with Express.js.
In the next stage of learning Express.js, the natural step is to understand POST requests and req.body, because that's where we'll start sending data from the client to the server and creating resources instead of just retrieving them.