Vertx-web: Support required parameter for API request

Created on 20 Jun 2017  路  3Comments  路  Source: vert-x3/vertx-web

Version

  • vert.x core: 3.4.1
  • vert.x web: 3.4.1

Context

The path parameter is retrieved using routingContext.request().getParam("whatever_id"). It can be checked if this parameter is null and depending on that, we can throw a 400. But this can create lot of boilerplate code in case of multiple required parameters.
Currently, is there any way to make request parameters required or optional?

question

Most helpful comment

@shiprabehera no currently there is no support for this, you can however declare simple validation handlers like:

if (ctx.request().getParam("whatever_id") == null || "".equals(ctx.request().getParam("whatever_id"))) {
  ctx.fail(400);
} else {
  ctx.next();
}

and now just refer to it before the routes that require it. There is a PR in review to allow multple handlers per route so your code would be something like:

router.get("/:whatever_id")
  .handler(validateWhateverId)
  .handler(ctx -> {
    // at this point it is guaranteed that the whatever_id is valid
    ...

All 3 comments

Not that I know of, but a lot of side-projects gravitate around this idea of "automatic parameter checking" (required / optional, but also the parameter type : int, date, etc.).

You can have a look at the Google Group (and the different discussions around Swagger-Gen for example).

But for sure, vertx-web definitely needs an "official" way of reducing the "checking boilerplate". I do agree. Here's such an attempt.

@shiprabehera no currently there is no support for this, you can however declare simple validation handlers like:

if (ctx.request().getParam("whatever_id") == null || "".equals(ctx.request().getParam("whatever_id"))) {
  ctx.fail(400);
} else {
  ctx.next();
}

and now just refer to it before the routes that require it. There is a PR in review to allow multple handlers per route so your code would be something like:

router.get("/:whatever_id")
  .handler(validateWhateverId)
  .handler(ctx -> {
    // at this point it is guaranteed that the whatever_id is valid
    ...

@pmlopes Thank you. That is exactly how I am handling it, just wanted to confirm if we have or plan to support this feature.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

plenderyou picture plenderyou  路  7Comments

ramtech123 picture ramtech123  路  5Comments

encodeering picture encodeering  路  5Comments

LLfam picture LLfam  路  4Comments

vietj picture vietj  路  7Comments