The Shortest way to return a Response Entity in Spring Boot

Today I found out, there is a super short way to return a ResponseEntity in Spring boot. Usually you want to fetch data from a repository using some kind of interface. Let’s say you use the:

Interface CrudRepository<T,ID>

It provides a method to find an entity by its ID:

Optional<T> findById(ID id)

As you can see it returns an optional object. If there is no entity found it will just return an empty optional object.

Now you have to handle two cases in which you will return the right http code. If you found an entity, you should return it and send a “200 OK”. If your optional is empty you should return a “404 Not Found”. Let’s see how an implementaiton could look like:

    public ResponseEntity<Item> findById(PathVariable Integer id){
        Optional<Item> optionalItem = itemService.findItemById(id);
            return ResponseEntity.ok(optionalItem.get());
        } else {
            return ResponseEntity.notFound().build();

As you can see we use an itemService which has a function to find an item by it’s id. Inside that service we would use the itemRepository.
Now there are multitple ways to make it look shorter. But today i will show you the shortest way i could find:

return ResponseEntity.of(itemService.findItemById(id));

Just one line. The docs of the “of” method say it is a shortcut. If the optional has no value, it will return a 404 status and if it finds one, it will return the value with a 200 OK status.

I read this on Ken Kousen’s newsletter “Tales from the jar side” you should give it a try. I really enjoy reading it once a week.