Search code examples
quarkusopen-libertymicroprofile

How to validate path parameter in microprofile


Here key is pathParam. And even if I send the value of key greater than 9. It sends me valid response, instead of throwing validation error.

Curl request -

curl --location --request GET 'localhost:8080/v1/batch-tokens/11/action/count'

Code -

@Path("/v1/batch-tokens")
public class BatchTokenResource implements Serializable {

    private static final Logger LOGGER = Logger.getLogger(BatchTokenResource.class.getName());
    private static final String LOG_HEADER = "[" + BatchTokenResource.class.getSimpleName() + "]::";

    @GET
    @Path("/{key}/action/count")
    public Response countTokenPerKey(
            @PathParam("key") @Min(value = 0) @Max(value = 9) 
            @Pattern(regexp = "^\\d$") String key
    ) {
        LOGGER.log(Level.INFO, () -> LOG_HEADER + "countTokenPerKey " +
                "key=" + key
        );
        try {
            Long tokenCount = 100L;
            return Response.ok(new TokenModel(key, tokenCount)).build();
        } catch (Exception ex) {
            LOGGER.log(Level.WARNING, () -> LOG_HEADER + "countTokenPerKey failed." +
                    "key=" + key +
                    "exception=" + ex.getMessage()
            );
            throw ex;
        }
    }
}

I tried searching on quarkus.io/guide and internet, but only found docs to validate bean parameters.

Guide for validating bean parameters:

  1. https://quarkus.io/guides/validation
  2. https://microprofile.io/2019/07/11/validate-your-microservices-with-microprofile-and-bean-validation

Solution

  • Looks like the culprit is the type of the parameter:

    String key

    https://javadoc.io/doc/jakarta.validation/jakarta.validation-api/latest/jakarta/validation/constraints/Max.html

    Supported types are:
    
    BigDecimal
    BigInteger
    byte, short, int, long, and their respective wrappers
    Note that double and float are not supported due to rounding errors (some providers might provide some approximative support).