0
0
Expressframework~5 mins

Resource-based URL design in Express

Choose your learning style9 modes available
Introduction

Resource-based URL design helps organize web addresses so they clearly show what data or action they relate to. It makes websites easier to understand and use.

When building a web API to manage users, products, or orders.
When you want URLs that are easy to read and remember.
When designing routes that follow REST principles for clarity.
When you want to separate different data types with clear paths.
When you want to make your app easier to maintain and extend.
Syntax
Express
app.METHOD('/resource/:id', handlerFunction)

METHOD is the HTTP method like GET, POST, PUT, DELETE.

Use :id to capture a specific resource identifier from the URL.

Examples
Get a list of all users.
Express
app.get('/users', (req, res) => { /* list users */ })
Get details of a single user by their ID.
Express
app.get('/users/:id', (req, res) => { /* get user by id */ })
Create a new user resource.
Express
app.post('/users', (req, res) => { /* create new user */ })
Update an existing user by ID.
Express
app.put('/users/:id', (req, res) => { /* update user by id */ })
Sample Program

This Express app uses resource-based URLs for books. You can get all books or a single book by its ID using clear, simple URLs.

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

// List all books
app.get('/books', (req, res) => {
  res.json([{ id: 1, title: 'Book One' }, { id: 2, title: 'Book Two' }]);
});

// Get a book by ID
app.get('/books/:id', (req, res) => {
  const bookId = Number(req.params.id);
  const books = [{ id: 1, title: 'Book One' }, { id: 2, title: 'Book Two' }];
  const book = books.find(b => b.id === bookId);
  if (book) {
    res.json(book);
  } else {
    res.status(404).send('Book not found');
  }
});

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

Use plural nouns for resource names (e.g., /books, /users) to keep URLs consistent.

Keep URLs simple and predictable to help users and developers understand them easily.

Use HTTP methods (GET, POST, PUT, DELETE) to represent actions on resources clearly.

Summary

Resource-based URLs organize web addresses around data items like users or books.

They use clear paths and HTTP methods to show what action happens.

This design makes APIs easier to use and maintain.