I wanted to create an REST API service application which exposes a few services to create user(sign up) and get user creation result.

I have analyzed and thought of using some latest technologies in the market, so I ended up on Gradle + Spring boot + Swagger2 combination.

Let us see how can we create an app using the above combination.

First, we will quickly see what are those technologies.

Gradle
Gradle is a build automation and dependency management system that builds built upon concepts of apache ant, apache maven and introduces a groovy based domain specific language instead of XML (maven).Gradle

Spring boot
Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”. Spring Boot

Swagger
Swagger is a powerful open source framework backed by a large ecosystem of tools that helps you design, build, document, and consume your RESTful APIs.Swagger

Spring boot uses tomcat as a web server by default, but you can exclude tomcat and use ‘jetty’ instead of tomcat.

First step:
We have to create a folder(project folder) and run the following command to create gradle related artifacts in the project.

Folder name : springboot-gradle-swagger2-app

cd springboot-gradle-swagger2-app
gradle init --type java-library

Java-library is the project type to create. It creates maven folder structure and other stuff.

You can see the following file structure:

Second Step: (build.gradle)
In this step we update build.gradle file with all the required dependencies for spring boot , swagger2.
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.3.RELEASE")
}
}
// Apply the java plugin to add support for Java
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'application'
repositories {
maven { url "http://repo.spring.io/libs-snapshot" }
mavenCentral()
jcenter()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
// The production code uses the SLF4J logging API at compile time
compile ("org.slf4j:slf4j-api:1.7.21")
compile ("org.springframework.boot:spring-boot-starter-web:1.5.3.RELEASE")
compile ("org.springframework.boot:spring-boot-gradle-plugin:1.5.3.RELEASE")
testCompile ("org.springframework.boot:spring-boot-starter-test:1.2.3.RELEASE")
testCompile ("junit:junit:4.12")
compile ("io.springfox:springfox-swagger2:2.4.0")
compile ("io.springfox:springfox-swagger-ui:2.4.0")
}

We will need 2 dependencies for swagger, that are swagger2 and swagger-ui.

Third Step: – Create controller

In this step , we create a controller named ‘SignUpController.java’ to create users , retrieve users by email etc.
This is not calling any real service in fact, it is just a controller to demonstrate the basic rest functionality and swagger ui.

package com.mksiva.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.mksiva.dto.UserDO;
@RestController
@RequestMapping("/api")
public class SignUpController {

@RequestMapping(value = "", method = RequestMethod.GET)
public String status() {
return "MyApp Interface API Service is running!";
}

@RequestMapping(value = "/user/{email}", method = RequestMethod.GET)
@ResponseBody
public String getUserByEmail(@PathVariable("email") String email) {
return email;
}

@RequestMapping(value = "/userCreationResult/{email}", method = RequestMethod.GET)
@ResponseBody
public String userCreationResultByKey(@PathVariable("email") String email) {
return "User [" + email + "] creation is in progress...";
}

@RequestMapping(value = "/user", method = RequestMethod.POST, consumes = {
MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public String createUser(@RequestBody UserDO aUserDO) {
return aUserDO.getEmail();
}
}

Fourth Step: – Create Spring boot application class

In this step ,we create a java file called “Application.java” , this is the important file, to start spring boot application., this is where all the
application level configuration should go, Like Mapper(json to Object mappers) etc.

package com.mksiva.controller;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {

System.out.println("Let's inspect the beans provided by Spring Boot:");

String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
};
}
}

Fifth Step: – Swagger config

In this step, we will create “SwaggerConfig.java” to configure swagger and it is target REST ent points mapping using annotations.

package com.mksiva.controller;

import static springfox.documentation.builders.PathSelectors.regex;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.mksiva.controller"))
.paths(regex("/api.*")) // .paths(postPaths()) PathSelectors.ant("/api/*")
.build()
.apiInfo(apiInfo());
}

private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo(
"MyApp REST API",
"To interface with MyApp from any other applications.",
"MyApp API",
"Terms of service",
"",
"",
"API license URL");
return apiInfo;
}
}

Sixth Step: – creating Data Transfer Object
In this step , we will create a entity or data object called ‘UserDO.java”. and it is needed to be passed as a parameter to rest service, so that
the json input format is derived from this class.
package com.mksiva.dto;

import io.swagger.annotations.ApiModelProperty;

public class UserDO {
@ApiModelProperty(required = true)
private String name;

@ApiModelProperty(required = true)
private String email;

@ApiModelProperty(required = true)
private String phone;

private String aboutMe;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public String getAboutMe() {
return aboutMe;
}

public void setAboutMe(String aboutMe) {
this.aboutMe = aboutMe;
}
}

Seventh Step: – Checking the application files:

We should be having the following files in order to start spring boot application.

  1. SignUpController.java
  2. Application.java
  3. SwaggerConfig.java
  4. UserDO.java

The following is the files list:

Eighth Step: – Gradle commands

1. >gradle eclipse – To make the project as a eclipse project
2. >gradle build – To build the project
2. >gradle bootRun – To build the project and start the spring boot application.

We will now start the rest server:

> gradle bootRun

You can see the server starts up:


Now the Spring boot server is started, it is a tomcat server , that runs on port 8080.

You can access application by typing http://localhost:8080/api :
You will see the message “MyApp Interface API Service is running!”.

You can also check all the rest services provided by our application using swagger explorer. It is very useful and you can test the rest api from
there itself, if you want.

Try Swagger API explorer (http://localhost:8080/swagger-ui.html)

From this swagger explorer, you can see the REST API available,

what is the input and what it does and other important details.

That’s it. Have fun.