Node.js Restful API

A RESTful API in Node.js is an application interface that adheres to REST principles, allowing users to interact with resources via standard HTTP methods. Node.js, often paired with frameworks like Express, is ideal for building scalable and efficient RESTful APIs.

 

Key Features of RESTful APIs

  1. Uses standard HTTP methods: GET, POST, PUT, DELETE.
  2. Operates on resource-based URLs.
  3. Stateless communication between client and server.
  4. Supports JSON format for data exchange.

 

Setting Up a Basic RESTful API

Installing Required Modules

Initialize the project:

npm init -y  

Install Express:

npm install express  

Code Example

Create server.js:

const express = require('express');  
const app = express();  

// Middleware to parse JSON requests  
app.use(express.json());  

// Sample in-memory data  
let books = [  
  { id: 1, title: '1984', author: 'George Orwell' },  
  { id: 2, title: 'To Kill a Mockingbird', author: 'Harper Lee' }  
];  

// GET: Fetch all books  
app.get('/books', (req, res) => {  
  res.json(books);  
});  

// POST: Add a new book  
app.post('/books', (req, res) => {  
  const book = req.body;  
  books.push({ id: books.length + 1, ...book });  
  res.status(201).json(book);  
});  

// PUT: Update a book  
app.put('/books/:id', (req, res) => {  
  const id = parseInt(req.params.id);  
  const updatedBook = req.body;  
  books = books.map(book => (book.id === id ? { id, ...updatedBook } : book));  
  res.json(updatedBook);  
});  

// DELETE: Remove a book  
app.delete('/books/:id', (req, res) => {  
  const id = parseInt(req.params.id);  
  books = books.filter(book => book.id !== id);  
  res.status(204).send();  
});  

// Start the server  
const PORT = 3000;  
app.listen(PORT, () => {  
  console.log(`Server is running on http://localhost:${PORT}`);  
});  

 

Testing the API

GET Request:

curl http://localhost:3000/books  

POST Request:

curl -X POST -H "Content-Type: application/json" -d '{"title":"New Book","author":"Author Name"}' http://localhost:3000/books  

PUT Request:

curl -X PUT -H "Content-Type: application/json" -d '{"title":"Updated Book","author":"Updated Author"}' http://localhost:3000/books/1  

DELETE Request:

curl -X DELETE http://localhost:3000/books/1  

 

Summary

Node.js makes it simple to build RESTful APIs with frameworks like Express. By following REST principles and leveraging Node.js's efficiency, developers can create APIs that are scalable, easy to maintain, and perfect for modern web and mobile applications