REST API With Spring Boot & Groovy

Iqbal Djulfri
Sep 6, 2018 · 9 min read

Tutorial on how to create Spring Boot REST API with Groovy

Java is a powerful and highly scalable programming language. However, setting up a web application with Java is so painful. There are so many ways to do it and there are also so many configurations you need to do, even on a small scale application. In addition, the old way to deploy a Java web application is by deploying it to the Java web server application, thus adding another layer of complexity.

Spring Boot To The Rescue

Spring Boot is an opinionated framework design to simplify the bootstrapping and development of a Spring application. Spring itself is a powerful Java framework to build a scalable and efficient application. Spring Boot helps developers by having the most commons use-cases as its default configuration, thus where the opinionated term comes from. Whenever a developer need something different, they need to write the configuration for that different thing only. Otherwise, the Spring Boot app will ‘just run’.

REST API With Spring Boot

Spring Boot can also be set up to be a RESTful application with ease. In this tutorial we will build a Hero Association API, in which we can manage our heroes, report a disaster, assign heroes to solve disaster, and resolve disaster status.

What You Need

  1. Java IDE (IntelliJ IDEA recommended)
    This will help you a lot
  2. JDK 8
  3. Postman or similar HTTP Client
  4. MySQL server
    Create schema named hero

Initialize With Spring Initialzr

You need to build the project structure and initial configuration. To do this go to start.spring.io, select Generate a Gradle Project with Groovy and Spring Boot 2.0.4. As you can see here, we can use Java, Groovy, or Kotlin as the main programming language. There will be some difference between them, but the main concept is the same.

Then fill com.bukalapak for group name and hero for artefact. You can fill this with anything you want since it won’t do anything with the app, but the best practice is to fill project group or company as the group and project name as the artefact.

The last step is to fill the dependencies. Search and add these dependencies:

  1. Web: you want to build a web application.
  2. JPA: Java Persistence API; you want to connect to database.
  3. MySQL: you want to use MySQL database.
  4. DevTools: you want to utilize tools to make development easier.
  5. Actuator: you want to maintain the app for production and to see what endpoints are available.

Next click Generate Project button and Spring Initalizr will give you a .zip file as the project boilerplate. Download and extract this file to your computer. We will call this folder PROJECT_HOME.

Why Groovy?

Groovy is a newer-school language compared to Java but will be compiled to Java byte code so it can run on JVM. It’s build with Java but designed to bring back the fun side of Java programming. It is less strong-typed than Java and has many built-in utilities that is not provided by vanilla Java. To learn more about Groovy you can check it out here.

I have been working with Java for more than 8 years. It offers a strict, strong-typed syntax which I liked. However, in my opinion, Java is not as flexible as Groovy and, also in my opinion, Groovy is more suitable to rapid application development. One of the things I hate with Java is arithmetic. It is so confusing to read and write, but in Groovy you can write it as easy as .

First Configuration

By default Spring Boot web app doesn’t need any configuration, but you add MySQL as dependency and it needs a configuration to connect to a database. Open file and add the following code.

Now we need to initialize Gradle wrapper. Gradle is a dependency management we will use in this tutorial. With Gradle wrapper you can use a consistent Gradle version because the Gradle itself will be downloaded within the project scope. To initialize Gradle wrapper run the file. Gradle will start downloading if you haven’t already downloaded it.

Compared to the configuration without Spring Boot (vanilla Spring), this is MUCH MUCH more less and easier to maintain

Building The Application

At last you can start building the application. The application will consists of 4 parts.

  1. Models are the backbone; they create structure and serve as a working copy of the persisted data.
  2. Repositories are the interface between application logic and database.
  3. Services are where most of the application logic are located.
  4. Controllers are the gateway of the application and the outside world.

Models

This tutorial will guide you to build Models like this following diagram.

To do so, create a new folder named in . Then create 3 new files named , and inside , and fill these files with these following codes.

Ability.groovy

Hero.groovy

Disaster.groovy

As you can see above, there are Java annotations inserted to tell Spring what those classes are about.

  • will tell Spring data to register this class as a persisted entity that will be working copies of the data in the database. By default Spring uses Hibernate entity manager to save and load from databases and will use class name as table name. Hibernate will also use marked class properties as the column names and their types as the column types.
  • will tell Hibernate to use marked property as primary key.
  • will tell Hibernate to auto-generate primary key values. By default Hibernate will use a table which contains a sequence to track primary keys’ values. You will change this to use MySQL’s auto increment features by changing the to .
  • will tell Hibernate to add relation in the specified class to the property’s type. By default, Hibernate will auto load the related type from database (in this case, every time you load , you will automatically load ). You can disable this by changing to . Since you also want every has , change to to set this Foreign Key as .
  • will tell Spring not to include this when writing this class to JSON.

There is another way to do this: by putting the entities specifications in another files. In my experience, using annotations will make your code easier to read and maintain, but it ‘dirties’ your code. Some people prefer to put those in different files. It is just a matter of opinion though.

Repositories

After you specify the Models, you will need something as interface between this application and the Hibernate persistence manager. Therefore you need Repository interfaces. These interfaces are part of JPA dependency and there are several of them each is tailored to a specific use-case. In this tutorial, you need all Models to have its own Repository. To start creating Repositories, create a folder named in . Then write the following files inside the folder.

AbilityRepository.groovy

HeroRepository.groovy

DisasterRepository.groovy

Those are only interfaces, the implementation will be implemented by Spring so we don’t need to worry about it. offers a basic CRUD operations. is a subclass of so it does what its superclass does and adds paging and sorting features. Every Repository implementation will be managed by Spring (it is called Spring Bean or Spring Component) as a singleton instance that can be injected into other Spring Beans.

Services

You will write our application logic as Services. Create a folder called in , then write these following files inside.

HeroService.groovy

DisasterService.groovy

Every class with annotation will be a Spring Bean, usually Services will be injected into other Services or Controllers. In the codes above every Service is injected with Repository. You can do this by adding to a class property. Spring will search its registered Beans and inject the appropriate one. By using this kind of design, you don’t need to worry about instantiation, you just have to believe that it will be there when you need it and concentrate on writing your own code.

In my experience, in a small projects, you can skip Services and put the application logic in Controllers because it adds more complexity. However, please note that it will be VERY costly to refactor it later if the projects become larger. So, skip Services in projects you are SURE that they won’t get bigger.

Controllers

Everything else is set, now create endpoints so users can access your API. You will create Controllers to specify endpoints and handle users’ requests. First, create folder inside and write these files inside the newly created folder.

HeroController.groovy

DisasterController.groovy

Every Controllers are annotated with . This annotation makes your class a specific type of Spring Bean which can handle web requests and convert every return value to JSON format.

However, you need to specify the URL mapping for every controller. You can do this by adding annotations to Controllers’ methods. If you add this to the class, it will add a specified prefix to the method’s . , , , and are subclasses of with specific web request methods (, , , and respectively).

will tell Spring to parse the URL, transform the value to a specified type then inject it to parameter. will tell Spring to transform the request body to a specified type then also inject it to parameter.

There are also a special annotation called . This annotation will tell Spring to create a transaction for every request passed to this Spring Bean. You can also add to a single method or Services.

This is not even my final form yet

Controllers can do much more. However this tutorial scope will become too big if I try to show its true powers.

Running The Application

You have create your application structure in Models, database interfaces in Repositories, application logic in Services, and endpoints in Controllers. Now you can run your application by running . If you are getting an error like this

That means you are using Java version > 1.8. To solve this, go to and add inside . After that you can try to run it again.

By default the Spring Boot application will run in port 8080. For the first time you can send request to . Try sending this following JSON as request body with .

{
“name”: “Gatot Kaca”,
“abilities”: [
{ “name”: “Bones of Steel” },
{ “name”: “Muscles of Iron” },
{ “name”: “Fly” }
]
}

And you will get this following JSON as the result. Note that it has s already set. This means the request earlier has been saved to the database.

{
"id": 1,
"name": "Gatot Kaca",
"abilities": [
{
"id": 1,
"name": "Bones of Steel"
},
{
"id": 2,
"name": "Muscles of Iron"
},
{
"id": 3,
"name": "Fly"
}
]
}

You can also call the other endpoints. I’ll leave that up to you to try and have some fun with this application. If you want to build the JAR file, please run . It will be located in .

In my experience if you have a small project, JAR files are enough. You can register it as a operating system service or put it in a docker container. However, building a WAR file and put it in an application server such as Tomcat or Glassfish will offer many more configuration and will help you in a bigger projects.

But when did you ever touch the database?

Apart from creating schema, you have never touched it again. By specifying in the , Hibernate will update your tables, columns, relations, and indices every time you run the application. If Hibernate detect changes, it will try to update the tables. Most of the time it will run smoothly, but in some cases you need to update the database yourself.

In my experience this features helps a lot, especially if you’re doing a small to medium projects. In a bigger projects I suggest to disable this feature and get a database architect to do this task.

Conclusion

Spring Boot makes the development of Spring based application less hassle with near to none configuration. Combined with Groovy, the development of Java web application is more fun than ever. With Gradle we don’t need to download libraries manually. Since the project output is a JAR file, we don’t need to deploy to Java web server to run Spring Boot applications.

The full version source can be accessed in:

Resources

Inside Bukalapak

Stories and insights from the people inside Bukalapak

Iqbal Djulfri

Written by

Engineering Manager at Bukalapak

Inside Bukalapak

Stories and insights from the people inside Bukalapak

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade