Node.js RESTful API Development-120%
What is RESTful API Development in Node.js
With Express.js, RESTful APIs are defined by defining routes and endpoints that adhere to Representational State Transfer (REST) principles.
Generally, RESTful APIs use HTTP methods like GET, POST, PUT and DELETE to perform CRUD operations on resources.
Designing RESTful APIs with Express.js:
Resource Naming: Each resource should be represented by a unique URI (Uniform Resource Identifier).
HTTP Methods: The CRUD operations on resources should be done by use of http methods namely GET, POST, PUT and DELETE.
Response Codes: Appropriate HTTP status codes should be used to indicate the outcome of API requests.
Request and Response Formats: Data sent to and received from an API should be in standard formats like JSON.
Implementing CRUD Operations:
Let's create an example RESTful API for managing a collection of books:
const express = require('express');
const app = express();
// Middleware for parsing JSON request bodies
app.use(express.json());
let books = [
{ id: 1, title: 'Book 1', author: 'Author 1' },
{ id: 2, title: 'Book 2', author: 'Author 2' }
];
// GET all books
app.get('/books', (req, res) => {
res.json(books);
});
// GET a specific book by ID
app.get('/books/:id', (req, res) => {
const bookId = parseInt(req.params.id);
const book = books.find(book => book.id === bookId);
if (book) {
res.json(book);
} else {
res.status(404).json({ message: 'Book not found' });
}
});
// POST a new book
app.post('/books', (req, res) => {
const { title, author } = req.body;
const newBook = { id: books.length + 1, title, author };
books.push(newBook);
res.status(201).json(newBook);
});
// PUT (update) an existing book by ID
app.put('/books/:id', (req, res) => {
const bookId = parseInt(req.params.id);
const { title, author } = req.body;
const index = books.findIndex(book => book.id === bookId);
if (index !== -1) {
books[index] = { id: bookId, title, author };
res.json(books[index]);
} else {
res.status(404).json({ message: 'Book not found' });
}
});
// DELETE a book by ID
app.delete('/books/:id', (req, res) => {
const bookId = parseInt(req.params.id);
const index = books.findIndex(book => book.id === bookId);
if (index !== -1) {
books.splice(index, 1);
res.status(204).send();
} else {
res.status(404).json({ message: 'Book not found' });
}
});
const port = 3000;
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Handling Request Parameters, Query Strings, and Request Bodies:
Request Parameters (req.params): These are used for accessing parameters within the URL path such as /books/:id.
Query Strings (req.query): These are used for accessing parameters within the URL query string e.g., /books?category=fiction.
Request Body (req.body): This is used to access data passed in the request body such as JSON data for creating or updating resources.