Skip to content

Express: Book Management

Design and implement an Express.js application to manage a list of books. Each book must have an id, title, and author. Initialize the application with at least two predefined books stored in an in-memory array. The application must support the following functionalities:

  • GET /books: This route should return the list of all books.

  • POST /books: This route should accept a new book's title and author in the request body, assign it a unique id, add it to the array, and return a confirmation message.

  • PUT /books/:id: This route should update an existing book’s title and/or author based on the id provided in the URL. Only the fields present in the request body should be updated. If the book is not found, return a 404 status with an appropriate message.

  • DELETE /books/:id: This route should remove a book by its id. If the book does not exist, return a 404 error. Otherwise, return a success message indicating which book was deleted.

  • Ensure proper use of express.json() middleware and return all responses in plain text format using res.send().

app.js

js
import express from 'express';

const app = express();
const PORT = 3000;

// Middleware to parse JSON bodies
app.use(express.json());

// In-memory data store for books
let books = [
    { id: 1, title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },
    { id: 2, title: 'To Kill a Mockingbird', author: 'Harper Lee' }
];

// --- Routes ---

// GET /books - Retrieve all books
app.get('/books', (req, res) => {

	res.json(Books); // Works, sends JSON

	// Not needed but to Send as Plain text 
    // Formatting the array as readable string
    const responseText = books.map(b => `ID: ${b.id}, 
		    Title: ${b.title}, 
		    Author: ${b.author}`).join('\n');
    res.send(responseText);
});

// POST /books - Add a new book

// Variable to manage the next unique ID
let nextId = 3;

app.post('/books', (req, res) => {
    const { title, author } = req.body;

	if(!title || !author){
		return res.status(400).send("Both title and author are required");
	}
    const newBook = { id: nextId++, title, author };
    books.push(newBook);
    res.status(201).send(`Book added successfully with ID: ${newBook.id}`);
});

// PUT /books/:id - Update an existing book
app.put('/books/:id', (req, res) => {
    const bookId = parseInt(req.params.id, 10);
    const { title, author } = req.body;
    
    const book = books.find(b => b.id === bookId);

    if (!book) {
        return res.status(404).send('Error: Book not found.');
    }

    if (title !== undefined) {
        book.title = title;
    }
    if (author !== undefined) {
        book.author = author;
    }

    res.send(`Book with ID: ${bookId} updated successfully.`);
});

// DELETE /books/:id - Remove a book by its ID
app.delete('/books/:id', (req, res) => {
    const bookId = parseInt(req.params.id, 10);
    const bookIndex = books.findIndex(b => b.id === bookId);

    if (bookIndex === -1) {
        return res.status(404).send('Error: Book not found.');
    }

    const [deletedBook] = books.splice(bookIndex, 1);
    res.send(`Book '${deletedBook.title}' with ID: ${bookId} was deleted successfully.`);
});

// Start the server
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

Test the API with Postman

Get all books (GET)

  1. Set the method to GET and the URL to http://localhost:3000/books.

  2. Click Send. You will see the list of books as plain text in the response body.

Add a new book (POST)

  1. Set the method to POST and the URL to http://localhost:3000/books.

  2. Go to the Body tab, select raw, and choose JSON.

  3. Enter the new book's data:

json
{
	"title": "1984",
	"author": "George Orwell"
}
  1. Click Send. You will get a plain text confirmation message.

Update a book's title (PUT)

  1. Set the method to PUT and the URL to http://localhost:3000/books/1.

  2. Go to the Body tab, select raw, and choose JSON.

  3. Enter only the title to update it:

json
{
	"title": "The Great Gatsby (Revised Edition)"
}
  1. Click Send. You will receive a plain text success message.

Delete a book (DELETE)

  1. Set the method to DELETE and the URL to http://localhost:3000/books/2.

  2. Click Send. You will receive a success message confirming which book was deleted.

Attempt to delete a non-existent book (DELETE)

  1. Change the URL to an ID that doesn't exist, like: http://localhost:3000/books/99.

  2. Click Send. The API will return a 404 Not Found status with the plain text error message.

Made with ❤️ for students, by a fellow learner.