JavaScript Required

We're sorry, but we doesn't work properly without JavaScript enabled.

Restful web services using spring

Large organizations maintain many web applications written in multiple languages. One could be a Java web development, another is a .NET application etc. There could be situations wherein cross application data sharing is required. As these applications are developed in different languages, and may be deployed in different operating systems data sharing in a conventional way is not possible. So, we need to have a language, platform independent way of sharing data. We will use web services for this purpose.

Web services uses XML or JSON formats for data transfer among the systems. The data is being offered as a service. In order to get the data from an application, we simply need to consume the service for that. The Web services works over the HTTP protocol. Apart from the above use cases, we can have applications that consume data from external third-party systems as well. The web service uses either SOAP or REST architecture. In this tutorial we will see REST web services in details. The sample code snippets are written using the popular Java framework Spring.

What is RESTful web service?

In RESTful web services are based on the Representational State Transfer (REST) architecture. These services are light weight and easily scalable. In REST everything is considered as a resource. Each resource is accessed by a common interface with HTTP methods like GET, PUT, POST etc.

Spring is a popular Java framework. It is light weight and we plug and play modules based on our need. It supports the RESTful web services. It has the provisions for creating a REST service and consume a service as well. We will see those in detail.

Create a REST service

Below tools are required for developing a Spring application for this.

  • Java 1.8
  • Intellij IDEA
  • Maven

First create a Maven project in Intellij editor. Then add the dependencies for Spring as shown below in pom.xml file.

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency>

This will add the spring-webmvc jar file as a dependency and we intend to use Spring version 4. This jar contains the necessary annotations for creating a REST endpoint. The jackson-databind contains the classes for converting a Java class to JSON. Our class has a REST endpoint which will produce JSON data and another endpoint that accepts JSON data. JSON is a programming language independent data format.

Create configuration

We will create the Java based Spring configuration for this. Create a Config.java under 'src' folder as below. Keep this in a proper package.

I have used 'com.sample' as the package name.

@Configuration @EnableWebMvc @ComponentScan(basePackages = "com.sample") public class Config { }

The above Config class uses annotation for the configuration. The @Configuration says this class contains configuration details. @EnableWebMvc annotation automatically detects the Jackson jar file in class path and register default JSON converter for the app. This converter is used to convert the Java object to JSON and vice versa. @ComponentScan annotation will scan the given package to find any Spring beans. Ie. The classes that are mapped with @RestController, @Service, @Repository etc. will be treated as Spring beans.

Now we need to create a model class.

public class Employee{ private Long id; private String name; // Parameterized constructor to set property values. //Getter and setter methods }

Next step is to create the REST endpoint. We will create an EmployeeController.java. This will have endpoints for handling the web service calls. Here we basically handle a GET request to get the details of an employee, and POST request to save the details of employee.

@RestController public class EmployeeController{ private static List employees; { employees = new ArrayList(); employees.add(new Employee(101, "John")); employees.add(new Employee(201, "Russ")); } @GetMapping("/employees/{id}") public ResponseEntity getEmployee(@PathVariable("id") Long id) { for(Employee employee: employees){ if(employee.getId() == id){ return new ResponseEntity(employee, HttpStatus.OK); } return new ResponseEntity(employee, HttpStatus.NOT_FOUND); } @PostMapping(value = "/employees") public ResponseEntity createEmployee(@RequestBody Employee employee) { employees.add(employee); return new ResponseEntity("CREATED", HttpStatus.OK); } }

In this above code sample @RestController annotation will define this class as a REST controller, which has endpoints defined for some url patterns. Each url patterns is mapped with some specific methods using @GetMapping or @PostMapping. The names of these annotations suggest the HTTP methods that they support. The POST mapped method will get the Employee JSON as the input and @RequestBody will convert that JSON to Employee object. In the GET mapped endpoint we can see @PathVariable annotation, which will be used to get the value passed as a path variable ie. {id} is mapped variable id.

We can test these endpoints by using Postman tool.

To get the details of Employee with id 101. Send a GET request to

localhost:8080/employees/101

In order to add an Employee data, we need to POST a request to localhost:8080/employee. Use below JSON in the request body.

{ "id" : "301", "name" : "Ed" }

This will add an employee data.

How to access a web service in Spring

Spring provides the classes for consuming any web service. In order to consume the above service, we need follow below steps.

Add below dependency in pom.xml. This Jar provides a RestTemplate class, which has methods to access REST web service.

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </dependency>

Then using the below code we can consume a web service.

RestTemplate restTemplate = new RestTemplate(); Employee employee= restTemplate.getForObject("localhost:8080/employees/101", Employee.class);

Conclusion:

Most of the programming languages provide support for creating the REST services. In this tutorial we have seen REST architecture and how to create a REST application using Spring. We just need to add the corresponding dependencies and define an endpoint that serves the data. Data is shared in the form of JSON in REST services. Spring also has provision for consuming the REST services as well. Any enterprise application would find the need of data sharing using the web services. This tutorial will give a basic idea of these services.

Ast Note

Some of our clients

team