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

CodeMeaningUse Case
200OKSuccessful GET/PUT
201CreatedSuccessful POST
400Bad RequestInvalid Data
404Not FoundResource doesn't exist
500Server ErrorInternal bug