Book Lover’s Dream: How a Custom Book API Changed My Reading Life
Turning Pages to Turning Codes
As a book fanatic, my collection of books has grown substantially over the years. With stacks of novels, biographies, and non-fiction scattered throughout my home, it became increasingly difficult to keep track of what I’ve read, what I haven’t, and which ones were my absolute favorites. Determined to bring some order to my literary chaos, I decided to design my very own Book API. This API has not only helped me organize my books but has also provided me with an efficient way to manage and personalize my reading experience.
The Problem: Too Many Books, Not Enough Organization
My love for books is boundless, but managing a vast collection can be a daunting task. I needed a way to:
- Keep a Comprehensive List: Have a central repository for all my books.
- Track Reading Status: Easily see which books I’ve read and which ones are still waiting to be explored.
- Add Personal Notes: Include summaries and personal comments on the books I’ve read.
- Mark Favorites: Highlight my favorite books for quick access.
The Solution: Creating the Book API
To tackle these challenges, I developed a Book API using Node.js and Express. This API allows me to perform various actions such as adding new books, updating existing ones, marking books as read or unread, and even tagging my favorites. Here’s how I did it:
Designing the API
I started designing the API. The API includes endpoints for retrieving all books, read books, unread books, and favorite books, as well as adding, updating, and deleting books.
GET /books - Retrieve a list of all books.
GET /books/read - Retrieve read books.
GET /books/unread - Retrieve unread books.
GET /books/:id - Retrieve a specific book by ID.
POST /books - Add a new book.
PUT /books/:id - Update an existing book.
GET /books/favorites - Retrieve favorite books.
POST /books/favorites/:id - Mark a book as favorite.
PUT /books/summary/:id - Update your thoughts of existing book wrt id.
PUT /books/comments/:id - Update your comments of existing book wrt id.
DELETE /books/:id - Delete a book.
Step 1: Setting Up the Environment
If you haven’t set up your environment yet, follow these initial steps:
- Install Node.js: Download and install Node.js from nodejs.org.
- Create a Project Directory: Create a new directory for your project and navigate into it.
mkdir books-api
cd books-api
Initialize a New Node.js Project: Run the following command to create a package.json
file.
npm init -y
Install Necessary Packages:
npm install express body-parser
Step 2: Implementing the API
Create a new file named app.js
and add the following code to implement the API with the new functionalities:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
app.use(bodyParser.json());
let books = [
{ id: 1, title: '1984', author: 'George Orwell', year: 1949, read: true, summary: '', comments: '', favorite: false },
{ id: 2, title: 'To Kill a Mockingbird', author: 'Harper Lee', year: 1960, read: false, summary: '', comments: '', favorite: false },
{ id: 3, title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', year: 1925, read: true, summary: '', comments: '', favorite: false },
];
// Retrieve a list of books
app.get('/books', (req, res) => {
res.json(books);
});
// Retrieve read books
app.get('/books/read', (req, res) => {
const readBooks = books.filter(book => book.read);
res.json(readBooks);
});
// Retrieve unread books
app.get('/books/unread', (req, res) => {
const unreadBooks = books.filter(book => !book.read);
res.json(unreadBooks);
});
// Retrieve favorite books
app.get('/books/favorites', (req, res) => {
const favoriteBooks = books.filter(book => book.favorite);
res.json(favoriteBooks);
});
// Retrieve a specific book by ID
app.get('/books/:id', (req, res) => {
const book = books.find(b => b.id === parseInt(req.params.id));
if (!book) return res.status(404).send('Book not found');
res.json(book);
});
// Add a new book
app.post('/books', (req, res) => {
const book = {
id: books.length + 1,
title: req.body.title,
author: req.body.author,
year: req.body.year,
read: req.body.read || false,
summary: req.body.summary || '',
comments: req.body.comments || '',
favorite: req.body.favorite || false
};
books.push(book);
res.status(201).json(book);
});
// Update an existing book
app.put('/books/:id', (req, res) => {
const book = books.find(b => b.id === parseInt(req.params.id));
if (!book) return res.status(404).send('Book not found');
book.title = req.body.title;
book.author = req.body.author;
book.year = req.body.year;
book.read = req.body.read;
book.summary = req.body.summary;
book.comments = req.body.comments;
book.favorite = req.body.favorite;
res.json(book);
});
// Delete a book
app.delete('/books/:id', (req, res) => {
const bookIndex = books.findIndex(b => b.id === parseInt(req.params.id));
if (bookIndex === -1) return res.status(404).send('Book not found');
books.splice(bookIndex, 1);
res.status(204).send();
});
// Mark a book as favorite
app.put('/books/favorite/:id', (req, res) => {
const bookId = parseInt(req.params.id);
const { favorite } = req.body;
const book = books.find(b => b.id === bookId);
if (book) {
book.favorite = favorite;
res.status(200).json(book);
} else {
res.status(404).json({ message: "Book not found" });
}
});
// Update the summary of existing book
app.put('/books/summary/:id', (req, res) => {
const bookId = parseInt(req.params.id);
const { summary } = req.body;
const book = books.find(b => b.id === bookId);
if (book) {
book.summary = summary;
res.status(200).json(book);
} else {
res.status(404).json({ message: "Book not found" });
}
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Step 3: Running the API
Start the server by running the following command in your terminal:
node app.js
Your API should now be running on http://localhost:3000
Step 4: Testing the API with Postman
1. GET /books
- Open Postman: Open the Postman application.
- Set Request Type to GET: Select
GET
from the dropdown menu. - Enter URL: Type
http://localhost:3000/books
- Send Request: Click
Send
to see the list of all books.
[
{
"id": 1,
"title": "1984",
"author": "George Orwell",
"year": 1949,
"read": true,
"summary": "A dystopian social science fiction novel and cautionary tale about the dangers of totalitarianism.",
"comments": "A must-read classic.",
"favorite": true
},
{
"id": 2,
"title": "To Kill a Mockingbird",
"author": "Harper Lee",
"year": 1960,
"read": false,
"summary": "",
"comments": "",
"favorite": false
},
{
"id": 3,
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"year": 1925,
"read": true,
"summary": "A novel about the American dream and the roaring twenties.",
"comments": "A poignant critique of the American dream.",
"favorite": false
}
]
2. GET /books/read
- Open a New Tab in Postman: Click the
+
button. - Set Request Type to GET: Select
GET
from the dropdown menu. - Enter URL: Type
http://localhost:3000/books/read
- Send Request: Click
Send
to see the list of read books.
3. GET /books/unread
- Open a New Tab in Postman: Click the
+
button. - Set Request Type to GET: Select
GET
from the dropdown menu. - Enter URL: Type
http://localhost:3000/books/unread
- Send Request: Click
Send
to see the list of unread books.
4. GET /books/
- Open a New Tab in Postman: Click the
+
button. - Set Request Type to GET: Select
GET
from the dropdown menu. - Enter URL: Type
http://localhost:3000/books/1
(replace1
with the desired book ID). - Send Request: Click
Send
to see the specific book details.
5. POST /books
- Open a New Tab in Postman: Click the
+
button. - Set Request Type to POST: Select
POST
from the dropdown menu. - Enter URL: Type
http://localhost:3000/books
- Go to the Body Tab: Select the
Body
tab below the URL bar. - Select raw and JSON: Select
raw
and chooseJSON
. - Enter JSON Data:
{
"title": "The Catcher in the Rye",
"author": "J.D. Salinger",
"year": 1951,
"read": false,
"summary": "",
"comments": "",
"favorite": false
}
We can also send the POST request using curl :
curl -X POST http://localhost:3000/books \
-H "Content-Type: application/json" \
-d '{
"title": "Brave New World",
"author": "Aldous Huxley",
"year": 1932,
"read": false,
"summary": "A dystopian novel set in a futuristic world state.",
"comments": "Looking forward to reading this classic.",
"favorite": false
}'
- Send Request: Click
Send
to add a new book.
6. PUT /books/
- Open a New Tab in Postman: Click the
+
button. - Set Request Type to PUT: Select
PUT
from the dropdown menu. - Enter URL: Type
http://localhost:3000/books/1
(replace1
with the book ID you want to update). - Go to the Body Tab: Select the
Body
tab below the URL bar. - Select raw and JSON: Select
raw
and chooseJSON
. - Enter JSON Data:
{
"id": 1,
"title": "1984",
"author": "George Orwell",
"year": 1949,
"read": true,
"summary": "A dystopian social science fiction novel and cautionary tale about the dangers of totalitarianism.",
"comments": "A must-read classic.",
"favorite": true
}
- Send Request: Click
Send
to update the book.
7. DELETE /books/:id
- Open a New Tab in Postman: Click the
+
button. - Set Request Type to DELETE: Select
DELETE
from the dropdown menu. - Enter URL: Type
http://localhost:3000/books/1
(replace1
with the book ID you want to delete). - Send Request: Click
Send
to delete the book.
8. GET /books/favorites
- Open a New Tab in Postman: Click the
+
button. - Set Request Type to GET: Select
GET
from the dropdown menu. - Enter URL: Type
http://localhost:3000/books/favorites
. - Send Request: Click
Send
to see the list of favorite books.
9. PUT /books/favorites/:id
- Open Postman: Open the Postman application.
- Set Request Type to PUT: Select
PUT
from the dropdown menu. - Enter URL: Type
http://localhost:3000/books/favorites/1
(replace1
with the ID of the book you want to mark as favorite). - Send Request: Click
Send
to mark the book as a favorite. - Using Curl Request:
curl -X PUT http://localhost:3000/books/favorite/1 \
-H "Content-Type: application/json" \
-d '{
"favorite": true
}'
10. PUT /books/summary/:id
- Open Postman: Open the Postman application.
- Set Request Type to PUT: Select
PUT
from the dropdown menu. - Enter URL: Type
http://localhost:3000/books/summary/1
(replace1
with the ID of the book you want to change the summary). - Send Request: Click
Send
to mark the book as a favorite. - Using Curl Request:
curl -X PUT http://localhost:3000/books/summary/1 \
-H "Content-Type: application/json" \
-d '{
"summary": "A gripping and thought-provoking dystopian novel about a totalitarian regime."
}'
Response:
{
"id": 1,
"title": "1984",
"author": "George Orwell",
"year": 1949,
"read": true,
"summary": "A gripping and thought-provoking dystopian novel about a totalitarian regime.",
"comments": "An eye-opening read.",
"favorite": true
}
In the similar way, we can also update the comments section of the book.
With this API, I can now effortlessly manage my book collection. I can quickly see which books I’ve read, which ones are on my to-read list, and mark my favorites. Adding personal summaries and comments has also made my reading experience more enriching. This custom solution has brought a much-needed order to my literary world and made my life as a book fanatic a whole lot easier. I highly recommend building a similar API.
Happy Code-Reading!! 😁