Products JSON API in Node.js
A Products JSON API is an API that returns product information in JSON format. In Node.js, we can create an HTTP server that handles requests and sends product data to the client.
In this lesson, we will learn how to create a Products JSON API, retrieve all products, retrieve a single product by ID, handle HTTP routes, and return appropriate status codes.
1. What Is a Products JSON API?
A Products JSON API allows a client application to request product information from a server. The server returns the requested information in JSON format.
For example, Samadhan wants to display products on a website. The website sends a request to the Node.js server, and the server returns product details such as ID, name, price, and category.
[
{
"id": 1,
"name": "Laptop",
"price": 55000,
"category": "Electronics"
},
{
"id": 2,
"name": "Keyboard",
"price": 1500,
"category": "Accessories"
}
]
Here, the API returns two products as a JSON array. Each product is represented as a JavaScript object before being converted into JSON text for the HTTP response.
2. How Does a Products API Work?
The client sends an HTTP request to a specific API route. The Node.js server checks the request method and URL, retrieves the required product data, and sends a response.
Requests product information
Checks the HTTP method and route
Finds the required product data
Returns product information to the client
3. Creating a Products JSON API
First, import the built-in HTTP module. Then create an array
containing product information and use http.createServer()
to create the API server.
Example:
const http = require('http');
const products = [
{
id: 1,
name: 'Laptop',
price: 55000,
category: 'Electronics'
},
{
id: 2,
name: 'Keyboard',
price: 1500,
category: 'Accessories'
},
{
id: 3,
name: 'Mouse',
price: 800,
category: 'Accessories'
}
];
const server = http.createServer((req, res) => {
res.setHeader(
'Content-Type',
'application/json; charset=utf-8'
);
if (req.method === 'GET' && req.url === '/api/products') {
res.writeHead(200);
res.end(JSON.stringify(products));
} else {
res.writeHead(404);
res.end(JSON.stringify({
message: 'API route not found'
}));
}
});
server.listen(3000, () => {
console.log('Products API running at http://localhost:3000');
});
In this example, the server checks whether the client sends
a GET request to /api/products. If the route matches,
the server returns the complete product list.
If the requested route does not match, the server returns
HTTP status 404 Not Found.
4. Understanding the Code
| Code | Explanation |
|---|---|
require('http') |
Imports Node.js's built-in HTTP module. |
const products = [...] |
Stores the sample product data in an array. |
http.createServer() |
Creates an HTTP server to handle incoming requests. |
req.method |
Checks the HTTP method used by the client. |
req.url |
Checks the requested URL path. |
res.setHeader() |
Sets the response Content-Type header. |
JSON.stringify(products) |
Converts the JavaScript product array into JSON text. |
res.writeHead(200) |
Sets the HTTP status to 200 OK. |
res.end() |
Sends the response and finishes it. |
server.listen(3000) |
Starts the server on port 3000. |
5. Running the Products API
Save the code in a file named server.js.
Open a terminal in the same folder and execute the following command.
node server.js
Expected output:
Products API running at http://localhost:3000
The server is now listening on port 3000 and can receive HTTP requests from a browser or another client.
6. Getting All Products
To retrieve all products, send a GET request to the following URL:
http://localhost:3000/api/products
You can open this URL in a browser while the server is running. The server returns the product array as JSON.
Expected response:
[
{
"id": 1,
"name": "Laptop",
"price": 55000,
"category": "Electronics"
},
{
"id": 2,
"name": "Keyboard",
"price": 1500,
"category": "Accessories"
},
{
"id": 3,
"name": "Mouse",
"price": 800,
"category": "Accessories"
}
]
The response status is 200 OK because the server
successfully returned the product list.
7. Getting a Single Product by ID
Sometimes a client needs only one product instead of the complete product list. We can use the product ID to find the required product.
Add the following route before the final else block
inside http.createServer().
else if (req.method === 'GET' && req.url === '/api/products/1') {
const product = products.find(item => item.id === 1);
if (product) {
res.writeHead(200);
res.end(JSON.stringify(product));
} else {
res.writeHead(404);
res.end(JSON.stringify({
message: 'Product not found'
}));
}
}
The find() method searches the array and returns
the first product that matches the specified condition.
Request URL:
http://localhost:3000/api/products/1
Expected response:
{
"id": 1,
"name": "Laptop",
"price": 55000,
"category": "Electronics"
}
This route is specifically written for product ID 1. To support every product ID dynamically, the server would need to extract and validate the ID from the requested URL.
8. Handling Unknown Routes
If a client requests a URL that the server does not support, the API should return an appropriate error response.
Example:
else {
res.writeHead(404);
res.end(JSON.stringify({
message: 'API route not found'
}));
}
Request URL:
http://localhost:3000/unknown
Expected response:
{
"message": "API route not found"
}
HTTP status 404 Not Found indicates that the
requested route was not found on the server.
9. Testing the Products API Using curl
We can use the curl command to send requests
to the API from a terminal.
Get all products:
curl -i http://localhost:3000/api/products
Get the product with ID 1:
curl -i http://localhost:3000/api/products/1
Request an unknown route:
curl -i http://localhost:3000/unknown
The -i option displays the HTTP response headers
along with the response body, so you can check the status code.
10. Important HTTP Status Codes
| Status Code | Meaning | Usage |
|---|---|---|
200 OK |
Request successful. | Product data is returned. |
404 Not Found |
Requested resource was not found. | Unknown API route or missing product. |
11. Practice Tasks
Task 1: Create a Products API
- Create a file named
server.js. - Import the built-in
httpmodule. - Create an array containing at least three products.
- Create a GET route named
/api/products. - Return all products in JSON format.
Expected result: The API should return all
products when the client requests /api/products.
Task 2: Retrieve a Single Product
- Add a route for retrieving one product.
- Use the product ID to find the required product.
- Return the product as JSON.
- Return HTTP status
404when the product is not found.
Expected result: The API should return the selected product or an appropriate not-found response.
Summary
In this lesson, we created a simple Products JSON API using Node.js's built-in HTTP module. We learned how to create product data, handle GET requests, return all products, retrieve a predefined product, and handle unknown routes.
We also used JSON.stringify() to convert
JavaScript data into JSON text and learned how HTTP status
codes communicate the result of a request.
Remember the flow: Client Request → Check Route → Find Product Data → Convert to JSON → Send HTTP Response.