= Vert.x OpenAPI Router
:toc: left

Vert.x OpenAPI Router is based on https://vertx.io/docs/vertx-openapi/java/[Vert.x OpenAPI] and only provides the router functionality.

Vert.x OpenAPI Router can:

* generate a router according to your OpenAPI contract, with correct paths & methods.

== Using Vert.x OpenAPI Router

To use Vert.x OpenAPI Router, add the following dependency to the _dependencies_ section of your build descriptor:

* Maven (in your `pom.xml`):

[source,xml,subs="+attributes"]
----
<dependency>
 <groupId>io.vertx</groupId>
 <artifactId>vertx-web-openapi-router</artifactId>
 <version>4.5.5</version>
</dependency>
----

* Gradle (in your `build.gradle` file):

[source,groovy,subs="+attributes"]
----
dependencies {
 compile 'io.vertx:vertx-web-openapi-router:4.5.5'
}
----

== RouterBuilder

With the `link:../../apidocs/io/vertx/ext/web/openapi/router/RouterBuilder.html[RouterBuilder]` you can easily generate a Vert.x Web Router based on the passed
`link:../../apidocs/io/vertx/openapi/contract/OpenAPIContract.html[OpenAPIContract]`.

[source,java]
----
OpenAPIContract contract = getContract();
RouterBuilder routerBuilder = RouterBuilder.create(vertx, contract);
Router router = routerBuilder.createRouter();

// In case that a BodyHandler was applied before, it is necessary to pass a RequestExtractor
RouterBuilder.create(vertx, contract, RequestExtractor.withBodyHandler());
----

The `link:../../apidocs/io/vertx/ext/web/openapi/router/RouterBuilder.html[RouterBuilder]` provides methods to access the generated routes.
These routes can then be customized by adding custom handlers or enable / disable the validation.

[source,java]
----
OpenAPIRoute getPetsRoute = routerBuilder.getRoute("getPets");

// Disables validation for this route.
getPetsRoute.setDoValidation(false);

for (OpenAPIRoute route : routerBuilder.getRoutes()) {
  // Access the operation object from the contract
  Operation operation = route.getOperation();

  // Add a custom handler
  route.addHandler(routingContext -> {
    // do something
  });

  // Add a failure handler
  route.addFailureHandler(routingContext -> {
    // do something
  });
}
----

After a successful validation of the incoming request, the validated parameters and request body are stored in the RoutingContext and can be accessed inside your custom handlers.

[source,java]
----
OpenAPIRoute putPetRoute = routerBuilder.getRoute("putPet");

putPetRoute.addHandler(routingContext -> {
  ValidatedRequest validatedRequest =
    routingContext.get(RouterBuilder.KEY_META_DATA_VALIDATED_REQUEST);

  validatedRequest.getBody(); // returns the body
  validatedRequest.getHeaders(); // returns the header
  // ..
  // ..
});
----