In Vert.x, should REST endpoints return Future or T?

I am having a hard time finding documentation on which is the correct return type.

For example, if I have a REST endpoint which lookups and returns a String should the endpoint have a return type of Future<String> or String? Further, what impact would this have on the event loop (i.e. would returning String over Future<String> cause more blocking)?

Thanks!

Answer

If you look at section (2) of the quick-start at https://vertx.io/get-started, you’ll see chunk of code I’ve pasted below (I’ve added some numbered comments):

// Mount the handler for all incoming requests at every path and HTTP method
router
  .route()  // (1)
  .handler(context -> {  // (2)
    // Get the address of the request
    String address = context.request().connection().remoteAddress().toString();
    // Get the query parameter "name"
    MultiMap queryParams = context.queryParams();
    String name = queryParams.contains("name") ? queryParams.get("name") : "unknown";
    // Write a json response
    context.json(  // (3)
      new JsonObject()
        .put("name", name)
        .put("address", address)
        .put("message", "Hello " + name + " connected from " + address)
    );
  });

What this is doing is:

  1. Registering a Handler (basically a callback) that will be invoked for every request that the router receives.
  2. The handler will be called with a RoutingContext, which contains references to an HttpServerRequest object representing the current request, as well as an HttpServerResponse object representing the response. The latter allows you to control the response that is sent back to the client (ie headers, body, etc).
  3. context.json() is a convenience method for writing a JSON formatted response payload – the body will be correctly formatted, the content-type header will be set, etc.

Fundamentally, what .json() is doing is:

  final JsonObject myJson = ...;
  
  final Buffer myJsonBuffer = Json.encodeToBuffer(myJson);

  context.response()
      .putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
      .write(myJsonBuffer);

Those last three lines are how the response is actually sent back to the client.

For a more detailed explanation, check out the Vert.x Web documentation regarding responses here.