Enhance Post Method with method Return to Correct HTTP status Code and Location

 Response Status for REST API

404 Response is not Found

500 Response is Server Error

400 Response is Validation Error

200 Response is Success

201 Response is Created

204 Response is No Content

401 Response is Unauthorized (when authorization failed)

400 Response is Bad Request (such as validation error)

How to Give Response as 201 when resource is created 

@PostMapping("/users")

public ResponseEntity<User> addUser(@RequestBody User user) {

User savedUser = userDaoService.save(user);

return ResponseEntity.created(null).build();

}


postman request for given API call

try to add new User name = Kapil with given birthdate =1997-06-27



Get a Response status as 201
Lets add the location URI as well into the Response header


@PostMapping("/users")

public ResponseEntity<User> addUser(@RequestBody User user) {

User savedUser = userDaoService.save(user);

URI location = ServletUriComponentsBuilder.fromCurrentRequest()

.path("/{id}")

.buildAndExpand(savedUser.getId())

.toUri();

return ResponseEntity.created(location).build();

}

Will get Location in Header now as well which will tell the URI of given added user



Comments

Popular posts from this blog

Introduction of RESTful Web Service

Learn JPA and Hibernate

Implementing Dynamic Filtering for Rest API