Tip
|
The corresponding source code is in the step-6 folder of the guide repository.
|
Exposing a web HTTP/JSON API is very straightforward using what we have already covered from the vertx-web
module.
We are going to expose a web API with the following URL scheme:
-
GET /api/pages
gives a document will all wiki page names and identifiers, -
POST /api/pages
creates a new wiki page from a document, -
PUT /api/pages/:id
updates a wiki page from a document, -
DELETE /api/pages/:id
deletes a wiki page.
Here is a screenshot of interacting with the API using the HTTPie command-line tool:
We are going to add new route handlers to the HttpServerVerticle
.
While we could just add handlers to the existing router, we can also take advantage of sub-routers.
They allow a router to be mounted as a sub-router of another one, which can be useful for organizing and/or re-using handlers.
Here is the code for the API router:
link:src/main/java/io/vertx/guides/wiki/http/HttpServerVerticle.java[role=include]
-
This is where we mount our router, so requests starting with the
/api
path will be directed toapiRouter
.
Here is the code for the different API router handlers.
link:src/main/java/io/vertx/guides/wiki/http/HttpServerVerticle.java[role=include]
-
We just remap database results in page information entry objects.
-
The resulting JSON array becomes the value for the
pages
key in the response payload. -
JsonObject#encode()
gives a compactString
representation of the JSON data.
link:src/main/java/io/vertx/guides/wiki/http/HttpServerVerticle.java[role=include]
This handler and other handlers need to deal with incoming JSON documents.
The following validateJsonPageDocument
method is a helper for doing validation and early error reporting, so that the remainder of the processing assume the presence of certain JSON entries:
link:src/main/java/io/vertx/guides/wiki/http/HttpServerVerticle.java[role=include]
link:src/main/java/io/vertx/guides/wiki/http/HttpServerVerticle.java[role=include]
The handleSimpleDbReply
method is a helper for finishing the request processing:
link:src/main/java/io/vertx/guides/wiki/http/HttpServerVerticle.java[role=include]
We write a basic test case in the io.vertx.guides.wiki.http.ApiTest
class.
The preamble consists in preparing the test environment. The HTTP server verticle needs the database verticle to be running, so we need to deploy both in our test Vert.x context:
link:src/test/java/io/vertx/guides/wiki/http/ApiTest.java[role=include]
-
We use a different JDBC URL to use an in-memory database for the tests.
The proper test case is a simple scenario where all types of requests are being made. It creates a page, fetches it, updates it then deletes it:
link:src/test/java/io/vertx/guides/wiki/http/ApiTest.java[role=include]
Tip
|
The test uses Future objects composition rather than nested callbacks; the last composition must complete the
async future or the test will eventually time out.
|