Express.js HTTP Methods

Every request your browser or app sends to a server carries an HTTP method. The method tells the server what action the client wants to perform. Express provides a dedicated function for each method. Understanding these methods is essential because they form the foundation of how web applications and APIs communicate.

HTTP Methods: The Library Desk Analogy

Picture a library service desk. Visitors come with different requests: some want to borrow a book, some want to return one, some want to update their member details, and some want to cancel their membership. The librarian handles each request type differently even though the desk (the URL) is the same. HTTP methods work the same way — the URL identifies the resource, and the method identifies the action.

Resource: /books  (the library shelf)

┌────────────┬────────────────────────────────────────┐
│ HTTP Method│ Action                                 │
├────────────┼────────────────────────────────────────┤
│ GET        │ Show me the list of books              │
│ POST       │ Add this new book to the shelf         │
│ PUT        │ Replace this book with a new edition   │
│ PATCH      │ Update just the title of this book     │
│ DELETE     │ Remove this book from the shelf        │
└────────────┴────────────────────────────────────────┘

GET: Retrieve Data

GET fetches data from the server. No data is modified. Visiting a web page, loading a product list, and reading a user profile are all GET requests. Browsers send a GET request every time you type a URL and press Enter.

app.get('/users', (req, res) => {
  res.json([
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' }
  ]);
});

GET requests do not carry a body. Any data sent to the server goes in the URL as query parameters (covered in a later topic).

POST: Send New Data

POST sends data to the server to create something new. Submitting a registration form, uploading a photo, and placing an order are all POST requests. The data travels in the request body, hidden from the URL.

app.use(express.json()); // Needed to read JSON request bodies

app.post('/users', (req, res) => {
  const newUser = req.body;
  // Save newUser to database...
  res.status(201).json({ message: 'User created', user: newUser });
});

Status code 201 means "Created." Use it instead of 200 when a new resource is successfully created.

PUT: Replace a Resource Completely

PUT replaces an entire resource with new data. If you PUT a user object, the server replaces all fields of that user with what you sent, even if some fields are empty. Nothing carries over from the old version.

app.put('/users/:id', (req, res) => {
  const userId = req.params.id;
  const updatedUser = req.body;
  // Replace the entire user record in the database...
  res.json({ message: `User ${userId} replaced`, user: updatedUser });
});

PATCH: Update Part of a Resource

PATCH updates only the specific fields you send. If a user changes their email address, you PATCH just the email field. All other fields stay the same. PATCH is more efficient than PUT when only a small change is needed.

┌────────────────────────────────────────────────────────┐
│           PUT vs PATCH: The Difference                 │
├────────────────────┬───────────────────────────────────┤
│       PUT          │            PATCH                  │
├────────────────────┼───────────────────────────────────┤
│ Replace entire     │ Update only specific fields       │
│ record             │                                   │
│                    │                                   │
│ Send all fields,   │ Send only changed fields          │
│ even unchanged     │                                   │
│                    │                                   │
│ Missing fields     │ Missing fields keep old values    │
│ become empty       │                                   │
└────────────────────┴───────────────────────────────────┘
app.patch('/users/:id', (req, res) => {
  const userId = req.params.id;
  const changes = req.body; // Only changed fields arrive here
  // Merge changes into existing user record...
  res.json({ message: `User ${userId} partially updated` });
});

DELETE: Remove a Resource

DELETE tells the server to remove the specified resource. Deleting an account, removing a post, and clearing a cart item are all DELETE requests.

app.delete('/users/:id', (req, res) => {
  const userId = req.params.id;
  // Remove user from database...
  res.json({ message: `User ${userId} deleted` });
});

Building a Complete CRUD API

CRUD stands for Create, Read, Update, Delete — the four basic database operations. Every HTTP method maps to one CRUD operation. Here is a complete example for a /products resource:

const express = require('express');
const app = express();
app.use(express.json());

// READ all products
app.get('/products', (req, res) => {
  res.json([{ id: 1, name: 'Laptop' }, { id: 2, name: 'Mouse' }]);
});

// READ one product
app.get('/products/:id', (req, res) => {
  res.json({ id: req.params.id, name: 'Laptop' });
});

// CREATE a product
app.post('/products', (req, res) => {
  res.status(201).json({ message: 'Product added', data: req.body });
});

// UPDATE entire product
app.put('/products/:id', (req, res) => {
  res.json({ message: `Product ${req.params.id} replaced`, data: req.body });
});

// UPDATE part of product
app.patch('/products/:id', (req, res) => {
  res.json({ message: `Product ${req.params.id} updated`, changes: req.body });
});

// DELETE a product
app.delete('/products/:id', (req, res) => {
  res.json({ message: `Product ${req.params.id} deleted` });
});

app.listen(3000);

CRUD to HTTP Method Mapping

┌────────────────────────────────────────────────────────────┐
│            CRUD → HTTP Method → Express Function           │
├──────────┬──────────────┬─────────────────────────────────-┤
│ CREATE   │ POST         │ app.post('/resource', handler)   │
│ READ     │ GET          │ app.get('/resource', handler)    │
│ UPDATE   │ PUT / PATCH  │ app.put('/resource/:id', ...)    │
│ DELETE   │ DELETE       │ app.delete('/resource/:id', ...) │
└──────────┴──────────────┴──────────────────────────────────┘

HEAD: Like GET Without the Body

HEAD works exactly like GET but the server returns only the headers, not the body. Clients use HEAD to check if a resource exists or when it was last modified without downloading the full content. Express automatically supports HEAD for every GET route you define.

OPTIONS: Ask What's Allowed

The OPTIONS method asks the server which HTTP methods it allows for a given URL. Browsers use OPTIONS automatically in a process called a "preflight request" when your frontend JavaScript makes a cross-origin request (calling an API on a different domain). Express handles OPTIONS through CORS middleware, which you will explore in the security topics.

Idempotent vs Non-Idempotent Methods

Some HTTP methods produce the same result no matter how many times you call them. These are called idempotent.

┌─────────────────────────────────────────────────────────┐
│             Method Safety and Idempotency               │
├────────────┬──────────────┬─────────────────────────────┤
│ Method     │ Safe (read-  │ Idempotent (same result     │
│            │ only)?       │ every time)?                │
├────────────┼──────────────┼─────────────────────────────┤
│ GET        │ Yes          │ Yes                         │
│ HEAD       │ Yes          │ Yes                         │
│ POST       │ No           │ No (creates new each time)  │
│ PUT        │ No           │ Yes (replaces same resource)│
│ PATCH      │ No           │ No (depends on logic)       │
│ DELETE     │ No           │ Yes (deleting again = same) │
└────────────┴──────────────┴─────────────────────────────┘

Knowing whether a method is idempotent helps you design APIs that behave predictably, especially when network errors cause clients to retry requests.

Summary

HTTP methods define the action a client wants to perform on a resource. GET retrieves data. POST creates new data. PUT replaces an entire resource. PATCH updates specific fields. DELETE removes a resource. Together they form the CRUD operations: Create (POST), Read (GET), Update (PUT/PATCH), and Delete (DELETE). Express provides app.get(), app.post(), app.put(), app.patch(), and app.delete() to handle each method. Using the correct method for each action keeps your API predictable and follows web standards.

Leave a Comment

Your email address will not be published. Required fields are marked *