Enable Javascript

Please enable Javascript to view website properly

Toll Free 1800 889 7020

Looking for an Expert Development Team? Take 2 weeks Free Trial! Try Now

Restful web services using spring

Many big companies have several web apps that might be developed using a variety of different programming languages. One could be a Java web development, another is a .NET application etc. In some cases, cross application data sharing might be needed. As the apps are developed using diverse programming languages, data sharing might not be very convenient, also considering that they might also be deployed in various operating systems. So, we need to have a language, platform independent way of sharing data. We will use web services for this purpose.

Web services mostly use either JSON or XML formats for data transfer between a wide range of systems. The data is being offered as a service. If data is required from an all, the service needs to the consumed 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. Either SOAP or REST architecture is used most probably by the web service. In this tutorial, REST web services will be thoroughly used. We have written the sample code snippets using the 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. To access a resource, a common interface is used. The commonly used HTTP methods are POST, GET, PUT and more.

Spring is a popular Java framework. It is a lightweight and easy to use framework. 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

Here’s what you need for developing a Spring application:

  • 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. I.e. 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 i.e. {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:

REST architecture is quite popular, therefore, many programming languages offer the support to create the REST services. We already covered the process of creating and using the REST architecture and application using Spring. Afterwards, the users will need to add the corresponding dependencies. Also, they will need to define an endpoint which serves the data. JSON is used for data sharing in REST services. Spring can consume the REST services too. This tutorial will give a basic idea of the web services.

Software Development Team
Need Software Development Team?
captcha
🙌

Thank you!
We will contact soon.

Oops! Something went wrong.

Recent Blogs

Categories

NSS Note
Trusted by Global Clients