Building RESTful APIs with Express

    Aditya
    3 min read 07-06-2024
    Blog Post Image

    Building RESTful APIs with Express

    Express.js is a fast, unopinionated, and minimalist web framework for Node.js. It is widely used to build RESTful APIs, which are essential for modern web applications that interact with backend services.

    To get started with Express, you need to install it via npm:

    npm install express

    Once installed, you can create a basic RESTful API by following these steps:

    const express = require('express');
    const app = express();
    const port = 3000;
    app.use(express.json());
    const books = [
      { id: 1, title: '1984', author: 'George Orwell' },
      { id: 2, title: 'To Kill a Mockingbird', author: 'Harper Lee' },
    ];
    app.get('/api/books', (req, res) => {
      res.json(books);
    });
    app.get('/api/books/:id', (req, res) => {
      const book = books.find(b => b.id === parseInt(req.params.id));
      if (!book) return res.status(404).send('The book with the given ID was not found.');
      res.json(book);
    });
    app.post('/api/books', (req, res) => {
      const book = {
        id: books.length + 1,
        title: req.body.title,
        author: req.body.author,
      };
      books.push(book);
      res.status(201).json(book);
    });
    app.put('/api/books/:id', (req, res) => {
      const book = books.find(b => b.id === parseInt(req.params.id));
      if (!book) return res.status(404).send('The book with the given ID was not found.');
      book.title = req.body.title;
      book.author = req.body.author;
      res.json(book);
    });
    app.delete('/api/books/:id', (req, res) => {
      const book = books.find(b => b.id === parseInt(req.params.id));
      if (!book) return res.status(404).send('The book with the given ID was not found.');
      const index = books.indexOf(book);
      books.splice(index, 1);
      res.json(book);
    });
    app.listen(port, () => {
      console.log(`Example app listening at http://localhost:${port}`);
    });

    In this example, we create a simple RESTful API for managing a list of books. The API supports the following operations:

    • GET `/api/books`: Retrieve all books

    • GET `/api/books/:id`: Retrieve a single book by ID

    • POST `/api/books`: Create a new book

    • PUT `/api/books/:id`: Update an existing book by ID

    • DELETE `/api/books/:id`: Delete a book by ID

    Express makes it easy to build and manage RESTful APIs with its intuitive routing and middleware features. By using Express, you can quickly create robust and scalable backend services for your applications.