Java Spring Boot का REST API
In this page:
@RestController
@RequestMapping("/path")
class ControllerName {
@GetMapping("/{id}")
public Type get(@PathVariable Long id) {
// body
}
}
REST Controllers
@RestController annotation किसी class को सीधे HTTP requests handle करने वाली चिह्नित करता है, और @Controller को @ResponseBody के साथ combine करता है ताकि हर method की return value response में अपने आप JSON में serialize हो जाए, बिना आपके serialization code हाथ से लिखे।
उदाहरण: REST Controllers
import org.springframework.web.bind.annotation.RestController;
@RestController // combines @Controller + @ResponseBody
public class Main {
public static void main(String[] args) {
System.out.println("Every method's return value is serialized to JSON automatically");
}
}
Login to try C/C++/Java/PHP code in the editor
GET Request Handlers
incoming GET requests को किसी specific controller method पर route करने के लिए @GetMapping का उपयोग करें, और URL path से सीधे dynamic segments (जैसे /users/{id} में id) को एक typed method parameter के रूप में capture करने के लिए @PathVariable का।
उदाहरण: GET Request Handlers
// Import org.springframework.web.bind.annotation.* so it can be used by its short name
import org.springframework.web.bind.annotation.*;
@RestController
// Define the class Main
public class Main {
@GetMapping("/users/{id}")
String getUser(@PathVariable int id) {
// Send "User #" + id back to the caller
return "User #" + id;
}
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Print a line to the console
System.out.println(new Main().getUser(7));
}
}
Login to try C/C++/Java/PHP code in the editor
POST Request Handlers
incoming POST requests को route करने के लिए @PostMapping का उपयोग करें, और Spring को incoming JSON request body को अपने आप सीधे एक Java object में deserialize करवाने के लिए @RequestBody annotation का, payload को manually parse करने से आपको बचाते हुए।
उदाहरण: POST Request Handlers
// Import org.springframework.web.bind.annotation.* so it can be used by its short name
import org.springframework.web.bind.annotation.*;
@RestController
// Define the class Main
public class Main {
// Define the record UserRequest (an immutable data carrier)
record UserRequest(String name) {}
@PostMapping("/users")
String createUser(@RequestBody UserRequest request) {
// Send "Created: " + request.name() back to the caller
return "Created: " + request.name();
}
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Print a line to the console
System.out.println(new Main().createUser(new UserRequest("Riya")));
}
}
Login to try C/C++/Java/PHP code in the editor
Custom Request Mappings
किसी controller class के सामने @RequestMapping लगाना आपको इसके सभी endpoints को एक shared base URL path के तहत group करने देता है, जो बढ़ते हुए REST API को हर endpoint में एक common prefix दोहराने के बजाय साफ़, resource-based sections में organized रखता है।
उदाहरण: Custom Request Mappings
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users") // shared base path for every endpoint below
public class Main {
@GetMapping("/{id}")
String getUser(@PathVariable int id) { return "User #" + id; }
public static void main(String[] args) {
System.out.println(new Main().getUser(3));
}
}
Login to try C/C++/Java/PHP code in the editor
Content Negotiation
REST controllers client के Accept header और request के Content-Type के आधार पर एक ही response को अपने आप XML या JSON के रूप में format कर सकते हैं, एक endpoint को हर format के लिए handler logic दोहराए बिना कई consumers को serve करने देते हुए।
उदाहरण: Content Negotiation
// Import org.springframework.web.bind.annotation.* so it can be used by its short name
import org.springframework.web.bind.annotation.*;
@RestController
// Define the class Main
public class Main {
@GetMapping(value = "/data", produces = {"application/json", "application/xml"})
String getData() {
return "same handler serves JSON or XML based on Accept header";
}
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Print a line to the console
System.out.println(new Main().getData());
}
}
Login to try C/C++/Java/PHP code in the editor
@RestControllerके बजाय@Controllerका उपयोग करना और return value को response body के बजाय एक view name के रूप में treat होते पाना।- किसी POST method parameter पर
@RequestBodyभूल जाना, जिससे JSON body bind नहीं होता और object खाली या null रहता है। - path को
/users/{id}नाम देना लेकिन parameter को@PathVariable("id")के बिनाuserIdनाम देना, जिससे Spring दोनों को मेल नहीं खिला पाता।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: