GET Requests in REST API
GET is an HTTP method used to retrieve information from a server through a REST API.
When a user opens a product page, views a list of courses, or checks their profile, the application commonly sends a GET request to retrieve the required data.
In Node.js and Express.js, we can create GET endpoints using
app.get(). These endpoints can return JSON data,
individual resources, or lists of resources to the client.
1. What Is a GET Request?
A GET request asks the server to retrieve a representation of a resource. It is commonly used when an application needs to read information without changing the resource on the server.
For example, an application may use these endpoints:
GET /api/products— retrieve all products.GET /api/products/101— retrieve a product with ID 101.GET /api/courses— retrieve available courses.
2. How a GET Request Works
The client sends a GET request to an endpoint. Express matches the requested path, executes the route handler, and returns the requested data.
Step 1: Client
Requests product information
Step 2: GET Endpoint
GET /api/products
Step 3: Express Route Handler
Finds and prepares the requested data
Step 4: JSON Response
Returns product information and a status code
Step 5: Client
Displays the received information
For example, when the client requests
/api/products, the server may return an array
containing all available products.
3. Creating a Simple GET API
Let us create a GET endpoint that returns a list of products stored in a JavaScript array.
Step 1: Create app.js
const express = require('express');
const app = express();
const products = [
{
id: 1,
name: 'Laptop',
price: 55000
},
{
id: 2,
name: 'Keyboard',
price: 1500
},
{
id: 3,
name: 'Mouse',
price: 700
}
];
// GET endpoint
app.get('/api/products', (req, res) => {
res.status(200).json(products);
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Step 2: Install Express.js
npm init -y
npm install express
Step 3: Run the application
node app.js
Expected terminal output:
Server running on port 3000
Step 4: Open the endpoint
http://localhost:3000/api/products
Expected JSON response:
[
{
"id": 1,
"name": "Laptop",
"price": 55000
},
{
"id": 2,
"name": "Keyboard",
"price": 1500
},
{
"id": 3,
"name": "Mouse",
"price": 700
}
]
The app.get() method registers the GET endpoint.
The res.status(200) call sets the success status,
and res.json() sends the array as a JSON response.
4. GET Request Using Route Parameters
Sometimes we need to retrieve one specific resource instead of the entire collection. Route parameters allow us to identify the resource through the URL.
For example, /api/products/2 requests the product with ID 2.
const express = require('express');
const app = express();
const products = [
{ id: 1, name: 'Laptop', price: 55000 },
{ id: 2, name: 'Keyboard', price: 1500 },
{ id: 3, name: 'Mouse', price: 700 }
];
app.get('/api/products/:id', (req, res) => {
const id = Number(req.params.id);
const product = products.find(p => p.id === id);
if (!Number.isInteger(id) || id <= 0) {
return res.status(400).json({
message: 'Invalid product ID'
});
}
if (!product) {
return res.status(404).json({
message: 'Product not found'
});
}
res.status(200).json(product);
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Test this URL:
http://localhost:3000/api/products/2
Expected response:
{
"id": 2,
"name": "Keyboard",
"price": 1500
}
The value :id is a route parameter.
Express makes its value available through
req.params.id. The application converts it to
a number and searches for the matching product.
5. GET Request Using Query Parameters
Query parameters are commonly used to filter, search, sort, or paginate a collection of resources.
For example, the URL
/api/products?category=electronics contains a
query parameter named category.
const express = require('express');
const app = express();
const products = [
{ id: 1, name: 'Laptop', category: 'electronics' },
{ id: 2, name: 'Keyboard', category: 'accessories' },
{ id: 3, name: 'Mouse', category: 'accessories' }
];
app.get('/api/products', (req, res) => {
const category = req.query.category;
let result = products;
if (category) {
result = products.filter(
product => product.category === category
);
}
res.status(200).json(result);
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Request URL:
http://localhost:3000/api/products?category=accessories
Expected response:
[
{
"id": 2,
"name": "Keyboard",
"category": "accessories"
},
{
"id": 3,
"name": "Mouse",
"category": "accessories"
}
]
Express provides query parameters through req.query.
The example filters the product array and returns only products
that match the requested category.
6. Diagram 2: Route Parameters vs Query Parameters
Both route parameters and query parameters provide information through a URL, but they are commonly used for different purposes.
Example URL 1
/api/products/101
Route Parameter
req.params.id gives the value 101.
Example URL 2
/api/products?category=electronics
Query Parameter
req.query.category gives the value electronics.
| Feature | Route Parameter | Query Parameter |
|---|---|---|
| Example | /products/101 |
/products?category=electronics |
| Access in Express | req.params |
req.query |
| Common purpose | Identify a specific resource | Filter or customize a collection request |
7. Common HTTP Status Codes for GET Requests
| Status Code | Meaning | Example |
|---|---|---|
| 200 OK | The request succeeded. | Products were returned successfully. |
| 400 Bad Request | The request contains invalid input. | A product ID is not valid. |
| 401 Unauthorized | Valid authentication credentials are missing or invalid. | An endpoint requires authentication. |
| 404 Not Found | The requested resource was not found. | No product exists with the requested ID. |
| 500 Internal Server Error | An unexpected server-side error occurred. | A database operation fails unexpectedly. |
8. Best Practices for GET APIs
- Use clear resource-based endpoint names.
- Use GET requests to retrieve data rather than modify resources.
- Validate route and query parameters.
- Return appropriate status codes.
- Use pagination when retrieving large collections.
- Do not expose private information without proper authorization.
- Use a database when data must persist beyond the server process.
Important Points to Remember
- GET requests are used to retrieve resources.
- Use
app.get()to define a GET endpoint in Express.js. - Use
res.json()to return JSON data. - Access route parameters through
req.params. - Access query parameters through
req.query. - Use status code 200 for a successful retrieval.
- Use 400 for invalid input and 404 when the requested resource does not exist.
- GET requests should not be designed to modify server resources.
Summary
GET is an HTTP method used to retrieve information from a
REST API. Express.js provides app.get() for
defining endpoints that return resources as JSON or other
supported response formats.
Route parameters help identify specific resources, while query parameters commonly support filtering and searching. Proper validation and status codes make GET endpoints easier to use and maintain.