blue-sky
blue-sky

Reputation: 53876

How to validate @PathVariable is set?

Here is my Get request:

@GetMapping("/stats/{fromDate}/{toDate}")
public StatsSummary getStatsSummary(@PathVariable String fromDate, @PathVariable String toDate) {

    logger.info("Calculating statistics between" + fromDate + ",to" + toDate);

    return statsService.getStatsSummary(fromDate, toDate);

}

I've tried adding the annotation @NotBlank as:

public StatsSummary getStatsSummary(@PathVariable String fromDate, @PathVariable @NotBlank String toDate) {

but when I invoke /stats/2020-05-30/ which does not include toDate I receive the response:

{
    "timestamp": "2020-09-04T06:02:46.567+00:00",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/stats/2020-05-30/"
}

So the annotation is not being registered correctly?

Update:

It seems PathVariable is not meant to be validated:

The validators (@Validated @Valid) do not work with Spring and TomEE

Upvotes: 2

Views: 202

Answers (3)

Rafa C.
Rafa C.

Reputation: 63

In REST, path variables are part of the resource URL. Therefore, if a part of the path/URL is missing, the resource is different.

That is why a 404 is the correct response code.

If those two variables can be empty, they should be @RequestParam.

Upvotes: 2

Dejan
Dejan

Reputation: 353

Actually Spring by sending 404 returns correct answer to a client. When someone doesn't provide full URL, the 404 is the status to respond.

The proper way to validate that is to use some date class like Date or LocalDate or similar instead of String. Probably you'll need to define proper formatting of date so take a look at the following link for details. https://www.baeldung.com/spring-date-parameters

Upvotes: 1

ssaa
ssaa

Reputation: 1112

Add the following annotation to the class worked for me.(Not to the method)

@Validated

Upvotes: 0

Related Questions