Build a REST API with Node.js and Express
Step-by-step guide to creating a production-ready REST API with Node.js and Express.
Building APIs is a fundamental skill for modern web developers. Let’s create one from scratch.
Prerequisites
- Node.js installed
- Basic JavaScript knowledge
- A code editor
Project Setup
First, create a new directory and initialize npm:
mkdir my-api
cd my-api
npm init -y
Install Express:
npm install express
Creating the Server
Create index.js:
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());
// Routes
app.get('/', (req, res) => {
res.json({ message: 'Welcome to the API' });
});
app.get('/api/users', (req, res) => {
res.json([
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' }
]);
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Adding CRUD Operations
let users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' }
];
// Create
app.post('/api/users', (req, res) => {
const user = {
id: users.length + 1,
name: req.body.name
};
users.push(user);
res.status(201).json(user);
});
// Update
app.put('/api/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ error: 'Not found' });
user.name = req.body.name;
res.json(user);
});
// Delete
app.delete('/api/users/:id', (req, res) => {
users = users.filter(u => u.id !== parseInt(req.params.id));
res.status(204).send();
});
Error Handling
Always handle errors gracefully:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
Conclusion
You now have a functional REST API! Next steps: add validation, authentication, and a database.
Musetrend
Creator behind Musetrend.
You might also like
Getting Started with n8n Workflow Automation
Learn how to automate your digital workflows with n8n, the open-source automation platform. Step-by-step guide for …
10 Color Palettes That Will Transform Your Design
Discover stunning color combinations that professional designers use to create eye-catching visuals.
15 Stunning Color Palettes for Your Next Design Project
Discover beautiful, curated color combinations that will elevate your design work. Perfect for web design, branding, and …