Node.js Masterclass
High-Performance Backends01.Home02.Introduction03.Environment Setup04.Modules & Exports05.File System (fs)06.Path & OS Modules07.Buffer & Streams08.Events & EventEmitter09.HTTP Module10.NPM & Package.json11.Express.js Fundamentals12.Express Routing13.Express Middleware14.RESTful API Development15.Asynchronous Programming16.Error Handling17.Database with Mongoose18.Authentication with JWT19.Environment Variables20.Testing with Jest21.Deployment & PM2
RESTful API Development
REST (Representational State Transfer) is an architectural style for designing networked applications. In this chapter, we'll build a basic CRUD API for a "Books" collection.
1. HTTP Methods in REST
- GET /books: Retrieve all books.
- GET /books/:id: Retrieve a single book.
- POST /books: Create a new book.
- PUT /books/:id: Update an existing book.
- DELETE /books/:id: Delete a book.
2. Implementation Example
const express = require('express');
const app = express();
app.use(express.json());
let books = [
{ id: 1, title: 'Node.js Guide', author: 'Pradeep' }
];
// GET All
app.get('/api/books', (req, res) => {
res.json(books);
});
// POST Create
app.post('/api/books', (req, res) => {
const newBook = { id: Date.now(), ...req.body };
books.push(newBook);
res.status(201).json(newBook);
});
// DELETE
app.delete('/api/books/:id', (req, res) => {
books = books.filter(b => b.id !== parseInt(req.params.id));
res.status(204).send();
});3. Status Codes to Remember
| Code | Meaning | Use Case |
|---|---|---|
| 200 | OK | Successful GET/PUT |
| 201 | Created | Successful POST |
| 400 | Bad Request | Invalid Data |
| 404 | Not Found | Resource doesn't exist |
| 500 | Server Error | Internal bug |