'How to return CREATED status (201 HTTP) in ResponseEntity
There is a Spring-MVC application. In controllers, when returning the results of methods, I return via ResponseEntity<>. On success, I return (200 statutes) the OK-method. But when creating something, I would like to return the CREATED-method (201 status). I just can’t understand what kind of URL to ask in parentheses when calling through CREATED. How can this be implemented?
Now I have such an implementation:
@PostMapping("/create/dish")
ResponseEntity<Dish> createDish(@Valid @RequestBody DishDTO dishDTO) {
return ResponseEntity.ok(cookService.createDish(dishDTO.getDishName(), dishDTO.getAboutDish(), dishDTO.getDishType(),
dishDTO.getCookingTime(), dishDTO.getWeight(),
dishDTO.getDishCost(), dishDTO.getCooksId()));
}
I want to remake it like this to make it work(now it not work):
@PostMapping("/create/dish")
ResponseEntity<Dish> createDish(@Valid @RequestBody DishDTO dishDTO) {
return ResponseEntity.created(cookService.createDish(dishDTO.getDishName(), dishDTO.getAboutDish(), dishDTO.getDishType(),
dishDTO.getCookingTime(), dishDTO.getWeight(),
dishDTO.getDishCost(), dishDTO.getCooksId()));
}
P.S. I don’t have a frontend at all. All through Swagger or PostMan.
Solution 1:[1]
Just return this way:
return new ResponseEntity<Dish>(cookService.createDish(...), HttpStatus.CREATED)
Making sure you have imported org.springframework.http.HttpStatus
Solution 2:[2]
You can use
return new ResponseEntity(cookService.createDish(...), HttpStatus.CREATED);
Read more here
Solution 3:[3]
If you want to create a 201 (CREATED) response without a body, then use:
ResponseEntity.status(HttpStatus.CREATED).build()
Solution 4:[4]
You can use
ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(savedObjectId).toUri()).build()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | t0r0X |
| Solution 2 | t0r0X |
| Solution 3 | Rajib Biswas |
| Solution 4 | UmutSalihBayrak |

