RESTful services with Lambda handlers, JPA, Jackson and Bean Validation

Main.java
import org.rapidoid.annotation.Valid;
import org.rapidoid.jpa.JPA;
import org.rapidoid.setup.App;
import org.rapidoid.setup.On;
 
public class Main {
 
    public static void main(String[] args) {
        App.bootstrap(args).jpa(); // bootstrap JPA
 
        On.get("/books").json(() -> JPA.of(Book.class).all()); // get all books
 
        On.post("/books").json((@Valid Book b) -> JPA.save(b)); // insert new book if valid
    }
 
}
Book.java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
 
@Entity
public class Book {
 
    @Id
    @GeneratedValue
    public Long id;
 
    @NotNull
    public String title;
 
    public int year;
 
}

Let's send some HTTP requests and check the results:

POST /books {"title":"Java Book","year":2016}
{"id":1,"title":"Java Book","year":2016}
GET /books
[{"id":1,"title":"Java Book","year":2016}]
POST /books {"year":2004}
{"error":"Validation failed: Book.title (may not be null)","code":422,"status":"Unprocessable Entity"}
GET /books
[{"id":1,"title":"Java Book","year":2016}]

HTTP server routes information:

Verb Path Zone Content type MVC View name Roles
GET /books main json
POST /books main json

Project setup with Maven

To run the example, you need to create a new Java 8 project and configure it properly using Maven:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>com.example</groupId>
    <artifactId>my-example</artifactId>
    <version>1.0.0-SNAPSHOT</version>
 
    <dependencies>
        <dependency>
            <groupId>org.rapidoid</groupId>
            <artifactId>rapidoid-quick</artifactId>
            <version>5.3.4</version>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
 
</project>

Building the project with Maven is easy:
mvn package