🌐 Section 6 · Question #3

What are the main HTTP methods used in REST

In REST architecture, HTTP methods map directly to domain CRUD (Create, Read, Update, Delete) operations:


🟢 Junior Level

HTTP Methods (HTTP Verbs) are standardized protocol commands defined in the RFC 9110 (HTTP Semantics) specification. They inform the server what action a client intends to execute on a target resource identified by a Uniform Resource Identifier (URI).

In REST architecture, HTTP methods map directly to domain CRUD (Create, Read, Update, Delete) operations:

HTTP Method CRUD Equivalent Semantic Purpose Example Request Standard Success Status
GET Read Retrieve a representation of the resource GET /api/v1/products/42 200 OK
POST Create Create a new subordinate resource or trigger an operation POST /api/v1/products 201 Created (with Location)
PUT Update (Replace) Completely replace the target resource PUT /api/v1/products/42 200 OK / 204 No Content
PATCH Update (Partial) Partially update specific fields of the resource PATCH /api/v1/products/42 200 OK / 204 No Content
DELETE Delete Remove the specified resource DELETE /api/v1/products/42 204 No Content
Fundamental REST Design Principle:
• URIs are NOUNS representing domain entities (/orders, /customers/10).
• HTTP Verbs are ACTIONS operating on those nouns (GET, POST, PUT, DELETE).

Spring Boot 3 REST Controller Implementation

package com.example.controller;

import com.example.dto.CreateProductRequest;
import com.example.dto.PatchProductRequest;
import com.example.dto.ProductDto;
import com.example.dto.ReplaceProductRequest;
import com.example.service.ProductService;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.net.URI;
import java.util.List;

@RestController
@RequestMapping("/api/v1/products")
public class ProductController {

    private final ProductService productService;

    public ProductController(ProductService productService) {
        this.productService = productService;
    }

    // 1. GET: Read collection or single resource
    @GetMapping("/{id}")
    public ResponseEntity<ProductDto> getProduct(@PathVariable Long id) {
        return ResponseEntity.ok(productService.findById(id));
    }

    // 2. POST: Create a subordinate resource with Location header
    @PostMapping
    public ResponseEntity<ProductDto> createProduct(@Valid @RequestBody CreateProductRequest req) {
        ProductDto created = productService.create(req);
        URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                .path("/{id}")
                .buildAndExpand(created.id())
                .toUri();
        return ResponseEntity.created(location).body(created); // 201 Created + Location header
    }

    // 3. PUT: Complete resource replacement
    @PutMapping("/{id}")
    public ResponseEntity<ProductDto> replaceProduct(@PathVariable Long id, 
                                                     @Valid @RequestBody ReplaceProductRequest req) {
        return ResponseEntity.ok(productService.replace(id, req));
    }

    // 4. PATCH: Partial field modification
    @PatchMapping("/{id}")
    public ResponseEntity<ProductDto> patchProduct(@PathVariable Long id, 
                                                   @RequestBody PatchProductRequest req) {
        return ResponseEntity.ok(productService.patch(id, req));
    }

    // 5. DELETE: Resource removal
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
        productService.delete(id);
        return ResponseEntity.noContent().build(); // 204 No Content
    }
}

🟡 Middle Level

Method Classification: Safe & Idempotent (RFC 9110)

RFC 9110 classifies HTTP methods into two critical dimensions: Safety and Idempotency.

                        ┌─── Safe (Read-only; causes zero server state modifications):
                        │    GET, HEAD, OPTIONS, TRACE
           ┌── Guarantees┤
           │            └─── Idempotent (N identical executions result in identical server state):
           │                 GET, HEAD, PUT, DELETE, OPTIONS
HTTP Verbs ┤
           │            ┌─── PUT: Complete replacement (all fields required)
           └── Mutations ┼─── PATCH: Partial update (RFC 7386 / RFC 6902)
                        └─── POST: Create / Trigger business process (NON-idempotent)

Comprehensive HTTP Method Matrix

Method Request Body Allowed? Safe? Idempotent? Cacheable by Default?
GET ❌ No ✅ Yes ✅ Yes ✅ Yes
HEAD ❌ No ✅ Yes ✅ Yes ✅ Yes
OPTIONS ❌ No ✅ Yes ✅ Yes ❌ No
POST ✅ Yes ❌ No ❌ No ⚠️ Only with explicit Cache-Control
PUT ✅ Yes ❌ No ✅ Yes ❌ No
PATCH ✅ Yes ❌ No ⚠️ Context-dependent ❌ No
DELETE ⚠️ Discouraged ❌ No ✅ Yes ❌ No

Ancillary Utility Methods: HEAD and OPTIONS

  • HEAD (Metadata Inspection):
    • Executes the exact same request routing, authorization, and header generation as GET, but suppresses the response payload.
    • Primary Use Cases: Verifying if a resource exists (200 OK vs 404 Not Found), checking download size via Content-Length, or testing if a local cached file is stale via ETag / Last-Modified without consuming bandwidth.
  • OPTIONS (Capability Discovery & CORS):
    • Queries the server for allowed communication options for a target URI.
    • Primary Use Case: CORS Preflight in modern browsers. Before executing a non-simple cross-origin request, the browser dispatches an OPTIONS call to verify permissions:
      OPTIONS /api/v1/products HTTP/1.1
      Origin: https://app.example.com
      Access-Control-Request-Method: PUT
      
      HTTP/1.1 204 No Content
      Access-Control-Allow-Origin: https://app.example.com
      Access-Control-Allow-Methods: GET, POST, PUT, DELETE
      

🔴 Senior Level

Semantic Subtleties: PUT vs. PATCH in Production

  1. Strict Contract of PUT (Full Representation Replacement):
    • If a client issues PUT /users/42 with payload {"name": "Alice"}, and the existing database entity had email: "alice@example.com" and status: "ACTIVE", the backend is obligated to set email and status to null or their default values.
    • If the client wishes to retain existing values during a PUT, it must supply the entire resource representation in the request body.
  2. Formal Specifications for PATCH:
    • JSON Merge Patch (RFC 7386): The client sends a partial JSON document. A major challenge in Java is distinguishing between:
      • A field that was omitted from the JSON (must not be altered).
      • A field explicitly passed as null (must be cleared in the database).
      • Solution: Use JsonNullable<T> from org.openapitools.jackson.nullable.JsonNullable.
    • JSON Patch (RFC 6902): The client transmits an array of atomic mutation operations (add, remove, replace, copy, move, test):
      [
        { "op": "replace", "path": "/email", "value": "alice@newmail.com" },
        { "op": "remove", "path": "/phoneNumber" }
      ]
      

Automated Network Retries in Cloud Service Meshes (Envoy / Istio)

Modern distributed systems configure automated retry policies inside proxy sidecars (Envoy, Istio, Linkerd) based strictly on HTTP method semantics:

Client Request ──► [Envoy Sidecar Proxy] ──► [Target Service] (Drops TCP / Returns 503)
                         │
                         ├── If GET, PUT, DELETE: ✅ AUTOMATICALLY RETRIES (Safe / Idempotent)
                         └── If POST: ❌ FORBIDDEN TO RETRY (Risk of duplicate charges/orders!)
  • Safe Retries: For idempotent verbs (GET, PUT, DELETE), proxies can safely execute automated exponential backoff retries without application-level coordination.
  • Unsafe POST Retries: Automatically retrying a failed POST can result in duplicate financial debits or duplicate orders. Safe retries on POST mandate the implementation of an Idempotency-Key header with distributed state storage (e.g., Redis atomics).

Method Tunneling (X-HTTP-Method-Override)

Certain legacy corporate proxy firewalls, API gateways, or legacy HTTP clients permit only GET and POST traffic, blocking PUT, PATCH, and DELETE.

To circumvent these network restrictions, clients tunnel mutations through POST using the X-HTTP-Method-Override header:

POST /api/v1/orders/102 HTTP/1.1
Host: api.example.com
X-HTTP-Method-Override: DELETE

In Spring Boot, method tunneling is enabled by configuring the HiddenHttpMethodFilter bean, which intercepts the request and wraps it in a customized HttpServletRequestWrapper exposing the override verb.


4 Tricky Questions

1. What is the fundamental technical difference between a Safe method and an Idempotent method?

Answer:

  • A method is Safe if its invocation causes zero state modifications on the server (read-only operations: GET, HEAD, OPTIONS). Safe methods have no side effects on domain data and can be invoked arbitrarily by web crawlers or prefetch engines without caution.
  • A method is Idempotent if the side effects of executing $N > 1$ identical requests are identical to the side effect of executing a single request ($f(f(x)) = f(x)$).
  • The Core Distinction: An idempotent method can modify server state, whereas a safe method cannot. For example, DELETE is not safe (it mutates the database by deleting a record), but it is idempotent (calling DELETE 10 times leaves the resource deleted, with the exact same resulting server state as calling it once).

2. If the first call to DELETE /users/42 returns 204 No Content and the second call returns 404 Not Found, does this violate HTTP idempotency?

Answer: No, it does not violate idempotency. According to RFC 9110, idempotency is defined by the resulting state of the resource on the server, not by the HTTP response status code.

  • Prior to the first call: User 42 exists in the database.
  • After the first call: User 42 is deleted (server responds 204 No Content).
  • After the second call: User 42 remains absent from the database (server responds 404 Not Found). Because the state of the system is identical after the 1st request and after the 100th request (User 42 does not exist), the operation is strictly idempotent.

3. What is the practical utility of the HEAD method, and how does it optimize network bandwidth in highload applications?

Answer: The HEAD method instructs the server to process the request identically to a GET (including route matching, security checks, and calculation of response headers such as Content-Length, ETag, and Last-Modified), but completely omit the response body.

  • Bandwidth Optimization: A mobile client or CDN cache can issue a HEAD request to inspect the ETag or Content-Length of a 500 MB video asset. If the client’s local ETag matches the server’s ETag, the client skips the 500 MB download entirely.
  • Resource Existence Verification: Health checks and uptime monitors use HEAD to verify endpoint availability without transferring large payload data.

4. What happens when a client sends a PUT request omitting a field that previously had a value?

Answer: Under strict REST and RFC 9110 semantics, PUT represents a complete resource replacement:

  • The server replaces the existing resource in its entirety with the representation supplied in the payload.
  • Any fields omitted from the payload must be cleared (set to null) or reset to schema default values.
  • If a client intended to modify only a subset of fields while preserving existing values for unspecified attributes, it is an architectural error to use PUT. The client must use PATCH instead.

🎯 Interview Cheat Sheet

30-Second Elevator Pitch

The primary HTTP methods in REST are governed by RFC 9110 and map directly to CRUD operations:

  • GET — Reads resource state (Safe & Idempotent).
  • POST — Creates subordinate resources or triggers operations (Unsafe & Non-idempotent).
  • PUT — Fully replaces target resource (Unsafe & Idempotent).
  • PATCH — Partially updates resource fields (Unsafe & Context-dependent idempotency).
  • DELETE — Removes target resource (Unsafe & Idempotent).

Ancillary methods include HEAD (headers-only metadata inspection) and OPTIONS (communication capability checks and CORS Preflight).


Red Flags (What NOT to Say)

  • ❌ “PUT and PATCH are interchangeable synonyms for updating a resource.” (PUT is full replacement; PATCH is partial modification).
  • ❌ “DELETE is non-idempotent because the second request returns a 404 error instead of 204.” (Idempotency is measured by server state, not the HTTP response code).
  • ❌ “GET can be used to mutate or delete data if it’s faster.” (Violates RFC 9110 safety guarantees; crawlers and caching proxies will destroy data).
  • ❌ “POST requests are automatically retried by load balancers on connection timeout.” (POST is non-idempotent; automatic retries cause duplicate operations unless guarded by an Idempotency-Key).