Home > AI > Backend > SpringBoot >

@PathVariable

Example

1. A Simple Mapping

GET http://localhost:8080/api/employees/1

@RestController
@RequestMapping("api")
public class TestController {
    @GetMapping("/employees/{id}")
    @ResponseBody
    public String getEmployeesById(@PathVariable String id) {
        return "ID: " + id;
    }
}

2. Specifying the Path Variable Name

GET http://localhost:8080/api/employees/1

@GetMapping("/employees/{id}")
    @ResponseBody
    public String getEmployeesByIdWithVariableName(@PathVariable("id") String employeeId) {
        return "ID: " + employeeId;
    }

3. Multiple Path Variables in a Single Request

GET http://localhost:8080/api/employees/1/shark

@GetMapping("/employees/{id}/{name}")
@ResponseBody
public String getEmployeesByIdAndName(@PathVariable String id, @PathVariable String name) {
    return "ID: " + id + ", name: " + name;
}

4. Optional Path Variables

4-1. Setting @PathVariable as Not Required

@GetMapping(value = { "/employees", "/employees/{id}" })
@ResponseBody
public String getEmployeesByIdWithRequiredFalse(@PathVariable(required = false) String id) {
    if (id != null) {
        return "ID: " + id;
    } else {
        return "ID missing";
   }
}

4.2 Using java.util.Optional

@GetMapping(value = { "/employees", "/employees/{id}" })
@ResponseBody
public String getEmployeesByIdWithOptional(@PathVariable Optional<String> id) {
    if (id.isPresent()) {
        return "ID: " + id.get();
    } else {
        return "ID missing";
    }
}

Leave a Reply