Getting 400 Bad Request in response when I enter Date input in Swagger

Viewed 3716

One of my endpoint takes 2 parameters in Java code with data/format type as Date. In swagger, the API shows expected input as:

string($date-time)

(query)

When I enter 2020-07-07T01:08:10Z in both the parameter boxes, I get status code 400 Bad request in response. I also tried with 2020-07-07T01:08:10.873Z.

Am I giving wrong Date format?. Please help.

Edit:

@GetMapping("/findAllEventsWithoutLogin")
    public Collection<GeneralEvent> getAllEvents(@RequestParam("start_date") Date startDate,
            @RequestParam("end_date") Date endDate) {

package com.events.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableSwagger2

@Configuration
public class SwaggerConfig {

    @Bean
    public Docket productApi() {

        return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any()).build();
    }
}

enter image description here

Edit:

FYI: The same Date format is working fine when I am passing Date in body, but not when I am passing it as a query parameter. Below is working fine.

enter image description here

1 Answers

No, You are not using the wrong date format.

  • date-time – the date-time notation as defined by RFC 3339, section 5.6, for example, 2020-07-07T01:08:10Z

There might be some other thing that is making your request not reachable to the backend java server. Please Post your minimal java code and if possible then also swagger minimal yml definition. So, that we can check what is wrong that you are facing.

After asking various ping pong questions which clarify my doubt.

Not I find there is one issue with your backend code that is you are using start_date and end_date java.util.Date as a query param. But you are requesting with a string which throws parsing IllegalArgumentException and causing 400 Bad Request. So, to fix this you need to change your backend code to add format as @DateTimeFormat (iso = DateTimeFormat.ISO.DATE_TIME) which is illustrated perfectly on-site baeldung. Change code is given below:

@GetMapping("/findAllEventsWithoutLogin")
    public Collection<GeneralEvent> getAllEvents(@RequestParam("start_date")  @DateTimeFormat (iso = DateTimeFormat.ISO.DATE_TIME) Date startDate,
            @RequestParam("end_date")  @DateTimeFormat (iso = DateTimeFormat.ISO.DATE_TIME) Date endDate) {

Please check this link to know about this issue in detail.

If you want to check cooked code then visit my github.

Related