Hello! In this article, we'll be creating a simple book API using Express.js. This API can be the foundation for building more complex projects such as a book review site, a library catalog, or even a bookstore.
Prerequisites:
Basic knowledge of JavaScript.
Node.js installed on your pc.
Setting Up:
Start by creating a new directory for your project and initializing a Node.js application:
mkdir book-api && cd book-api npm init -y
Next, let's install the required packages:
npm install express
The Code:
Create an index.js file. This will house our server and routes:
const express = require('express'); const app = express(); app.use(express.json()); let books = []; app.get('/books', (req, res) => { res.json(books); }); app.post('/books', (req, res) => { const { title, author } = req.body; const newBook = { id: Date.now(), title, author }; books.push(newBook); res.status(201).json(newBook); }); app.put('/books/:id', (req, res) => { const bookId = Number(req.params.id); const { title, author } = req.body; const bookIndex = books.findIndex(book => book.id === bookId); if (bookIndex === -1) return res.status(404).json({ message: "Book not found" }); books[bookIndex] = { id: bookId, title, author }; res.json(books[bookIndex]); }); app.delete('/books/:id', (req, res) => { const bookId = Number(req.params.id); books = books.filter(book => book.id !== bookId); res.status(204).end(); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Testing the API:
You can test this API using tools like Postman or by integrating it into a frontend application.
Conclusion:
Building a basic API with Express.js is straightforward. This simple book API is just the beginning. You can expand it by adding more features, integrating a database, and implementing authentication and authorization.
I hope you found this basic introduction to building an Express.js API helpful! If you enjoyed this guide and would like to delve deeper, give this article some ❤️ (likes). If we get enough interest, I'll create a follow-up post where we'll integrate a database and add authentication to our book API. This way, we can further enhance its features and make it more robust.
Top comments (0)