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 |