← Back to Advanced Java Course | Chapter 10: Spring Boot | Lesson 2 of 6

Java Spring Boot का REST API

एक Spring Boot REST API आपको ऐसे web addresses बनाने देता है जो data भेजते और प्राप्त करते हैं, जैसे एक shop counter जहां customers चीज़ें मांगते हैं। Controllers तय करते हैं कि हर request के लिए क्या करना है।
Syntax
java
@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

java
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");
	}
}

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

java
// 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));
	}
}

POST Request Handlers

incoming POST requests को route करने के लिए @PostMapping का उपयोग करें, और Spring को incoming JSON request body को अपने आप सीधे एक Java object में deserialize करवाने के लिए @RequestBody annotation का, payload को manually parse करने से आपको बचाते हुए।

उदाहरण: POST Request Handlers

java
// 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")));
	}
}

Custom Request Mappings

किसी controller class के सामने @RequestMapping लगाना आपको इसके सभी endpoints को एक shared base URL path के तहत group करने देता है, जो बढ़ते हुए REST API को हर endpoint में एक common prefix दोहराने के बजाय साफ़, resource-based sections में organized रखता है।

उदाहरण: Custom Request Mappings

java
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));
	}
}

Content Negotiation

REST controllers client के Accept header और request के Content-Type के आधार पर एक ही response को अपने आप XML या JSON के रूप में format कर सकते हैं, एक endpoint को हर format के लिए handler logic दोहराए बिना कई consumers को serve करने देते हुए।

उदाहरण: Content Negotiation

java
// 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());
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. @RestController के बजाय @Controller का उपयोग करना और return value को response body के बजाय एक view name के रूप में treat होते पाना।
  2. किसी POST method parameter पर @RequestBody भूल जाना, जिससे JSON body bind नहीं होता और object खाली या null रहता है।
  3. path को /users/{id} नाम देना लेकिन parameter को @PathVariable("id") के बिना userId नाम देना, जिससे Spring दोनों को मेल नहीं खिला पाता।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.