Creating a RESTful API with Express.js is a great way to manage and serve data in a structured way. REST (Representational State Transfer) is an architectural style that uses standard HTTP methods to interact with resources. Express.js, a minimalist web framework for Node.js, makes it easy to build web applications and APIs. In this article, we’ll look at three practical examples that will help you understand how to create a RESTful API with Express.js.
In this example, we’ll create a simple API for managing a to-do list. This API will allow users to create, read, update, and delete tasks.
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
let tasks = [];
app.get('/tasks', (req, res) => {
res.json(tasks);
});
app.post('/tasks', (req, res) => {
const task = req.body;
tasks.push(task);
res.status(201).json(task);
});
app.put('/tasks/:id', (req, res) => {
const { id } = req.params;
const updatedTask = req.body;
tasks[id] = updatedTask;
res.json(updatedTask);
});
app.delete('/tasks/:id', (req, res) => {
const { id } = req.params;
tasks.splice(id, 1);
res.status(204).send();
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
In this example, we will create a basic user authentication system. This API will allow users to register and log in with their credentials.
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt');
app.use(bodyParser.json());
let users = [];
app.post('/register', async (req, res) => {
const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
users.push({ username, password: hashedPassword });
res.status(201).send('User registered successfully');
});
app.post('/login', async (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username);
if (!user || !(await bcrypt.compare(password, user.password))) {
return res.status(403).send('Invalid credentials');
}
res.send('Login successful');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
In this example, we will create a RESTful API for managing products in an e-commerce application. Users will be able to create, view, update, and delete products.
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
let products = [];
app.get('/products', (req, res) => {
res.json(products);
});
app.post('/products', (req, res) => {
const product = req.body;
products.push(product);
res.status(201).json(product);
});
app.put('/products/:id', (req, res) => {
const { id } = req.params;
const updatedProduct = req.body;
products[id] = updatedProduct;
res.json(updatedProduct);
});
app.delete('/products/:id', (req, res) => {
const { id } = req.params;
products.splice(id, 1);
res.status(204).send();
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
These examples of creating a RESTful API with Express.js show how you can build a variety of applications quickly. Whether it’s a simple to-do list, user authentication, or product management, Express.js provides the tools you need to get started. Happy coding!