Let's build a simple Web API using Node.js and Express to manage a collection of books. The API will allow users to perform CRUD (Create, Read, Update, Delete) operations on books.
We'll assume that the data for books is stored in memory (as an array) for simplicity. In a real-world application, this data would likely be stored in a database.
Install Node.js and Express:
mkdir books-api
cd books-api
npm init -y
Install Express:
npm install express
Create the API:
app.js (or any name you prefer) to define your API.const express = require('express');
const app = express();
// Middleware to parse JSON bodies
app.use(express.json());
// In-memory book data
let books = [
{ id: 1, title: '1984', author: 'George Orwell', year: 1949 },
{ id: 2, title: 'To Kill a Mockingbird', author: 'Harper Lee', year: 1960 }
];
// 1. CREATE: Add a new book
app.post('/api/books', (req, res) => {
const { title, author, year } = req.body;
if (!title || !author || !year) {
return res.status(400).json({ message: 'Title, author, and year are required' });
}
const newBook = {
id: books.length + 1, // Generate a new ID
title,
author,
year
};
books.push(newBook);
res.status(201).json(newBook);
});
// 2. READ: Get all books
app.get('/api/books', (req, res) => {
res.json(books);
});
// 3. READ: Get a single book by ID
app.get('/api/books/:id', (req, res) => {
const bookId = parseInt(req.params.id);
const book = books.find(b => b.id === bookId);
if (!book) {
return res.status(404).json({ message: 'Book not found' });
}
res.json(book);
});
// 4. UPDATE: Update a book by ID
app.put('/api/books/:id', (req, res) => {
const bookId = parseInt(req.params.id);
const { title, author, year } = req.body;
const bookIndex = books.findIndex(b => b.id === bookId);
if (bookIndex === -1) {
return res.status(404).json({ message: 'Book not found' });
}
const updatedBook = {
id: bookId,
title: title || books[bookIndex].title,
author: author || books[bookIndex].author,
year: year || books[bookIndex].year
};
books[bookIndex] = updatedBook;
res.json(updatedBook);
});
// 5. DELETE: Delete a book by ID
app.delete('/api/books/:id', (req, res) => {
const bookId = parseInt(req.params.id);
const bookIndex = books.findIndex(b => b.id === bookId);
if (bookIndex === -1) {
return res.status(404).json({ message: 'Book not found' });
}
books.splice(bookIndex, 1); // Remove the book from the array
res.status(204).send(); // No content in the response body
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Create (POST):
POST /api/books endpoint is used to create a new book.Example request:
POST http://localhost:3000/api/books
Content-Type: application/json
{
"title": "Brave New World",
"author": "Aldous Huxley",
"year": 1932
}
Read (GET):
GET /api/books endpoint retrieves all books.GET /api/books/:id endpoint retrieves a single book by its id.Example request:
GET http://localhost:3000/api/books
Example response:
[
{ "id": 1, "title": "1984", "author": "George Orwell", "year": 1949 },
{ "id": 2, "title": "To Kill a Mockingbird", "author": "Harper Lee", "year": 1960 }
]
Example request for a single book:
GET http://localhost:3000/api/books/1
Example response:
{ "id": 1, "title": "1984", "author": "George Orwell", "year": 1949 }
Update (PUT):
PUT /api/books/:id endpoint updates an existing book.Example request:
PUT http://localhost:3000/api/books/1
Content-Type: application/json
{
"title": "Nineteen Eighty-Four",
"author": "George Orwell",
"year": 1949
}
Example response:
{ "id": 1, "title": "Nineteen Eighty-Four", "author": "George Orwell", "year": 1949 }
Delete (DELETE):
DELETE /api/books/:id endpoint deletes a book by its id.204 No Content status is returned, indicating that the operation was successful but there is no response body.Example request:
DELETE http://localhost:3000/api/books/1
Example response:
Status: 204 No Content
You can test the API using Postman (a popular tool for API testing) or cURL (command-line tool for transferring data).
For example, to test the Create operation using cURL:
curl -X POST http://localhost:3000/api/books \
-H "Content-Type: application/json" \
-d '{"title": "Brave New World", "author": "Aldous Huxley", "year": 1932}'
To test the Read operation (getting all books):
curl http://localhost:3000/api/books
This simple Node.js + Express Web API example demonstrates how to create CRUD operations to manage resources (in this case, books). The API supports creating, reading, updating, and deleting books, and it returns responses in JSON format, which is the standard for most modern web APIs. This pattern can be expanded to include features like authentication, validation, and database integration.
Open this section to load past papers