The following two tabs change content below.
Hi, I have written and developed this site to share my experience and ideas with other colleagues. I also started to prepare interview questions and answers for job seekers. I hope it will help you a lot.

In this post I am trying to explain RESTful webservice development using Spring. Before to start REST development process I am just going to give short description about REST and Spring framework and during the REST api development I will give the example of all stateless operation like GET (Download project source code from GitHub) , POST, DELETE etc.

What is REST?

REST (Representational State Transfer) is an architectural style, and an approach to communications that is often used in the development. REST is an architectural style for designing distributed systems. It is not a standard but a set of constraints, such as being stateless, having a client/server relationship, and a uniform interface. REST is not strictly related to HTTP, but it is most commonly associated with it.

What is Spring?

Spring is the most popular application development framework for enterprise Java. Millions of developers around the world use Spring Framework to create high performing, easily testable, and reusable code. Spring is lightweight and open source framework. It has a large and active community that provides continuous feedback based on a diverse range of real-world use cases. This has helped Spring to successfully evolve over a very long time.

Spring have many features some of them I am explaining in below section:

Spring enables the developers to develop the enterprise applications using POJOs (Plain Old Java Object). The benefit of developing the applications using POJO is, that we do not need to have an enterprise container such as an application server but we have the option of using a robust servlet container.

Spring comes with some of the existing technologies like ORM framework, logging framework, J2EE and JDK Timers etc, Hence we don’t need to integrate explicitly those technologies.

Spring WEB framework has a well-designed web MVC framework, which provides a great alternate to web framework.
Spring can eliminate the creation of the singleton and factory classes.

Spring framework is both complete and modular, because spring framework has a layered architecture.
Spring provides a consistent transaction management interface that can scale down to a local transaction and scale up to global transactions (using JTA).

Spring framework includes support for managing business objects and exposing their services to the presentation tier components, so that the web and desktop applications can access the same objects.
Spring framework has taken the best practice that have been proven over the years in several applications and formalized as design patterns.

Spring application can be used for the development of different kind of applications, like standalone applications, standalone GUI applications, Web applications and applets as well.

Now starting with REST api how to develop using spring framework

HTTP methods

GET requests a representation of the specified resource. Note that GET should not be used for operations that cause side-effects, such as using it for taking actions in web applications. One reason for this is that GET may be used arbitrarily by robots or crawlers, which should not need to consider the side effects that a request should cause.

Example

The service will handle GET requests for http://localhost:8080/getEmployee  optionally with a name parameter in the query string. The GET request should return a 200 OK response with JSON in the body that represents a greeting. It should look something like this:

Request URL:

http://localhost:8080/getEmployee?name=sharma

Response

{
“eName”: “sharma”,
“salary”: 10000,
“phone”: “9810093311”
}

Example explanation 

Before to start development we need to put required maven dependency as given below :

<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/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.kpblogs</groupId>
 <artifactId>rest-api</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>rest-api</name>
 <url>http://maven.apache.org</url>
 <parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>1.5.8.RELEASE</version>
 </parent>
 <dependencies>
 <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>com.jayway.jsonpath</groupId>
 <artifactId>json-path</artifactId>
 <scope>test</scope>
 </dependency>

</dependencies>

<properties>
 <java.version>1.8</java.version>
 </properties>


 <build>
 <plugins>
 <plugin>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-maven-plugin</artifactId>
 </plugin>
 </plugins>
 <finalName>rest-api</finalName>
 </build>
</project>

1. Create Employee model class with required fields like I am using eName, salary, phone.

Employee.java

package com.kpblogs.model;

public class Employee {

private String eName;
 private int salary;
 private String phone;
 public String geteName() {
 return eName;
 }
 public void seteName(String eName) {
 this.eName = eName;
 }
 public int getSalary() {
 return salary;
 }
 public void setSalary(int salary) {
 this.salary = salary;
 }
 public String getPhone() {
 return phone;
 }
 public void setPhone(String phone) {
 this.phone = phone;
 }
}

Note: Spring uses the Jackson JSON library to automatically marshal instances of type Greeting into JSON.

2. Resource Controller
To build RESTful web services, HTTP requests are handled by a controller. These components are easily identified by the @RestController annotation below is the MainController.java code with /getEmployee

MainController.java
package com.kpblogs.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.kpblogs.model.Employee;

@RestController
public class MainController {

@RequestMapping("/getEmployee")
 public Employee getEmployee(@RequestParam(value="name", defaultValue="Khushvinder") String name) {
 Employee employee = new Employee();
 employee.seteName(name);
 employee.setPhone("981009xxxxx");
 employee.setSalary(10000);
 return employee;
 }
}

The @RequestMapping annotation ensures that HTTP requests to /getEmployee are mapped to the getEmployee() method of RestController (MainController.java)

In the above example I am not specifying the method for RequestMapping because GET is the default method. if you want to change method then try below code:
@GetMapping(“/getEmployee”)

@RequestParam binds the value of the query string parameter name into the name parameter of the getEmployee() method.
This query string parameter is explicitly marked as optional if it is absent in the request, then default value of name whould be “khushvinder”

If we want to make compulsory name value in request then pass required=true in RequestParam.

 

3. You package everything in a single, executable JAR file, driven by a good old Java main() method. Along the way, you use Spring’s support for embedding the Tomcat servlet container as the HTTP runtime, instead of deploying to an external instance.So simple approch to test our API create standalone application using @SpringBootApplication annotation. below is the code of application:

Application .java

package com.kpblogs;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

@SpringBootApplication is a convenience annotation that adds all of the following:

1. @Configuration tags the class as a source of bean definitions for the application context.

2. @EnableAutoConfiguration tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. Normally you would add @EnableWebMvc for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.

3. @ComponentScan tells Spring to look for other components, configurations, and services in the hello package, allowing it to find the controllers. The main() method uses Spring Boot’s SpringApplication.run() method to launch an application. Did you notice that there wasn’t a single line of XML?

No web.xml file either. This web application is 100% pure Java and you didn’t have to deal with configuring any plumbing or infrastructure.

4. If you are using Eclipse IDE then directly open Application.java and right client and then run as Java application. Internally SpringBootApplication initialize the Tomcat container and will open on the default 8080  port. We can also create JAR file from our project and run that using below command:

Using Maven, you can run the application using ./mvnw spring-boot:run.

Or you can build the JAR file with ./mvnw clean package.

Then you can run the JAR file: java -jar target/rest-api-0.1.0.jar

Below is the screenshot of GET method

Rest-api-get
Rest-api-get

Download project source code from GitHub

330 total views, 2 views today

Leave a Reply

Your email address will not be published. Required fields are marked *