Want to improve as a dev?

I send a short email every workday about Spring topics, API development and improving as a dev. The current series is about building a Kanban API with Spring.

Let's Build an API together - Part 8

22.12.2017 by Jens in API Series | APIs | Newsletter

Last time I wrote the RAML spec for the Kanban API and now we are going to generate some Spring MVC controller for it. So, I setup a Spring Boot project on GitHub and used the Spring MVC - RAML Spec Synchroniser Plugin for Maven.

The plugin will generate Spring MVC controller and model from our RAML file. We could also use the other way around and generate a RAML from Spring MVC controller. However, I used the design doc to code way.

It does either generate a stub controller, where we can fill in the blanks, or it does generate a decorator controller plus a delegate exposed as an interface. Our code only needs to implement the delegate, and voila we are done.

The generated model is a simple POJO and gets also equals, hashCode and toString methods using Apache Commons Lang classes.

The Decorator controller looks like:

@RestController
@RequestMapping(value = "/tasks", produces = "application/json")
@Validated
public class TaskControllerDecorator
    implements TaskController
{

    @Autowired
    private TaskController taskControllerDelegate;

    /**
     * Retrieves all **tasks**
     * 
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResponseEntity<List<Task>> getTasks() {
        return this.taskControllerDelegate.getTasks();
    }
}

And TaskController is the interface we must implement.

However, code generation always has also disadvantages. So, let’s check what we are facing here.

Pro:

  • RAML spec file is the source of the API
  • API facing code is generated by spec and always up to date
  • Removes a bit of work as we do not need to set up the controller by ourselves. But honestly, it’s just a few minutes

Cons:

  • No extension possible without changing the code generator or just generating once; it’s open source so you could do it
  • It did not even generate some error handler for default cases like nothing found -> return 404
  • We must have two models in our code base, the generated one for the API and the model we use for the data storage backend. We can not use the same model and just annotate it with Spring Data annotations

As always, it depends on your particular context if the pros outweigh the cons. If the specs of your design team lead, it might be good to generate the MVC part as your code monkeys just need to implement a few methods. Especially when If your just a team of one and you write Spring MVC code in your sleep, there might be no benefit at all. For the Kanban project, we will see how long it will stay.


comments powered by Disqus