Can you explain when to use each HTTP method in the context of RESTful APIs?

Each HTTP method in a RESTful API maps to a specific type of operation on a resource, mirroring standard CRUD semantics.

Key Points: • GET retrieves a resource or collection and must not have side effects (safe and idempotent). • POST creates a new resource; calling it twice can create two records, so it is not idempotent. • PUT replaces a resource entirely and is idempotent -- calling it repeatedly with the same body yields the same result. • PATCH updates part of a resource, changing only the fields provided. • DELETE removes a resource and is idempotent, since deleting an already-deleted resource has no further effect.

Example: For a /users/5 resource, GET /users/5 fetches the user, PUT /users/5 replaces the whole record, PATCH /users/5 updates just the email field, and DELETE /users/5 removes the account.

Code Example:

@GetMapping("/{id}")
public UserDto get(@PathVariable Long id) { ... }

@PutMapping("/{id}")
public UserDto replace(@PathVariable Long id, @RequestBody UserDto dto) { ... }

@PatchMapping("/{id}")
public UserDto update(@PathVariable Long id, @RequestBody Map<String, Object> fields) { ... }

@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) { ... }

Interview Tip: A concise interview answer is:

"GET reads without side effects, POST creates a new resource, PUT replaces a resource entirely and is idempotent, PATCH applies a partial update, and DELETE removes the resource. Mapping these onto CRUD keeps the API predictable and consistent with REST conventions."