Have you noticed that all modern Java web frameworks support Lambda-based implementation of RESTful services? In general, it looks like this:

get("/foo", (req, resp) -> { application logic }); post("/bar", (req, resp) -> { application logic });

What's wrong with this style? The style is fine, but we can do much better.

Naive Implementation of a RESTful API With Rapidoid

I will use the powerful Rapidoid web framework to implement a very simple RESTful service, which calculates the sum of the x and y parameter values:

package com.example; import org.rapidoid.setup.On; public class Main { public static void main(String[] args) { On.get("/sum").json(req -> { int x = Integer.parseInt(req.param("x")); // ugly! int y = Integer.parseInt(req.param("y")); // ugly! return x + y; }); } }

This explicit parameter handling is verbose and ugly. Who cares about the sweet Lambda syntax if retrieving a simple parameter needs so much code?

Running the application will start the Rapidoid server, and by navigating to http://localhost:8888/sum?x=3&y=7, we should see 10 .

Beautiful Implementation of a RESTful API With Rapidoid

Let's simply declare x and y as Lambda parameters.

package com.example; import org.rapidoid.annotation.Required; import org.rapidoid.setup.On; public class Main { public static void main(String[] args) { On.get("/sum").json((@Required Integer x, @Required Integer y) -> x + y); } }

The Rapidoid web framework will retrieve the names, types, and annotations of the Lambda parameters and it will initialize them from the request parameters with automatic type conversion and validation.

POJO-Style Lambda Parameters

Of course, we can wrap the x and y parameters inside a POJO ( SumParams ) and Rapidoid will do its magic (automatic instantiation, initialization, validation, etc.):

package com.example; import org.rapidoid.setup.On; class SumParams { public int x; // x is required public Integer y; // y is optional, can be null } public class Main { public static void main(String[] args) { On.get("/sum").json((SumParams p) -> p.x + p.y); } }

This approach separates the structure of the parameters from the application logic and it scales well as the number of parameter grows, giving more space for annotations and maybe some extra logic.

Conclusion

The Java 8 Lambdas are great, but they can be used in either a beautiful or an ugly way. The Rapidoid web framework embraces their ultimate power, empowering the developers to implement their APIs or applications in a clean, robust, and elegant way.

I discussed the different coding styles through a trivial API implementation. The hardest aspects of the web and API development haven't been covered (yet).