Vert.x Web API Contract provides you RouterBuilder
, an object that helps you to build the Vert.x Web Router starting from the OpenAPI specification.
To load the specification into the start method of your Verticle:
link:src/main/java/io/vertx/howtos/openapi/APIVerticle.java[role=include]
-
If the loading succeeds, you receive a ready to use instance of
RouterBuilder
, otherwise -
you fail the deploy of the verticle
Now you can fit your business logic into the Route handlers using operation(operationId).handler()
.
For listPets
:
link:src/main/java/io/vertx/howtos/openapi/APIVerticle.java[role=include]
-
Get the response object
-
Put
Content-type: application/json
header -
Write the response with all pets
For createPets
:
link:src/main/java/io/vertx/howtos/openapi/APIVerticle.java[role=include]
-
Get the parsed parameters container
-
Extract the parsed body
-
Write the 200 empty response
For showPetById
:
link:src/main/java/io/vertx/howtos/openapi/APIVerticle.java[role=include]
-
Get the parsed parameters container
-
Extract the parsed path parameter
-
Search the pet
-
If pet is present, write the pet in the response
-
If pet is absent, fail the routing context with 404
Now we can generate the Router
and add the "Not Found" and "Bad Request" error handlers:
link:src/main/java/io/vertx/howtos/openapi/APIVerticle.java[role=include]
-
Generate the
Router
from theRouterBuilder
-
Mount the 404 not found error handler
-
Create the error json object with exception message, if any
-
Write the response with the error object
-
Instantiate a Vert.x HttpServer
-
Mount the router on the HttpServer instance
You can find the complete source code of APIVerticle
on this how-to repo.
The APIVerticle
already has a main
method, so it can be used as-is to:
-
create a
Vertx
context, then -
deploy
APIVerticle
.
You can run the application from:
-
your IDE, by running the
main
method from theAPIVerticle
class, or -
with Maven:
mvn compile exec:java
You can test your API using any command-line tool like curl
:
$ curl http://localhost:8080/pets [{"id":1,"name":"Fufi","tag":"ABC"},{"id":2,"name":"Garfield","tag":"ABC"},{"id":3,"name":"Puffa","tag":"ABC"}] $ curl http://localhost:8080/pets/3 {"id":3,"name":"Puffa","tag":"ABC"} $ curl http://localhost:8080/pets/5 {"code":404,"message":"Pet not found"} $ curl -X POST -H "Content-type: application/json" --data '{"id":4,"name":"Alan"}' http://localhost:8080/pets $ curl -X POST -H "Content-type: application/json" --data '{"id":4}' http://localhost:8080/pets {"code":400,"message":"$.name: is missing but it is required"} $ curl http://localhost:8080/pets [{"id":1,"name":"Fufi","tag":"ABC"},{"id":2,"name":"Garfield","tag":"ABC"},{"id":3,"name":"Puffa","tag":"ABC"},{"id":4,"name":"Alan"}]