0
0
Expressframework~5 mins

Why REST principles matter in Express

Choose your learning style9 modes available
Introduction

REST principles help make web services simple, fast, and easy to use. They guide how servers and clients talk clearly and predictably.

Building a web API that many different apps will use
Creating a service that needs to be easy to understand and maintain
Designing a system where clients can cache responses to improve speed
Making sure your service works well with web browsers and mobile apps
Wanting to separate client and server so they can evolve independently
Syntax
Express
GET /resources - to read data
POST /resources - to create data
PUT /resources/:id - to update data
DELETE /resources/:id - to delete data
Use HTTP methods (GET, POST, PUT, DELETE) to represent actions clearly.
Use URLs to represent resources (things) instead of actions.
Examples
These URLs and methods show how to get all books, add a new book, update book 123, and delete book 123.
Express
GET /books
POST /books
PUT /books/123
DELETE /books/123
Access or add orders for user 45 using clear resource paths.
Express
GET /users/45/orders
POST /users/45/orders
Sample Program

This Express app follows REST principles by using HTTP methods and clear URLs to manage books. It shows how clients can get, add, update, and delete books easily.

Express
import express from 'express';
const app = express();
app.use(express.json());

// Sample data
let books = [{ id: 1, title: 'Learn REST' }];

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

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

// Update a book
app.put('/books/:id', (req, res) => {
  const id = Number(req.params.id);
  const book = books.find(b => b.id === id);
  if (!book) return res.status(404).send('Book not found');
  book.title = req.body.title;
  res.json(book);
});

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

app.listen(3000, () => console.log('Server running on http://localhost:3000'));
OutputSuccess
Important Notes

Following REST makes your API predictable and easier for others to use.

Use proper HTTP status codes to tell clients what happened (like 201 for created, 404 for not found).

Keep URLs simple and focused on resources, not actions.

Summary

REST principles help build clear and easy-to-use web services.

Use HTTP methods and resource URLs to communicate actions and data.

Following REST improves maintainability and client compatibility.