Lightweight embedded Java REST server without a Framework

A quick Google search of Java REST frameworks will lead you to tons of existing frameworks. For example you can easily find tons of Spring Boot REST examples which have very few lines of code. However, what they do have is lots of annotations and lots of magic. Also, most of them don't do very much, they tend leave out exception handling, logging and metrics. Here is an example of a lightweight REST server with a lot of the appropriate middleware, no magic and not that many lines of custom code. This example does not include validation or databases, we will save that for a later date.

Model / Pojo

Our service will be very simple and only handle CRUD operations for a User class.

Request Utilities

Simple helpers to reduce boilerplate and reuse defaults / string literals across routes. In Spring its not uncommon to see something like @PathParam("userId") littered all over the code, or worse some say userId some say id and it can be inconsistent. Of course its possible to write your own custom annotations in Spring for reuse but who wants to do that for every single param? (There are other and better approaches out there but they don't seem to be followed very often).

Notice how there are two options for handling NotFound in the server. You can throw / handle exceptions or handle it directy in the route since we already know its not found. Spring and most frameworks tend to push for the throw / handle exception model. It is easy to do that, just remember throwing and catching exceptions can be expensive, in these cases it is easily avoidable so pick what makes sense for your business domain.

Get User 404

Both approaches respond in the same way however the exception handling version will be more expensive. It has to unroll the stack trace and whatnot. If that is acceptable by all means go for it. If you need maxiumim performance don't throw exceptions when you don't need to.