I have an API which returns the details of the employee based on the employee ID that is sent as a path parameter.
http://localhost:8080/emplyee/155
in the above url 155 is the employee ID and the API would return the details the employee whose ID is 155.
Below is from my controller file.
@GET
@produces({MediaType.APPLICATION_JSON})
@path("/{employee-id})
public Response getEmployeeDetails(@pathparam(employee-id) int empId);
The problem is this API is fetching the employee details even though any request body is sent along with the pathparam. So, how to block or send 400 bad request when an unnecessary request body is sent for this API as it is not needed and will not be used in the API logic?
below is the example for which I want the API to respond 400 error.
URI - http://localhost:8080/emplyee/155
Request - {"name":"hello","position":"tech"}
Respone - 200 OK and employee details of ID 155
This will work:
@RestController
@RequestMapping
public class MyController {
@GetMapping("/{employee-id}")
public ResponseEntity getEmployeeDetails(@PathVariable(name = "employee-id") int empId,
@RequestBody(required = false) Object requestBody) {
if (requestBody != null) {
throw new RuntimeException("Request body is not empty");
}
return ResponseEntity.ok(empId);
}
}
ex:
curl --location --request GET 'http://localhost:8080/2' \
--header 'Content-Type: application/json' \
--data-raw '{
"name": "grkn"
}'
{
"timestamp": "2023-04-25T06:35:02.132+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/2"
}
2023-04-25T09:35:02.125+03:00 ERROR 23340 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.lang.RuntimeException: Request body is not empty] with root cause
java.lang.RuntimeException: Request body is not empty
at com.example.testspringboot.HelloController.getEmployeeDetails(HelloController.java:18) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
.......