Search code examples
javaspring-bootdate

Not able to call GET API with Date request param in Spring boot project


I am trying to call a GET API with LocalDateTime format but it keeps giving error that the request param is missing.

Here is the API I am trying to call

@RequestMapping(value = "/api", method = RequestMethod.GET) public void apiCall(@RequestParam("restrictProfileDate") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") LocalDateTime restrictProfileDate) {

And here is the code that I am using to call this API

        HttpHeaders headers = new HttpHeaders();   
    LocalDate deltascreeningDate = LocalDate.now();
    Date date = Date.from(dateValue.atStartOfDay(ZoneId.systemDefault()).toInstant()); 

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String formattedDate = sdf.format(date);

    Map<String, String> params = new HashMap<>();
    params.put("restrictProfileDate", formattedDate);
    
    ResponseEntity<String> response = restTemplate.exchange(apiEndPoint, HttpMethod.GET, new HttpEntity<>(params, headers), String.class);

The error I am getting is "WARN o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required LocalDateTime parameter 'restrictProfileDate' is not present]"


Solution

  • new HttpEntity<>(params, headers)
    

    Actually uses first argument as a body, not as query params. You should pass params after String.class like this

    restTemplate.exchange(apiEndPoint, HttpMethod.GET, new HttpEntity<>(params, headers), String.class, params)
    

    See https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#exchange(java.lang.String,org.springframework.http.HttpMethod,org.springframework.http.HttpEntity,java.lang.Class,java.util.Map)