In this tutorial, we'll learn how to create a simple REST API using Node.js and the Express framework. REST APIs are vital for enabling communication between clients and servers, allowing them to interact with data over the web.
Prerequisites
Before we begin, ensure you have the following installed:
- Node.js: Download and install from [nodejs.org].
- npm: Comes bundled with Node.js, but make sure it's up to date.
Step 1: Setting Up the Project
- Create a new directory for your project:
mkdir my-api
cd my-api
- Initialize a new Node.js project:
npm init -y
- Install Express:
npm install express
Step 2: Creating Your First Endpoint
Create a file named server.js
in your project directory and add the following code:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
// Simple GET endpoint
app.get('/', (req, res) => {
res.send('Welcome to my API!');
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Testing the Endpoint
Run your server:
node server.js
Open your browser or Postman and go to http://localhost:3000
. You should see "Welcome to my API!".
Step 3: Adding CRUD Functionality
Now, let's implement Create, Read, Update, and Delete operations. For simplicity, we’ll store data in memory.
Sample Data
Add this sample data at the top of your server.js
file:
let items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
];
Create an Item
Add the following POST endpoint:
app.post('/items', (req, res) => {
const newItem = {
id: items.length + 1,
name: req.body.name,
};
items.push(newItem);
res.status(201).send(newItem);
});
Read All Items
Add the following GET endpoint:
app.get('/items', (req, res) => {
res.send(items);
});
Update an Item
Add the following PUT endpoint:
app.put('/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.send(item);
});
Delete an Item
Add the following DELETE endpoint:
app.delete('/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.');
const deletedItem = items.splice(itemIndex, 1);
res.send(deletedItem);
});
Step 4: Error Handling
To handle errors gracefully, you can add a middleware for 404 errors:
app.use((req, res) => {
res.status(404).send('Resource not found.');
});
Conclusion
Congratulations! You've built a simple REST API using Node.js and Express. You can now expand this API by adding features like authentication, connecting to a database, or implementing advanced error handling.
Further Reading
- [Express Documentation]
- [Node.js Documentation]
Feel free to share your thoughts or improvements in the comments below!
Top comments (0)