Junior — Middle
How to distinguish HTTP methods GET, POST, PUT, PATCH, and DELETE in the context of REST API?
sobes.tech AI
Answer from AI
In REST API, HTTP methods are used for different operations with resources:
- GET — retrieve data. Safe and idempotent method, does not change the server state.
- POST — create a new resource or perform an operation that changes the state. Not idempotent.
- PUT — complete update of a resource. Idempotent, repeated requests with the same data will not change the result.
- PATCH — partial update of a resource. Not necessarily idempotent, depends on implementation.
- DELETE — delete a resource. Idempotent, repeated calls will delete the resource or return that it does not exist.
Example:
| Method | Operation | Idempotency | Usage example |
|---|---|---|---|
| GET | Get data | Yes | Get list of users |
| POST | Create resource | No | Create a new user |
| PUT | Update resource | Yes | Replace user profile |
| PATCH | Partially update | Partially | Update user's email |
| DELETE | Delete resource | Yes | Delete user |
Example in Java using Spring:
@GetMapping("/users/{id}")
public User getUser(@PathVariable String id) { ... }
@PostMapping("/users")
public User createUser(@RequestBody User user) { ... }
@PutMapping("/users/{id}")
public User updateUser(@PathVariable String id, @RequestBody User user) { ... }
@PatchMapping("/users/{id}")
public User patchUser(@PathVariable String id, @RequestBody Map<String, Object> updates) { ... }
@DeleteMapping("/users/{id}")
public void deleteUser(@PathVariable String id) { ... }