REST APIs are essential for modern web development, enabling communication between clients and servers. In this guide, you’ll learn how to build a simple REST API using Node.js. By the end of this tutorial, you’ll have a fully functional API to perform basic CRUD (Create, Read, Update, Delete) operations.
Step 1: Set Up Your Environment
Before we begin, ensure you have the following installed:
- Node.js (LTS version recommended)
- A text editor (e.g., Visual Studio Code)
- Postman or any API testing tool
Step 2: Initialize a Node.js Project
Create a new folder for your project and initialize a Node.js application:
mkdir rest-api-nodejs
cd rest-api-nodejs
npm init -y
This will generate a package.json
file for your project.
Step 3: Install Required Dependencies
Install the following packages:
npm install express body-parser
- Express: A minimal Node.js framework for building APIs.
- Body-parser: Middleware to handle JSON payloads.
Step 4: Create the API
Create a file named index.js
and add the following code:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const PORT = 3000;
// Middleware
app.use(bodyParser.json());
// Sample data
let items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
];
// Get all items
app.get('/api/items', (req, res) => {
res.json(items);
});
// Get a single item by ID
app.get('/api/items/:id', (req, res) => {
const item = items.find(i => i.id === parseInt(req.params.id));
if (!item) return res.status(404).send('Item not found');
res.json(item);
});
// Add a new item
app.post('/api/items', (req, res) => {
const newItem = {
id: items.length + 1,
name: req.body.name
};
items.push(newItem);
res.status(201).json(newItem);
});
// Update an item
app.put('/api/items/:id', (req, res) => {
const item = items.find(i => i.id === parseInt(req.params.id));
if (!item) return res.status(404).send('Item not found');
item.name = req.body.name;
res.json(item);
});
// Delete an item
app.delete('/api/items/:id', (req, res) => {
const itemIndex = items.findIndex(i => i.id === parseInt(req.params.id));
if (itemIndex === -1) return res.status(404).send('Item not found');
items.splice(itemIndex, 1);
res.status(204).send();
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Step 5: Test Your API
Start your server by running:
node index.js
Use Postman or your browser to test the endpoints:
- GET /api/items: Retrieve all items.
- GET /api/items/:id: Retrieve a single item by ID.
- POST /api/items: Add a new item.
- PUT /api/items/:id: Update an existing item.
- DELETE /api/items/:id: Delete an item by ID.
Conclusion
Congratulations! You’ve built a simple REST API using Node.js. From here, you can expand your API to include authentication, connect it to a database, or deploy it to a cloud platform.
Goto home