I am developing simple rest api with spring boot. I create users via POST method. And deletes via DELETE. But when i use DELETE with json server returns Bad Request.
creating user:
ubuntu@ubuntu-pc:~$ curl -X POST -H "Content-type: application/json" -d '{"name": "developer", "email": "[email protected]"}' http://localhost:8080/add-user "OK" getting users:
ubuntu@ubuntu-pc:~$ curl http://localhost:8080 [{"id":"ff80818176c9b9720176c9bdfd0c0002","name":"developer","email":"[email protected]"}] deleting user using json:
ubuntu@ubuntu-pc:~$ curl -X DELETE -H "Content-type: application/json" -d '{"id": "ff80818176c9b9720176c9bdfd0c0002"}' http://localhost:8080/del-id {"timestamp":"2021-01-03T19:47:15.433+00:00","status":400,"error":"Bad Request","message":"","path":"/del-id"} deleting user using html queries:
ubuntu@ubuntu-pc:~$ curl -X DELETE http://localhost:8080/del-id?id=ff80818176c9b9720176c9bdfd0c0002 "OK" ubuntu@ubuntu-pc:~$ curl http://localhost:8080 [] UserRepository.java
public interface UserRepository extends CrudRepository<UserRecord, String> { } UserService.java
@Service public class UserService { @Autowired private UserRepository userRepository; public List<UserRecord> getAllUsers() { List<UserRecord> userRecords = new ArrayList<>(); userRepository.findAll().forEach(userRecords::add); return userRecords; } public void addUser(UserRecord user) { userRepository.save(user); } public void deleteUser(String id) { userRepository.deleteById(id); } } UserController.java
@RestController public class UserController { @Autowired private UserService userService; @RequestMapping("/") public List<UserRecord> getAllUser() { return userService.getAllUsers(); } @RequestMapping(value="/add-user", method=RequestMethod.POST) public HttpStatus addUser(@RequestBody UserRecord userRecord) { userService.addUser(userRecord); return HttpStatus.OK; } @RequestMapping(value="/del-id", method=RequestMethod.DELETE) public HttpStatus deleteUser(@RequestParam("id") String id) { userService.deleteUser(id); return HttpStatus.OK; } } jvm log:
2021-01-03 22:47:15.429 WARN 30785 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'id' is not present] What am i wrong?
DELETEendpoint only needs a parameter (id) in the request - not a JSON object. So, thishttp://localhost:8080/del-id?id=ff80818176c9b9720176c9bdfd0c0002is the correct request - if you add it to the body in JSON, then you will get a Bad Request (as the parameter is not where it is supposed to be)