Now that youโve built a basic server, letโs take it a step further by adding full CRUD functionality โ the foundation of most web apps.
๐ What is CRUD?
CRUD stands for:
โฆ C reate โ Add new data (e.g., new user)
โฆ R ead โ Get existing data (e.g., list users)
โฆ U pdate โ Modify existing data (e.g., change user name)
โฆ D elete โ Remove data (e.g., delete user)
These are the 4 basic operations every back-end should support.
๐งช Letโs Build a CRUD API
Weโll use the same setup as before (Node.js + Express) and simulate a database with an in-memory array.
Step 1: Setup Project (if not already)
npm init -y
npm install express
Step 2: Create server.js
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json()); // Middleware to parse JSON
let users = [
{ id: 1, name: 'Alice'},
{ id: 2, name: 'Bob'}
];
// READ - Get all users
app.get('/users', (req, res) => {
res.json(users);
});
// CREATE - Add a new user
app.post('/users', (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name
};
users.push(newUser);
res.status(201).json(newUser);
});
// UPDATE - Modify a user
app.put('/users/:id', (req, res) => {
const userId = parseInt(req.params.id);
const user = users.find(u => u.id === userId);
if (!user) return res.status(404).send('User not found');
user.name = req.body.name;
res.json(user);
});
// DELETE - Remove a user
app.delete('/users/:id', (req, res) => {
const userId = parseInt(req.params.id);
users = users.filter(u => u.id!== userId);
res.sendStatus(204);
});
app.listen(port, () => {
console.log(`CRUD API running at http://localhost:${port}`);
});Step 3: Test Your API
Use tools like Postman or cURL to test:
โฆ GET /users โ List users
โฆ POST /users โ Add user { "name": "Charlie"}
โฆ PUT /users/1 โ Update user 1โs name
โฆ DELETE /users/2 โ Delete user 2
๐ฏ Why This Matters
โฆ CRUD is the backbone of dynamic apps like blogs, e-commerce, social media, and more
โฆ Once you master CRUD, you can connect your app to a real database and build full-stack apps
Next Steps
โฆ Add validation (e.g., check if name is empty)
โฆ Connect to MongoDB or PostgreSQL
โฆ Add authentication (JWT, sessions)
โฆ Deploy your app to the cloud
๐ก Pro Tip: Try building a Notes app or a Product Inventory system using CRUD!
๐ฌ Double Tap โค๏ธ for more!