Creating a RESTful API with Express.js: 3 Examples

Discover 3 practical examples of creating a RESTful API with Express.js, designed for beginners and enthusiasts alike.
By Taylor

Introduction

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.

Example 1: Simple To-Do List API

Context

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}`);
});

Notes

  • This API uses an in-memory array to store tasks, so the data will reset every time the server restarts.
  • You can test this API using tools like Postman or Curl.

Example 2: User Authentication API

Context

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}`);
});

Notes

  • This example uses bcrypt for password hashing, ensuring user passwords are stored securely.
  • Consider implementing session management or JWT for a complete authentication system.

Example 3: CRUD Operations on Products

Context

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}`);
});

Notes

  • This API is a great starting point for any e-commerce application, allowing you to manage product inventory.
  • You can expand this example by adding validation, error handling, and a database for persistent storage.

Conclusion

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!