The idea of this Post will be to show how we can expose a Rest Service in OSB, so in this first part we will create a small Rest API using JAVA SpringBoot.
But what is an API ?
Application Programming Interface, this is a set of routines and standards established and documented by an application A, so that other applications can use the features of this application A, without needing to know details of the software implementation.
And what is Rest ?
Representational State Transfer (REST) consists of principles / rules / constraints that, when followed, allow the creation of a project with well-defined interfaces. communicate.
And what’s the difference between Rest and RESTful ?
The difference is only grammatical. In other words, systems that use the REST principles are called RESTful.
Rest: Set of architectural principles
RESTful: Ability of certain system to apply the principles of REST
The exposure of the Rest Service on the OSB will be divided into Parties as below so that I can detail each step as much as possible, check the Link of each to see the other Parties:
- Part 1: Creating a Rest API
- Part 2: Transforming Xml into Json Java
- Part 3: Expsomg Rest Servoce (Coming soon)
- Part 4: Exposing the Proxy using Java Callout (Coming soon)
- Part 5: Exposing in the Proxy using native process (Coming soon)
The idea of the Post is not to explain how Spring Boot works nor its annotations, but I will try to explain at least what I am using that in this first step will be to create only a HelloWorld because it will be enough to understand and implant any API Rest
On the https://start.spring.io let’s create a SpringBoot project as below
See below that we have selected only the “Web” Dependencies that are the default for creating the project and “DevTools” so that we can make changes to the code without having to restart our TomCat.
In Name and Artifact put helloworld and in Package Name put br.com.uanscarvalho.helloworld as below:
After this click the Generate Project button as below to create our project
After saving the project to a folder of your choice:
Now extract the file in your workspace, see below where my project was:
Now let’s import this project into Eclipse. In my case I will use the Eclipse Spring Tool Suite.
In eclipse, just click on File –> import –> import and on the screen below click Maven –> Existing Maven Projects
See below how my project was after being imported:
See below how the pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
<relativePath />
<!-- lookup parent from repository -->
</parent>
<groupId>br.com.uans</groupId>
<artifactId>helloworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>helloworld</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Now in Eclipse do the Clean and install Maven so that the necessary dependencies can be installed pom.xml
See below that the HelloworldApplication.java class was created automatically with the annotation @SpringBootApplication
The @SpringBootApplication annotation is a convenience note that contains the following Spring annotations: @Configuration, @EnableAutoConfiguration, and @ComponentScan. These last two basically tell the Spring initializer: “Search and instantiate every annotated bean of this packet forward.”
A Little About Annotations:
@Configuration:
It is an annotation that indicates that certain class has methods that expose new beans.
@EnableAutoConfiguration:
Used by Spring Boot to try to guess the settings needed to run your project @ EnableAutoConfiguration, which is perhaps the most important of this package. This is another Spring Boot annotation that indicates the need for the auto configuration of your project. Because of the existence of it will be triggered the process of analysis of the classes present in your classpath so that several of the settings that we accustomed to do are avoided. For example, when Hibernate jars are found, a LocalEntityManagerFactoryBean will already be automatically configured so that you can create EntityManager in your project. Another example is the automatic configuration of the embedded servlet container, when you add the Tomcat starter in your project.
@ComponentScan:
In general you use it in configuration classes (@Configuration) indicating which packages or classes should be scanned by Spring for this configuration to work
Now in Eclipse create the HelloworldController class as below
Inside the HelloworldController Class we will have the following code:
package br.com.uanscarvalho.helloworld;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloworldController {
@RequestMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
public String welcome(@RequestParam(value="nome", required=false) String nome) {
return "Ola " + nome;
}
}
Just for content see below another way to leave our class that in the end would have the same effect, here I show just one of many ways to pass the parameter to our method and for tests in the end we would make a call in the browser like this:
@RequestMapping(value = "/{nome}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
public String welcome(@PathVariable("nome") String nome) {
return "Ola " + nome;
}
Understanding a little of what was done, here I remember that my intention is just to explain the basics of what we are doing since there are several ways to do the same thing.
@Controller: It is used to signal that the class is a Spring MVC Controller.
@RestController: This annotation automatically adds the annotation @Controller and @ResponseBody and does nothing else, in which case every service return will be transformed to a JSON.
@RequestMapping: Used over methods of a class annotated with @Controller or @RestController .
See below some parameters that we can use in this annotation RequestMapping
value = “/” It is for you to put the addresses of your application, in our case for example @RequestMapping(value = “/” ) which when accessed by a client, should be directed to the given method (“/”), could be any name, for example (“/cliente”).
produces = MediaType.APPLICATION_JSON_VALUE Here we are saying to the method that our return must be a JSON .. if we wanted it to be an XML we would useAPPLICATION_XML_VALUE
but if we have to specify that we will pass a JSON as a request then we will paste the option consumes= MediaType.APPLICATION_JSON_VALUE
method = RequestMethod.GET here we are saying the method http should be a GET, if this property is omitted the method would pass all the methods (GET, POST, PUT, DELETE, etc.)
(@RequestParam(value = “nome”, required = false) String nome)Here I am telling the method that it should expect as a parameter a name “name” that should be a String, ie when accessing “/? Name = YourNameHere” the name parameter will assign the variable “name”, and if the parameter does not is past, what will happen? An error will be returned: “Required String parameter ‘nome’ is not presente”. Mif you do not want the parameter to be mandatory, just map it as “@RequestParam(required = false)”, and see how the name gets null, and no error is returned. The use will depend on your need.
@ResponseBody Used in methods annotated with @RequestMapping to indicate that the method’s return should be automatically written in the response to the client. Very common when we want to return JSON or XML due to some object in the application.
Above you saw that there are several ways to create a simple HelloWorld, right? However, for a slightly more real case, I suggest that you start from the class below because in it we will pass a parameter that is the most common way where applications need parameters to be passed (in the vast majority of cases).
Class HelloworldController Principal:
Then create the class as follows:
package br.com.uanscarvalho.controller;
import org.springframework.http.MediaType;
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 br.com.uanscarvalho.bean.Pessoa;
import br.com.uanscarvalho.bean.Response;
@RestController
public class HelloworldController {
@RequestMapping(value = "/hello", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
public @ResponseBody Response welcome(@RequestBody Pessoa pessoa) {
Response response = new Response();
response.setMensagem("Ola " + pessoa.getNome());
return response;
}
}
Without going into too much detail, what we have added here is the annotation @RequestBody where Spring will try to convert its return value and write it to the http response automatically and the @ResponseBody that we use when we want to return a JSON. We also created a Bean called Pessoa that will contain the value that we will pass on to the Body and another Bean called Response that will contain our response from the application.
Now in Eclipse create the package br.com.uanscarvalho.bean and the class Pessoa as below
Now inside Bean Pessoa add the following code:
package br.com.uanscarvalho.bean;
public class Pessoa {
private String nome;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}
Now within Bean Response add the following code:
Agora dentro do Bean Response adicione o seguinte codigo:
package br.com.uanscarvalho.bean;
public class Response {
private String mensagem;
public String getMensagem() {
return mensagem;
}
public void setMensagem(String mensagem) {
this.mensagem = mensagem;
}
}
Let’s test our application now:
To do this, execute the file HelloworldApplication by right clicking on the class then in Run As -> Spring Boot App
Note: If you receive an error saying Address already in use just go to the application.properties file and put “server.port = 9000” to change your port for example to port 9000 or whatever you want as shown below
Now the result should look like this … see the Console tab:
Now let’s test our simple application
To test I will use Postman as below but feel free to use whatever you prefer, such as SOAPUI for example:
Then configure it to call the URL http://localhost:9000/hello and then add the following Request in Json format
{
"nome": "Uans"
}
See below how the whole configuration, Request and Response was after we called our application
Below the link to find the ready code directly on GitHub
https://github.com/uanscarvalho/HelloWorld.git
Hugs and see you soon
/:-D