Topic: “Building RESTful APIs with Node.js and Express”
Description: How to design and build RESTful APIs using Node.js and Express.
Content:
1. Introduction to RESTful APIs
What is REST: Explain REST (Representational State Transfer) and its principles.
HTTP Methods: Discuss common HTTP methods: GET, POST, PUT, DELETE, PATCH.
2. Setting Up the Project
Project Initialization:
mkdir myapi
cd myapi
npm init -y
npm install express body-parser
Project Structure:
myapi/
├── node_modules/
├── package.json
├── index.js
3. Creating a Simple API
Basic Express Setup:
const express = require(‘express‘);
const bodyParser = require(‘body-parser‘);
const app = express();
const port = 3000;
app.use(bodyParser.json());
app.listen(port, () => {
console.log(`API running at http://localhost:${port}`);
});
4. Defining Routes
Sample Routes:
let books = [];
app.get(‘/books‘, (req, res) => {
res.json(books);
});
app.post(‘/books‘, (req, res) => {
const book = req.body;
books.push(book);
res.status(201).json(book);
});
app.get(‘/books/:id‘, (req, res) => {
const book = books.find(b => b.id === parseInt(req.params.id));
if (book) {
res.json(book);
} else {
res.status(404).send(‘Book not found‘);
}
});
app.put(‘/books/:id‘, (req, res) => {
const index = books.findIndex(b => b.id === parseInt(req.params.id));
if (index !== –1) {
books[index] = req.body;
res.json(books[index]);
} else {
res.status(404).send(‘Book not found‘);
}
});
app.delete(‘/books/:id‘, (req, res) => {
books = books.filter(b => b.id !== parseInt(req.params.id));
res.status(204).send();
});
5. Testing the API
Using Postman or Curl: Demonstrate how to use Postman or Curl to test API endpoints.
Example Tests:
GET /books
POST /books with JSON body {“id”: 1, “title”: “1984”, “author”: “George Orwell”}
GET /books/1
PUT /books/1 with JSON body {“id”: 1, “title”: “Animal Farm”, “author”: “George Orwell”}
DELETE /books/1