🔹 Step 1: Initialize Your Project
mkdir express-api-demo && cd express-api-demo
npm init -y
npm install express
🔹 Step 2: Create Your Basic Server
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
🔹 Step 3: Define API Routes
let users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
app.get('/api/users', (req, res) => {
res.json(users);
});
app.get('/api/users/:id', (req, res) => {
const user = users.find(u => u.id == req.params.id);
user ? res.json(user) : res.status(404).send('User not found');
});
🔹 Step 4: Add POST and DELETE
app.post('/api/users', (req, res) => {
const user = {
id: users.length + 1,
name: req.body.name
};
users.push(user);
res.status(201).json(user);
});
app.delete('/api/users/:id', (req, res) => {
users = users.filter(u => u.id != req.params.id);
res.status(204).send();
});
🔹 Step 5: Basic Error Handling
app.use((req, res) => {
res.status(404).send('Route not found');
});
🔹 Bonus: Test With Postman or Curl
Use Postman or curl to test:
curl http://localhost:3000/api/users
🚀 Ready to build your next Express.js REST API? Bookmark this guide!