Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Diffrence b/w @ResponseStatus and ResponseEntity.created(location).build() in post method of rest controller in spring boot

For a POST method in Rest controller I want to return status code 201.

I saw two approaches for that.

First one is:

    @PostMapping("/offers")
    @ResponseStatus(HttpStatus.CREATED)
    public Offer createOffer(@Valid @RequestBody Offer offer) {
        return offerRepository.Save(offer);
    }

Second approach is:

   @PostMapping("/offers")
   public ResponseEntity<Object> createOffer(@Valid @RequestBody Offer offer) {
        return offerService.createOffer(offer);
    }

Below is my service class:

    @Override
    public ResponseEntity<Object> createOffer(Offer offer) {
         Offer uOffer=OfferRepository.save(offer);
         URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{jobTitle}").
                    buildAndExpand(uOffer.getJobTitle()).toUri();
         return ResponseEntity.created(location).build(); 
    }

So my question is: for first approach we are not using any ResponseEntity.created as we are simply returning @ResponseStatus(HttpStatus.CREATED) from controller. But in the second we are not using @ResponseStatus(HttpStatus.CREATED) and we are handling that status code 201 by using uri and response entity.

What is the difference b/w the both approaches? Both seems to be same as they are returning the same response code 201. which one is preferred?

like image 594
Ankit Avatar asked Oct 14 '25 05:10

Ankit


1 Answers

In my opinion you should apply the following rules. If you want to return a ResponseEntity then use that to affect the status. Thus something like:

@PostMapping("/offers")
public ResponseEntity<Offer> createOffer(@Valid @RequestBody Offer offer) {
     Offer offer = offerService.createOffer(offer);
     URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{jobTitle}").
                buildAndExpand(uOffer.getJobTitle()).toUri();
     return ResponseEntity.created(location)
                          .body(offer)
                          .build(); 
}

Do not allow your service to generate the ResponseEntity as this is a view class for controllers and should not be in a service.

The second option is by using the class rather then response entity. Then the example would be something like:

@PostMapping("/offers")
@ResponseStatus(HttpStatus.CREATED)
public Offer createOffer(@Valid @RequestBody Offer offer) {
     // Do not return response entity but the offer
     return offerService.createOffer(offer);
}
like image 190
Gerben Jongerius Avatar answered Oct 18 '25 04:10

Gerben Jongerius