I'm trying to create a shopping Cart using Spring which will have cartId, product name, price
. This will be done using a specific endpoint /api/carts
. For this I would use the POST method and the @RequestBody
but the requirement of my homework is to create a POST method with empty body. What is the logic around that?
How do I do that in Spring?
My understanding is that I am also supposed to send data in the body like cartId, product name, price
. What am I missing?
My code would be something like this
@RestController
@RequestMapping ("/api")
public class Controller {
@Autowired
CartService service;
@PostMapping("/carts")
ResponseEntity<CartDTO> createCart (@RequestBody CartDTO dto){
Cart cart = new Cart(dto);
etc
but the above will not have an empty body. Can someone explain the difference in post method with empty body and with a body? Thank you
CodePudding user response:
It is technically impossible to post an empty body(aka no body)! You will always have a valid body for all requests based on http(see https://www.ietf.org/rfc/rfc2616.html#section-5)! The task, written in this terminology, is nonsense.
But you can post a valid body size of 0 bytes. That is the most matching interpretation of an "empty body". You can signalize a empty body if you neither post a Content-Length nor a Transfer-Encoding header. But thats not a non-body term. You always send a body, even if its 0 bytes long.
CodePudding user response:
You can acheive it like this:
@PostMapping("/carts")
public ResponseEntity createCart(@RequestBody CartDTO dto) {
.....logic
return new ResponseEntity(HttpStatus.CREATED);
}
This will only send the httpSTatus in response.