Node.js REST API Implementation
When building a REST API with Node.js, you can utilize its built-in modules like http
to create a straightforward and efficient API. Below is a step-by-step guide to implement a REST API without any external libraries or database integration.
Step 1: Setting Up the Node.js Environment
- Initialize a Node.js project
Create a folder for your project and initialize apackage.json
file:
mkdir node-rest-api
cd node-rest-api
npm init -y
- Create the Main Server File
Create a file namedserver.js
where the API logic will reside:
touch server.js
Step 2: Writing the Server Code
In the server.js
file, start by importing the required modules and initializing the server.
const http = require('http');
// Data storage for demonstration (in-memory storage)
let data = [
{ id: 1, name: "Item 1" },
{ id: 2, name: "Item 2" },
{ id: 3, name: "Item 3" }
];
// Helper function to parse JSON request body
function parseRequestBody(req) {
return new Promise((resolve, reject) => {
let body = '';
req.on('data', chunk => (body += chunk));
req.on('end', () => {
try {
resolve(JSON.parse(body));
} catch (error) {
reject(error);
}
});
});
}
// Create HTTP server
const server = http.createServer(async (req, res) => {
const { method, url } = req;
// Route: GET /items
if (method === 'GET' && url === '/items') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
}
// Route: POST /items
else if (method === 'POST' && url === '/items') {
try {
const newItem = await parseRequestBody(req);
newItem.id = data.length ? data[data.length - 1].id + 1 : 1;
data.push(newItem);
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(newItem));
} catch (error) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
}
// Route: PUT /items/:id
else if (method === 'PUT' && url.startsWith('/items/')) {
const id = parseInt(url.split('/')[2], 10);
const index = data.findIndex(item => item.id === id);
if (index === -1) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Item not found' }));
return;
}
try {
const updatedItem = await parseRequestBody(req);
data[index] = { ...data[index], ...updatedItem };
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data[index]));
} catch (error) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
}
// Route: DELETE /items/:id
else if (method === 'DELETE' && url.startsWith('/items/')) {
const id = parseInt(url.split('/')[2], 10);
const index = data.findIndex(item => item.id === id);
if (index === -1) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Item not found' }));
return;
}
data.splice(index, 1);
res.writeHead(204); // No content
res.end();
}
// Route Not Found
else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Route not found' }));
}
});
// Start server
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Step 3: Running the Server
Start the server using Node.js:
node server.js
Step 4: Testing the API
You can test the API endpoints using curl
or Postman. Here are some example requests:
- GET /items
curl -X GET http://localhost:3000/items
- POST /items
curl -X POST http://localhost:3000/items -H "Content-Type: application/json" -d '{"name":"New Item"}'
- PUT /items/:id
curl -X PUT http://localhost:3000/items/1 -H "Content-Type: application/json" -d '{"name":"Updated Item"}'
- DELETE /items/:id
curl -X DELETE http://localhost:3000/items/1
Conclusion
This Node.js REST API implementation demonstrates a simple and efficient way to create an API using the built-in http
module. While this approach is suitable for learning and small-scale applications, consider using frameworks like Express.js or adding a database for more robust projects.
Latest blog posts
Explore the world of programming and cybersecurity through our curated collection of blog posts. From cutting-edge coding trends to the latest cyber threats and defense strategies, we've got you covered.