Joskaa
Joskaa

Reputation: 313

How to fix error in Postman POST and Delete request with SpringBoot?

I am new to spring boot and I am trying to send a simple POST and DELETE request via postman, but i am stuck with error 500.Can someone point the errors in my code?.

I have spring boot simple app build with maven and run in embedded tomcat through STS.

i tried these requests for POST and DELETE:

POST:

http://localhost:8080/api/v1/addMenu

The Error status:

{"timestamp":"2022-08-05T13:41:37.984+00:00","status":500,"error":"Internal Server Error","path":"/api/v1/addMenu"}

DELETE:

http://localhost:8080/api/v1/delete/5

Error Status:

{"timestamp":"2022-08-05T13:45:51.548+00:00","status":500,"error":"Internal Server Error","path":"/api/v1/delete/5"}

Here is my controller code:

@RestController
@RequestMapping("/api/v1")
public class MenuController {
@Autowired
private MenuRepository menuRepository;

@GetMapping("/getMenu")
public List<Menu> list() {
    return menuRepository.findAll();
}

@GetMapping
@RequestMapping("/getMenu/{id}")
public Menu get(@PathVariable Integer id) {
    return menuRepository.getReferenceById(id);
}

@PostMapping("/addMenu")
public Menu create(@RequestBody final Menu menu) {
    return menuRepository.saveAndFlush(menu);
}

@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
public void delete(@PathVariable Integer id) {
    menuRepository.deleteById(id);
}

@RequestMapping(value = "{id}", method = RequestMethod.PUT)
public Menu update(@PathVariable Integer id, @RequestBody Menu menu) {
           
    Menu existingMenu = menuRepository.getReferenceById(id);
    BeanUtils.copyProperties(menu, existingMenu, "buy_id");
    return menuRepository.saveAndFlush(existingMenu);
}
}

MenuRepository:

public interface MenuRepository extends JpaRepository<Menu, Integer> {}

The port is default in 8080.

I tried the Get request and PUT request, which worked perfect with no errors, but the POST and DELETE gives error status. Can someone point the mistake in the code.?

Thanks

Upvotes: 0

Views: 1595

Answers (1)

tbatch
tbatch

Reputation: 1849

There is no mistake in the code you've posted. The 500 error means there is a problem internally with your server. This could be any sort of Exception. There doesn't appear to be anything wrong with your controller itself. Since you are getting a 500 error and not a 404 error, that means that the mappings exist and postman is able to contact them. The server is getting an error, but postman doesn't care about it. Postman only sees that something happened on the server side that caused a problem.

I believe a bit of debugging is in order. Set a breakpoint in your controller and attempt to run the code in the code evaluation to see what the error is. That should get you on track to find how to fix it.

Upvotes: 1

Related Questions