Skip to main content
Advertisement

3.2 HTTP Methods (GET, POST, PUT, DELETE)

The core principle of REST API design is "Do not indicate the action (behavior) in the URL; distinguish it by the HTTP method." Spring Boot provides intuitive annotations to seamlessly map these HTTP methods.

1. HTTP Method Mapping Annotations

In the past, developers had to write long, complex configuration strings like @RequestMapping(value = "/users", method = RequestMethod.GET). However, nowadays, intuitively abbreviated dedicated annotations tailored to each specific purpose are actively used.

Merely typing a URL into a browser address bar and hitting enter is fundamentally a flawless GET request.

HTTP MethodSpring AnnotationCore Role Requested of Server
GET@GetMapping** Read**(Retrieve) resources. Used when requesting data.
POST@PostMapping** Create**resources. Used when saving new data to the server.
PUT / PATCH@PutMapping / @PatchMapping** Update**resources. Used when modifying existing data entirely or partially.
DELETE@DeleteMapping** Delete**resources. Used when removing data.

2. REST API Controller Example

Here is a perfectly sound REST controller example handling a uniform User entity systematically. Even if frontends utilize the exact identical uniform /api/users URL consistently, the actual executed Java block code differs entirely depending on the incoming HTTP method.

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {

// 1. Read (GET /api/users)
@GetMapping
public String getUsers() {
return "Successfully retrieving and returning the list of 100 users.";
}

// 2. Create (POST /api/users)
@PostMapping
public String createUser() {
return "Successfully created a brand new user explicitly natively within the database.";
}

// 3. Update (PUT /api/users)
@PutMapping
public String updateUser() {
return "Updated existing user information.";
}

// 4. Delete (DELETE /api/users)
@DeleteMapping
public String deleteUser() {
return "Permanently destroyed user.";
}
}

Designing differently by only changing the behavior (method) for an identical resource (URL) is called RESTful Design.

3. Catching Variables in the URL (@PathVariable)

What if you want to retrieve exactly only user number 5, rather than all users? In this case, you send variables embedded directly strictly into the URL path. This is elegantly captured using the @PathVariable annotation.

@RestController
@RequestMapping("/api/users")
public class UserController {

// GET /api/users/5
@GetMapping("/{id}")
public String getUserById(@PathVariable("id") Long id) {
return "Successfully retrieved user number " + id;
}
}

Use curly braces { } properly to denote variable path parameters. The name inside the braces and @PathVariable("name") must perfectly match identically to effectively inject the value into the Java code.

Advertisement