Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is ResponseEntity and when should you use it? ResponseEntity क्या है और इसका उपयोग कब करना चाहिए?

Answer

ResponseEntity represents the entire HTTP response — status code, headers, and body — giving full control over what's returned, unlike a plain return type where Spring infers a 200 OK by default.

It is used whenever the response needs a specific status code (201 Created after a POST, 404 Not Found, 204 No Content for a delete), custom headers (like a Location header pointing to a newly created resource), or conditional responses based on business logic.

@PostMapping
public ResponseEntity<User> create(@Valid @RequestBody UserDto dto) {
    User saved = userService.save(dto);
    URI location = URI.create("/api/users/" + saved.getId());
    return ResponseEntity.created(location).body(saved);
}

ResponseEntity पूरे HTTP रिस्पॉन्स को दर्शाता है — स्टेटस कोड, हेडर्स और बॉडी — जिससे रिटर्न होने वाली चीज़ पर पूरा नियंत्रण मिलता है, जबकि सामान्य रिटर्न टाइप में स्प्रिंग डिफ़ॉल्ट रूप से 200 OK मान लेता है।

इसका उपयोग तब होता है जब रिस्पॉन्स को किसी विशिष्ट स्टेटस कोड की ज़रूरत हो (POST के बाद 201 Created, 404 Not Found, डिलीट के लिए 204 No Content), कस्टम हेडर्स की ज़रूरत हो, या बिज़नेस लॉजिक के आधार पर कंडीशनल रिस्पॉन्स देना हो।

@PostMapping
public ResponseEntity<User> create(@Valid @RequestBody UserDto dto) {
    User saved = userService.save(dto);
    URI location = URI.create("/api/users/" + saved.getId());
    return ResponseEntity.created(location).body(saved);
}

Was this answer clear?