Let's Build an API together - Part 12

04.01.2018 by Jens in API Series | APIs | Newsletter

I implemented a basic version of the TaskService today. You can find the full version in the GitHub repo as I’ll only discuss certain findings.

I added the H2 dependency as a runtime dependency so that we can use it for regular API starts. Right now, I let Spring Boot set it up with auto magic.

With the generated controller we are forced to map between our API model and the DB model. I wrote two helper method for that, mapToTask and mapToTaskModel which are both in the TaskService class. I already found that more annoying then I thought before.

The next thing is that the generated code uses the Spring MVC ResponseEntity in every return value. If I had hand-written the controller, I’d used annotations instead. However, that might be a matter of taste. What bugs me a bit is, that having the ResponseEntity and the API Task in my TaskService it pollutes it with too much data transformation. This makes it harder to detect the real business logic later, and the service has now more than one responsibility.


public ResponseEntity<Task> getTaskById(Long taskId) {

    final Optional<TaskModel> task = repository.findById(taskId);

    if (task.isPresent()) {
        return new ResponseEntity<Task>(mapToTask(task.get()), HttpStatus.OK);
    return new ResponseEntity<Task>(HttpStatus.NOT_FOUND);

If this would be a customer project, I’d actually reconsider at this stage if using the generator was a good choice. We haven’t wasted much time testing it out and can still easily revert to hand-written code. One of the reasons why I believe prototyping and constant refactoring are essential to the success of a project. Pretty often, we gain insights while working on something, we could not see in advance.

Want content like this in your inbox each workday? No BS, spam or tricks... just useful content:

I understand and agree to the privacy policy