dineshonjava

Spring REST Web Services Interview Questions and Answers

Spring REST Web Services Interview Questions and Answers
In this tutorial, I am putting collection of frequently asked important spring REST web services interview questions with answers. It will be help in the Spring REST related questions in the interview. You could also read my another articles related to Spring interview questions with answers for helping in the Spring related interviews. These articles listed as below.

Let's see the below questions related to Spring REST web services.

Spring REST Service Interview Questions
  1. Define Web Service?
  2. What does REST stand for? and what is RESTful web services?
  3. What is differences between RESTful web services and SOAP web services?
  4. What is a resource?
  5. What are safe REST operations?
  6. What are idempotent operations? Why is idempotency important?
  7. Is REST scalable and/or interoperable?
  8. What are the advantages of the RestTemplate?
  9. Which HTTP methods does REST use?
  10. What is an HttpMessageConverter?
  11. Is REST normally stateless?
  12. What does @RequestMapping do?
  13. Is @Controller a stereotype? Is @RestController a stereotype?
  14. What is the difference between @Controller and @RestController?
  15. When do you need @ResponseBody?
  16. What does @PathVariable do?
  17. What is the HTTP status return code for a successful DELETE statement?
  18. What does CRUD mean?
  19. Is REST secure? What can you do to secure it?
  20. Where do you need @EnableWebMVC?
  21. Name some common http response codes. When do you need @ResponseStatus?
  22. Does REST work with transport layer security (TLS)?
  23. Do you need Spring MVC in your classpath for Spring REST?

1. Define Web Service?
A web service is a kind of software that is accessible on the Internet. It makes use of the XML messaging system and offers an easy to understand, interface for the end users.

2. What does REST stand for? and what is RESTful web services?
REST stand for REpresentational State Transfer, term by Roy Fielding. REST is an architectural style that describes best practices to expose web services over HTTP with Emphasizes scalability. Web services written by apply REST Architectural concept are called RESTful web services which focus on System resources and how state of Resource should be transferred over http protocol to a different clients written in different languages. In RESTful web services http methods like GET, PUT, POST and DELETE can can be used to perform CRUD operations. Read more about REST.

3. What is differences between RESTful web services and SOAP web services?
1) REST is more simple and easy to use than SOAP
2) REST uses HTTP protocol for producing or consuming web services while SOAP uses XML.
3) REST is lightweight as compared to SOAP and preferred choice in mobile devices and PDA's.
4) REST supports different format like text, JSON and XML while SOAP only support XML.
5) REST web services call can be cached to improve performance.

4. What is a resource?
The key abstraction of information in REST is a resource. Any information that can be named can be a resource like Student, Employee etc. REST is resource based API. Expose resources through URIs like http://localhost:8080/api/employees/1111, It is based on Model nouns, not verbs. Resources support limited set of operations – GET, PUT, POST, DELETE in case of HTTP. Example: update an employee use PUT to /employees/1111 and don't POST to /employees/edit?id=1111 and Resources can support multiple representations like HTML, XML, JSON etc. Multiple URIs may refers to same resource as like CRUD operation on employee resource using HTTP verbs. Read More>>>

5. What are safe REST operations?
Safe REST operations are HTTP methods that do not modify resources. For example, using GET or HEAD on a resource URL, should NEVER change the resource. But it is still possible, that safe operations do change things on a server or resource. For example: GET http://localhost:8080/api/employees/1111/delete HTTP/1.1 but it is incorrect, this would actually delete the employee i.e. Safe methods are methods that can be cached, prefetched without any repercussions to the resource.

6. What are idempotent operations? Why is idempotency important?
Idempotent operations are those HTTP methods that can be called repetitively many times without different outcomes. It would not matter if the method is called only once, or many times over. The result should be the same. Again, this only applies to the result, not the resource itself.
Consider the following examples:

a = 4; (is idempotent)
a++; (is not idempotent)

Idempotency is important in building a fault-tolerant API. Suppose a client wants to update a resource through POST. Since POST is not a idempotent method, calling it multiple times can result in wrong updates. What would happen if you sent out the POST request to the server, but you get a timeout. Is the resource actually updated? Does the timeout happened during sending the request to the server, or the response to the client? Can we safely retry again, or do we need to figure out first what has happened with the resource? By using idempotent methods, we do not have to answer this question, but we can safely resend the request until we actually get a response back from the server.

HTTP Method Idempotent Safe
OPTIONS yes yes
GET yes yes
HEAD yes yes
PUT yes no
POST no no
DELETE yes no
PATCH no no

7. Is REST scalable and/or interoperable?
Yes, REST is scalable and interoperable.

8. What is the RestTemplate and It's advantages?
In Spring REST client, The RestTemplate is the core class for client-side access to Spring RESTful web services. It communicates HTTP server using RESTful constraints. It is very similar to other template classes in the Spring like JdbcTemplate and HibernateTemplate etc. In Spring, RestTemplate provides higher level implementation of corresponding HTTP methods such as GET, POST, PUT, DELETE, HEAD etc. It provides the methods to communicate by using these HTTP methods with URI template, URI params, request object and response type as arguments. Read More about RestTemplate.


9. Which HTTP methods does REST use?
RestTemplate provides higher level implementation of corresponding HTTP methods such as GET, POST, PUT, DELETE, HEAD etc.

10. What is an HttpMessageConverter?
HttpMessageConverter is a strategy interface that specifies a converter that can convert from and to HTTP requests and responses. Internally Spring MVC uses it to convert the Http request to an object representation and back. Message converters are used to marshall and unmarshall Java Objects to and from JSON, XML, etc – over HTTP. Read More about HttpMessageConverter in Spring.


11. Is REST normally stateless?
Yes.

12. What does @RequestMapping do?
@RequestMapping can be applied to the controller class as well as methods. This annotation for mapping web requests onto specific handler classes and/or handler methods. Read more about @RequestMapping annotation.


13. Is @Controller a stereotype? Is @RestController a stereotype?
Yes.

14. What is the difference between @Controller and @RestController?
The key difference between a traditional Spring MVC @Controller and the RESTful web service @RestController is the way the HTTP response body is created. While the traditional MVC controller relies on the View technology, the RESTful web service controller simply returns the object and the object data is written directly to the HTTP response as JSON/XML by registered HttpMessageConverters.

15. When do you need @ResponseBody?
When you use the @ResponseBody annotation on a method, Spring converts the return value and writes it to the http response automatically. Each method in the Controller class must be annotated with @ResponseBody.

16. What does @PathVariable do?
@PathVariable is used to pass parameter along with the url, sometimes we need to pass parameters along with the url to get the data. Spring MVC provides support for customizing the URL in order to get data. To achieving this purpose @PathVariable annotation is used in Spring mvc framework. Read More about PathVariable.

17. What is the HTTP status return code for a successful DELETE statement?
Either we can return HTTP status 204 (NO CONTENT) with no response body or return HTTP status 200 (OK) along with a response body with representation of the deleted item.

18. What does CRUD mean?
In Spring REST, the primary or most-commonly-used HTTP verbs are POST, GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and delete (or CRUD) operations, respectively.

19. Is REST secure? What can you do to secure it?
REST is nothing but it architectural desgin or paradigms to design restful web service. So REST does not provide any security constraints by default but we can implement it in the RESTful web services by using security layers like transport layer security (TLS), auth token security.

20. Where do you need @EnableWebMVC?
@EnableWebMvc- It used for enabling spring mvc behavior i.e. it is responsible for registering Spring MVC required Bean Post Processors in the application as like Jackson2JsonMessageConverter etc.

21. Name some common http response codes. When do you need @ResponseStatus?

  • 2xx Success
    • 200 OK
    • 201 Created
    • 204 No Content
  • 3xx Redirection
    • 304 Not Modified
  • 4xx Client Error
    • 400 Bad Request
    • 401 Unauthorized
    • 403 Forbidden
    • 404 Not Found
    • 409 Conflict
  • 5xx Server Error
    • 500 Internal Server Error
    • 503 Service Unavailable

@ResponseStatus annotation available on custom exceptions and to map these exceptions to HTTP status codes.

22. Does REST work with transport layer security (TLS)?
Yes. Transport Layer Security can encrypt the communication to a RESTful Webservice and authenticate the server to a client.

23. Do you need Spring MVC in your classpath for Spring REST?
Yes, Spring REST uses the Spring MVC annotations like @RestController, @RequestBody and @ResponseBody etc.




Customizing HttpMessageConverter with Spring MVC in REST

Customizing HttpMessageConverter with Spring MVC in REST
HttpMessageConverter is a strategy interface that specifies a converter that can convert from and to HTTP requests and responses in Spring REST Restful web services. Internally Spring MVC uses it to convert the Http request to an object representation and back. Let's see following code for REST endpoint service.

@RestController
public class AccountController {
  @PostMapping("/account")
  public Account create (@RequestBody Account account){
     return accountService.create(account);
  }
}

Sending Request
Let's see API call for this endpoint. REST client consumes this endpoint with JSON object and we can specify "Content-Type" to be "application/json"

POST /restapi/account/ HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Cache-Control: no-cache

{
"name":"Arnav Rajput",
"city":"Noida",
"balance":4000202.33
}

Getting Response
We get back a 200 OK – a successful response as below:

HTTP/1.1 200 OK
Content-Type ?application/json;charset=UTF-8
Date ?Thu, 30 Mar 2017 12:46:49 GMT
Server ?Apache-Coyote/1.1
Transfer-Encoding ?chunked
{
  "accountId": 1,
  "name": "Arnav Rajput",
  "city": "Noida",
  "balance": 4000202.33
}

Client-Server Communication for this API Endpoint:

  • REST Client sends a POST request to /restapi/account/ with the Accept header set to application/json to get all Account resources as Json
  • AccountController is hit and returns the corresponding Account Java object as response
  • Now Spring Framework then uses one of the Jackson message converters to marshall and unmarshall Java Objects to and from JSON over HTTP.


In this above code we are using @RestController, it is actually combination of @ResponseBody and @Controller as of Spring 4.0, before it we have to specify with handler method as below:

@RequestMapping(value="/account", method=RequestMethod.POST)
public @ResponseBody Account create (@RequestBody Account account){
 return accountService.create(account);
}  

@ResponseBody
In Spring MVC, @ResponseBody annotation on a AccoutnController method indicates to Spring that the return Account object of the method is serialized to JSON directly to the body of the HTTP Response. It uses "Accept" header to choose the appropriate Http Converter to marshall the object.

@RequestBody
In Spring MVC, @RequestBody annotation on the argument of a AccountController method create (@RequestBody Account account) – it indicates to Spring that the body of the HTTP Request (either in JSON or XML) is deserialized to that Account Java Object. It uses "Content-Type" header specified by the REST Client will be used to determine the appropriate converter for this.

Default Message Converters in Spring MVC
In Spring MVC Framework, there is a set of default converters automatically registered which supports a whole range of different resource representation formats - json, xml for object. In RestTemplate in Spring REST, objects passed to and returned from the methods of RestTemplate class like getForObject(), postForLocation(), and put() are converted to HTTP requests and from HTTP responses by registered HttpMessageConverters.

  • StringHttpMessageConverter: it converts Strings from the HTTP request and response.
  • FormHttpMessageConverter: it converts form data to/from a MultiValueMap<String, String>.
  • ByteArrayHttpMessageConverter: it converts byte arrays from the HTTP request and response.
  • MappingJackson2HttpMessageConverter: it converts JSON from the HTTP request and response.
  • Jaxb2RootElementHttpMessageConverter: it converts Java objects to/from XML.
  • SourceHttpMessageConverter: it converts javax.xml.transform.Source from the HTTP request and response.
  • AtomFeedHttpMessageConverter: it converts Atom feeds.
  • RssChannelHttpMessageConverter: it converts RSS feeds.

Customizing HttpMessageConverters with Spring MVC
Let's see Spring MVC configuration file.

@Configuration
@EnableWebMvc
@ComponentScan("com.doj.restapi.web.controller")
public class WebConfiguration{
 
}

In the above MVC configuration file, we are using @EnableWebMvc annotation, it automatically registered default Http message converters with application as listed above according to available library in the class path. Now, if there is a need to customize the default message converters in some way. Spring provides a WebMvcConfigurerAdapter class, which allow us to change the default list of Http Converters with our own. Now let's below changed configuration class for Spring MVC.

/**
 * 
 */
package com.doj.restapi.web.config;

import java.util.List;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @author Dinesh.Rajput
 *
 */
@Configuration
@EnableWebMvc
@ComponentScan("com.doj.restapi.web.controller")
public class WebConfiguration extends WebMvcConfigurerAdapter{
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
 converters.add(createXmlHttpMessageConverter());
        converters.add(new MappingJackson2HttpMessageConverter());
        super.configureMessageConverters(converters);
    }
    private HttpMessageConverter<Object> createXmlHttpMessageConverter() {
        MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();
        XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
        xmlConverter.setMarshaller(xstreamMarshaller);
        xmlConverter.setUnmarshaller(xstreamMarshaller);
        return xmlConverter;
    }
}


Make sure that XStream library should be in the classpath of application. Here we are creating a new converter, the MarshallingHttpMessageConverter and we are using the Spring XStream support to configure it.

Summary
In this tutorial, we have seen how Spring MVC allows us to specify and fully customize Http Message Converters to automatically marshall/unmarshall Java Entities to and from XML or JSON.



Spring Restful Web Services XML CRUD Example

In this spring rest tutorial, we will create restful web services Crud APIs by using HTTP verbs GET, POST, PUT and Delete and returning XML representations of resources. In previous post, we have created a Spring Restful web services CRUD based example which returns json. In this post, we will see same example Spring Restful web services CRUD based on which will return xml.

If you want to learn more about REST you could read my previous article What is REST? Architecture and it's Constraints. And also I have discussed how to consume Spring RESTful web services by RestTemplate read this article.

Technologies used in this example

  • Spring webmvc
  • Spring Data JPA
  • JAXB
  • Hibernate Entity Manager
  • H2 in-memory database


Let's see steps to create a simple Spring Restful web services crud example which will return XML.

Step 1: Create a Dynamic web project using maven.

Project Structure
Spring Restful Web Services XML CRUD Example

Download Source Code from GitHub
Spring Restful Web Services XML CRUD Example


Step 2: Maven dependency for this application.
In pom.xml, there are following dependency required for this application.

<properties>
   <spring.version>4.3.5.RELEASE</spring.version>
   <spring.data.version>1.11.1.RELEASE</spring.data.version>
   <h2.version>1.4.193</h2.version>
  </properties>
  
  <dependencies>
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-webmvc</artifactId>
     <version>${spring.version}</version>
 </dependency>
 
 <dependency>
     <groupId>org.springframework.data</groupId>
     <artifactId>spring-data-jpa</artifactId>
     <version>${spring.data.version}</version>
 </dependency>
 
 <dependency>
     <groupId>com.h2database</groupId>
     <artifactId>h2</artifactId>
     <version>${h2.version}</version>
 </dependency>
 
 <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>5.1.0.Final</version>
 </dependency>
  </dependencies>

If you want to include JSON response support as well then you need to do is include Jackson libraries into classpath, same APIs will work for jackson as well.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.0</version>
</dependency>

Step 3: Creating Spring Configuration files for this application
Here we are using Java based configuration. So let's see following configuration java classes for this example.

a) Spring Configuration class for Spring MVC

RestApplicationConfig.java
/**
 * 
 */
package com.doj.restapi.web.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

/**
 * @author Dinesh.Rajput
 *
 */
@Configuration
@EnableWebMvc
@ComponentScan("com.doj.restapi.web.controller")
public class RestApplicationConfig{
 
}

b) Spring Configuration for application Infrastructure

This file has configuration about application core services like DB connection, DataSource and also scan the packages for service classes and repositories i.e. Non web components.

InfrastructureConfig.java
/**
 * 
 */
package com.doj.restapi.config;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

/**
 * @author Dinesh.Rajput
 *
 */
@Configuration
@ComponentScan("com.doj.restapi.service")
@EnableJpaRepositories("com.doj.restapi.repository")
public class InfrastructureConfig {
 
 @Bean
 public DataSource dataSource() {
  return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
 }

 @Bean
 public JpaVendorAdapter jpaVendorAdapter() {
  HibernateJpaVendorAdapter bean = new HibernateJpaVendorAdapter();
  bean.setDatabase(Database.H2);
  bean.setGenerateDdl(true);
  return bean;
 }

 @Bean
 public LocalContainerEntityManagerFactoryBean entityManagerFactory(
   DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
  LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
  bean.setDataSource(dataSource);
  bean.setJpaVendorAdapter(jpaVendorAdapter);
  bean.setPackagesToScan("com.doj.restapi.bean");
  return bean;
 }

 @Bean
 public JpaTransactionManager transactionManager(EntityManagerFactory emf) {
  return new JpaTransactionManager(emf);
 }
}

Step 4: Creating Web Application Initializer file for this application
In this example we are using Java Based web application configuration instead of traditional web.xml file and for this we have required at least tomcat 7 and servlet 3.0+ .

RestApplicationInitializer.java

/**
 * 
 */
package com.doj.restapi.web;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import com.doj.restapi.config.InfrastructureConfig;
import com.doj.restapi.web.config.RestApplicationConfig;

/**
 * @author Dinesh.Rajput
 *
 */
public class RestApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

 @Override
 protected Class<?>[] getRootConfigClasses() {
  return new Class[] { InfrastructureConfig.class };
 }

 @Override
 protected Class<?>[] getServletConfigClasses() {
  return new Class[] { RestApplicationConfig.class };
 }

 @Override
 protected String[] getServletMappings() {
  return new String[] { "/" };
 }
}


Step 5: Creating Application classes
In this application, we will create and read account resource from account repository.
a) Create a Controller AccountController.java
/**
 * 
 */
package com.doj.restapi.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.doj.restapi.bean.Account;
import com.doj.restapi.bean.AccountList;
import com.doj.restapi.service.IAccountService;

/**
 * @author Dinesh.Rajput
 *
 */
@RestController
public class AccountController {
 
 @Autowired
 IAccountService accountService;
 
 @GetMapping("/")
 public String home (){
  return "Spring REST Dinesh on Java!!!";
 }
 
 @GetMapping("/accounts")
 public AccountList all (){
  return accountService.list();
 }
 
 @PostMapping("/account")
 public Account create (@RequestBody Account account){
  return accountService.create(account);
 }
 
 @GetMapping("/account/{accountId}")
 public Account get (@PathVariable Long accountId){
  return accountService.get(accountId);
 }
 
 @PutMapping("/account")
 public Account update (@RequestBody Account account){
  return accountService.update(account);
 }
 
 @DeleteMapping("/account/{accountId}")
 public void delete (@PathVariable Long accountId){
  accountService.delete(accountId);
 }
}


In this controller class we have used @RestController annotation. Till Spring 3, we would have been using @Controller annotation and in that case it was important to use @ResponseBody annotation as well as below:

@Controller
public class AccountController {
.....
.....

@RequestMapping("/account/{accountId}")
public  @ResponseBody Account get (@PathVariable Long accountId){
  return accountService.get(accountId);
}
.....
.....
}

As of spring 4.0, we can use @RestController which is combination of @Controller and @ResponseBody. Read my article RestController in Spring Framework 4.0 for more detail.

@RestController = @Controller + @ResponseBody

In this example, we are using @GetMapping, @PostMapping, @PutMapping and @DeleteMapping annotations, these annotations are introduced from Spring 4.3 version in parallel of @RequestMapping with Http Methods annotation as below.

@GetMapping = @RequestMapping + Http GET method
@PostMapping = @RequestMapping + Http POST method
@PutMapping = @RequestMapping + Http PUT method
@DeleteMapping = @RequestMapping + Http DELETE method

Spring provides HttpMessageConverters to convert an object to the xml representation requested by the user. Spring's @ResponseBody annotation is responsible for generating body response by using result of the method to the client. In this example we want XML response so this marshaling is done by the Jaxb2RootElementHttpMessageConverter provided by Spring which is automatically registered in spring context if JAXB libraries are found in classpath. JAXB library is inbuilt in the java from JDK 7.0 here I am using JDK 8 in this application, so there is no need to configure JAXB library into Maven dependency file.

b) JAXB Annotated Model Objects
We need to annotate bean class with @XmlRootElement and @XmlElement to support for xml.

Account.java
/**
 * 
 */
package com.doj.restapi.bean;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author Dinesh.Rajput
 *
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE) 
@Entity
@Table
public class Account implements Serializable{
 
 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 
 @XmlAttribute
 @Id
 @GeneratedValue
 public Long accountId;
 
 @XmlElement
 public String name;
 
 @XmlElement
 public String city;
 
 @XmlElement
 public Double balance;
 
 public Account() {
  super();
 }
 public Account(String name, String city, Double balance) {
  super();
  this.name = name;
  this.city = city;
  this.balance = balance;
 }
 public Long getAccountId() {
  return accountId;
 }
 public void setAccountId(Long accountId) {
  this.accountId = accountId;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public Double getBalance() {
  return balance;
 }
 public void setBalance(Double balance) {
  this.balance = balance;
 }
 @Override
 public String toString() {
  return "Account [accountId=" + accountId + ", name=" + name + ", city=" + city + ", balance=" + balance + "]";
 }
 
}


AccountList.java

/**
 * 
 */
package com.doj.restapi.bean;

import java.io.Serializable;
import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author Dinesh.Rajput
 *
 */
@XmlRootElement (name="accounts")
public class AccountList implements Serializable {

 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 
 private List<Account> listOfAccounts;

 public List<Account> getListOfAccounts() {
  return listOfAccounts;
 }
 @XmlElement(name = "account")
 public void setListOfAccounts(List<Account> listOfAccounts) {
  this.listOfAccounts = listOfAccounts;
 }
 
}


c) Create a Service class AccountService.java
This class has CRUD method service for account resource.

AccountService.java
/**
 * 
 */
package com.doj.restapi.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.doj.restapi.bean.Account;
import com.doj.restapi.bean.AccountList;
import com.doj.restapi.repository.AccountRepository;

/**
 * @author Dinesh.Rajput
 *
 */
@Service
public class AccountService implements IAccountService{
 
 @Autowired
 AccountRepository accountRepository;
 
 @Override
 public Account create(Account account) {
  return accountRepository.save(account);
 }

 @Override
 public Account get(Long accountId) {
  return accountRepository.findOne(accountId);
 }

 @Override
 public Account update(Account account) {
  return accountRepository.save(account);
 }

 @Override
 public void delete(Long accountId) {
  accountRepository.delete(accountId);
 }

 @Override
 public AccountList list() {
  AccountList accountList = new AccountList();
  Iterable<Account> itr = accountRepository.findAll();
  List<Account> accounts = new ArrayList<Account>();
  for(Account account : itr){
   accounts.add(account);
  }
  accountList.setListOfAccounts(accounts);
  return accountList;
 }
}


d) Create a Repository class AccountRepository.java
This is an interface which extends an interface of Spring Data JPA for using CRUD operation over account class.

/**
 * 
 */
package com.doj.restapi.repository;

import org.springframework.data.repository.CrudRepository;

import com.doj.restapi.bean.Account;

/**
 * @author Dinesh.Rajput
 *
 */
public interface AccountRepository extends CrudRepository {

}


Step 6: Deploying this application to tomcat server

Right click on project -> run as -> run on server

After starting of tomcat server, Let's check our application with Rest client Postman, it is UI based client for testing restful web applications, postman is chrome plugin. Launch postman.

a) POST method: CREATE Account Resource using POST http method
Post method is used to create new resource. Here we are adding new Account to the account database, so you can see we have used account XML in post body.

Spring-REST-POST

b) GET method: READ Account Resource using GET http method
Test our get method Spring REST service. You will get following output as below:

Spring-REST-GET

c) PUT method: UPDATE Account Resource using PUT http method
Put method is used to update resource. Here we will update name of account holder of accountId=1 using put method. So we will update account XML in body of request of accountId is 1 as below.

Spring-REST-PUT

d) Read All Account Resources using GET http method

Read ALL

e) DELETE method: DELETE Account Resource using DELETE http method
Delete method is used to delete resource. So here we will pass accountId of account which needs to be deleted as Path Param. We are going delete the account who have accountId=1.

Spring-REST-DELETE

f) Read All Accounts after DELETE Call

Spring-REST-After-delete



Spring REST client – RestTemplate Consume RESTful Web Service Example JSON

In Spring REST client, The RestTemplate is the core class for client-side access to Spring RESTful web services. It communicates HTTP server using RESTful constraints. It is very similar to other template classes in the Spring like JdbcTemplate and HibernateTemplate etc. In Spring, RestTemplate provides higher level implementation of corresponding HTTP methods such as GET, POST, PUT, DELETE, HEAD etc. It provides the methods to communicate by using these HTTP methods with URI template, URI param, request object and response type as arguments.

In this example, we will see how to consume JSON response. In my previous article we have seen Spring RESTful web services crud example. Earlier we have used postman REST UI based client to demonstrate all HTTP methods such as get, post, delete and put. But here we are going to consume Restful web services via RestTemplate of Spring REST client.


RestTemplate Methods
RestTemplate provides higher level methods that correspond to each of the six main HTTP methods that make invoking many RESTful services. In the following list has methods provided by Spring RestTemplate for each http methods.


Method

Spring RestTemplate’s method

Get

 getForObject, getForEntity

Post

postForObject(String url, Object request, Class responseType, String…? uriVariables)

postForLocation(String url, Object request, String…? urlVariables),

Put

put(String url, Object request, String…?urlVariables)

Delete

delete()

Head

headForHeaders(String url, String…? urlVariables)

Options

optionsForAllow(String url, String…? urlVariables)

As per as name of these methods of RestTemplate class indicate which HTTP method they implement internally and second part of the method name indicates what is return by these methods. For example, getForObject() will perform a HTTP GET action on the server, and convert the HTTP response into an object of given type and return it to the client. And other method postForLocation() will do a HTTP POST action on the server, converting the given object into a HTTP request, and returns the response HTTP Location header where the newly created object can be found.

Let's see these RestTemplate's methods with examples.
 Here I am using Spring Restful web services CRUD JSON Example of my previous post.

In this example, we are using @GetMapping, @PostMapping, @PutMapping and @DeleteMapping annotations, these annotations are introduced as of Spring 4.3 version in parallel of @RequestMapping annotation with Http Methods as below.

@GetMapping = @RequestMapping + Http GET method
@PostMapping = @RequestMapping + Http POST method
@PutMapping = @RequestMapping + Http PUT method
@DeleteMapping = @RequestMapping + Http DELETE method

HTTP GET Method Example
For API GET method call we can use either getForObject() or getForEntity() method of RestTemplate.

Spring REST API GET CODE:
@GetMapping("/account/{accountId}")
public Account get (@PathVariable Long accountId){
  return accountService.get(accountId);
}

We could define same above API call as below:
@RequestMapping(method=RequestMethod.GET, value = "/account/{accountId}", produces = MediaType.APPLICATION_JSON_VALUE)
public Account get (@PathVariable Long accountId){
  return accountService.get(accountId);
}

This call binds to convert on JSON media type only with the @RequestMapping annotation. If you want flexible return media type either JSON or XML based on the message converter available on the classpath of the application then it's recommend do not define produces property request mapping annotation.

Spring RestTemplate get Method :

/**
 * 
 */
package com.doj.restclient.account;

import org.springframework.web.client.RestTemplate;

/**
 * @author Dinesh.Rajput
 *
 */
public class SpringRestClient {
 
 private static RestTemplate restTemplate = new RestTemplate();
 private static final String baseURL = "http://localhost:8080/restapi/";

 /**
  * @param args
  */
 public static void main(String[] args) {
  //Read Account details for a given accountId = 1 using GET method of RestTemplate
  Account accountDetail = restTemplate.getForObject(baseURL+"account/1", Account.class);
  System.out.println("Account Detail for given AccountId : " +accountDetail); 
  
 }

}


Output on console:
After running above code, you will get below output:

Account Detail for given AccountId : Account [accountId=1, name=Dinesh Rajput, city=Noida, balance=212.33]

HTTP POST Method Example

For Http POST method calling we can use either postForObject() or postForLocation() method of RestTemplate.

Spring Rest API Code post method:

@PostMapping("/account")
public Account create (@RequestBody Account account){
   return accountService.create(account);
}

Spring RestTemplate post Method call:

/**
 * 
 */
package com.doj.restclient.account;

import org.springframework.web.client.RestTemplate;

/**
 * @author Dinesh.Rajput
 *
 */
public class SpringRestClient {
 
 private static RestTemplate restTemplate = new RestTemplate();
 private static final String baseURL = "http://localhost:8080/restapi/";

 /**
  * @param args
  */
 public static void main(String[] args) {
  //Create Account using POST method of RestTemplate
  Account account = new Account("Arnav Rajput", "Noida", 312.33);
  account = restTemplate.postForObject(baseURL+"account", account, Account.class);
  System.out.println("Added account: " +account);
  
 }

}


Output on console:
After running above code, you will get below output:

Added account: Account [accountId=3, name=Arnav Rajput, city=Noida, balance=312.33]

HTTP PUT Method Example

For Http PUT method calling we can use put() method of RestTemplate.

Spring Rest API Code put method:
@PutMapping("/account")
public Account update (@RequestBody Account account){
  return accountService.update(account);
}

Spring RestTemplate put Method call:
/**
 * 
 */
package com.doj.restclient.account;

import org.springframework.web.client.RestTemplate;

/**
 * @author Dinesh.Rajput
 *
 */
public class SpringRestClient {
 
 private static RestTemplate restTemplate = new RestTemplate();
 private static final String baseURL = "http://localhost:8080/restapi/";

 /**
  * @param args
  */
 public static void main(String[] args) {
  //Create Account using POST method of RestTemplate
  Account account = new Account("Arnav Rajput", "Noida", 312.33);
  account = restTemplate.postForObject(baseURL+"account", account, Account.class);
  System.out.println("Added account: " +account);
  
  //Update Account detail for given accountId = 1 using PUT method of RestTemplate
  Account updateAccount = new Account("Anamika Rajput", "Noida", 123.33);
  updateAccount.setAccountId(1l);
  restTemplate.put(baseURL+"account", updateAccount);
  Account updatedAccount = restTemplate.getForObject(baseURL+"account/1", Account.class);
  System.out.println("Updated Account: " +updatedAccount);
  
 }

}


Output on console:
After running above code, you will get below output:

Added account: Account [accountId=1, name=Arnav Rajput, city=Noida, balance=312.33]
Updated Account: Account [accountId=1, name=Anamika Rajput, city=Noida, balance=123.33]

HTTP DELETE Method Example

For Http DELETE method calling we can use delete() method of RestTemplate.

Spring Rest API Code delete method:
@DeleteMapping("/account/{accountId}")
public void delete (@PathVariable Long accountId){
  accountService.delete(accountId);
}

Spring RestTemplate delete Method call:
/**
 * 
 */
package com.doj.restclient.account;

import java.util.List;

import org.springframework.web.client.RestTemplate;

/**
 * @author Dinesh.Rajput
 *
 */
public class SpringRestClient {
 
 private static RestTemplate restTemplate = new RestTemplate();
 private static final String baseURL = "http://localhost:8080/restapi/";

 /**
  * @param args
  */
 public static void main(String[] args) {
  List<Account> accounts = restTemplate.getForObject(baseURL+"accounts", List.class);
  System.out.println("Total Accounts before DELETE call: ");
  for(Object acct : accounts){
   System.out.println(acct);
  }
  
  //Delete Account for given accountId = 2 using Delete method of RestTemplate
  restTemplate.delete(baseURL+"account/2");
  accounts = restTemplate.getForObject(baseURL+"accounts", List.class);
  System.out.println("Total Accounts after DELETE call: ");
  for(Object acct : accounts){
   System.out.println(acct);
  }
 }

}

Output on console:
After running above code, you will get below output:

Total Accounts before DELETE call:
{accountId=1, name=Anamika Rajput, city=Noida, balance=123.33}
{accountId=2, name=Anamika Rajput, city=Noida, balance=222.33}
{accountId=3, name=Arnav Rajput, city=Noida, balance=522.33}
Total Accounts after DELETE call:
{accountId=1, name=Anamika Rajput, city=Noida, balance=123.33}
{accountId=3, name=Arnav Rajput, city=Noida, balance=522.33}

Download Source Code from GitHub.

  1. Spring RESTful web service CRUD Example
  2. Spring REST Client using RestTemplate Example


Spring REST client – RestTemplate Consume RESTful Web Service Example JSON


Spring Restful Web Services JSON CRUD Example

In this spring rest tutorial, we will create restful web services Crud APIs by using HTTP verbs GET, POST, PUT and Delete and returning JSON representations of resources. In my previous post, we have created a very simple JAX-RS Restful web services but in this post we are using Spring REST, it will return response as json in this example. If you want to learn more about REST you could read my previous article What is REST? Architecture and it's Constraints.

Here we are using Spring 4.3.5 webmvc, Spring REST, Spring Data JPA and jackson libraries for this example. For back-end we are using H2 in-memory database for saving the data and also using Spring Data JPA over the Hibernate JPA as ORM. Let's see steps to create a simple Spring Restful web services crud example which will return json.

Step 1: Create a Dynamic web project using maven.

Project Structure
Spring Restful Web Services JSON CRUD Example

Download Source Code from GitHub
Spring Restful Web Services JSON CRUD Example


Step 2: Maven dependency for this application.
In pom.xml, there are following dependency required for this application.

<properties>
   <spring.version>4.3.5.RELEASE</spring.version>
   <spring.data.version>1.11.1.RELEASE</spring.data.version>
   <h2.version>1.4.193</h2.version>
  </properties>
  
  <dependencies>
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-webmvc</artifactId>
     <version>${spring.version}</version>
 </dependency>
 
 <dependency>
     <groupId>org.springframework.data</groupId>
     <artifactId>spring-data-jpa</artifactId>
     <version>${spring.data.version}</version>
 </dependency>
 
 <dependency>
     <groupId>com.h2database</groupId>
     <artifactId>h2</artifactId>
     <version>${h2.version}</version>
 </dependency>
 
 <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>5.1.0.Final</version>
 </dependency>
 
 <!-- Jackson JSON Mapper -->
       <dependency>
           <groupId>org.codehaus.jackson</groupId>
           <artifactId>jackson-mapper-asl</artifactId>
           <version>1.7.1</version>
       </dependency>
       <dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-databind</artifactId>
     <version>2.5.0</version>
 </dependency>
  </dependencies>

In the maven file we have dependencies of spring webmvc, spring data jpa, h2 database and hibernate entity manager for jpa transaction. Also we have to include jackson maven dependencies into classpath of your application because spring will register Jackson2JsonMessageConverter class automatically into context. Whenever we request resource as json with accept headers="Accept=application/json", then Jackson2JsonMessageConverter comes into picture and convert resource to json format.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.0</version>
</dependency>

Step 3: Creating Spring Configuration files for this application
In this spring restful web service application, we are using Java based configuration. So let's see following configuration java classes for this example.

a) Spring Configuration class for Spring MVC
The following file is required for configuring spring mvc to the application and enabling required bean post processors for message converter.

RestApplicationConfig.java
/**
 * 
 */
package com.doj.restapi.web.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

/**
 * @author Dinesh.Rajput
 *
 */
@Configuration
@EnableWebMvc
@ComponentScan("com.doj.restapi.web.controller")
public class RestApplicationConfig{
 
}
@EnableWebMvc- It used for enabling spring mvc behavior i.e. it is responsible for registering Spring MVC required Bean Post Processors in the application as like Jackson2JsonMessageConverter etc.
@ComponentScan- It scans the package com.doj.restapi.web.controller. This package has Rest Controllers for this application.

b) Spring Configuration for application Infrastructure
This file has configuration about application core services like DB connection, DataSource and also scan the packages for service classes and repositories i.e. Non web components.

InfrastructureConfig.java
/**
 * 
 */
package com.doj.restapi.config;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

/**
 * @author Dinesh.Rajput
 *
 */
@Configuration
@ComponentScan("com.doj.restapi.service")
@EnableJpaRepositories("com.doj.restapi.repository")
public class InfrastructureConfig {
 
 @Bean
 public DataSource dataSource() {
  return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
 }

 @Bean
 public JpaVendorAdapter jpaVendorAdapter() {
  HibernateJpaVendorAdapter bean = new HibernateJpaVendorAdapter();
  bean.setDatabase(Database.H2);
  bean.setGenerateDdl(true);
  return bean;
 }

 @Bean
 public LocalContainerEntityManagerFactoryBean entityManagerFactory(
   DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
  LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
  bean.setDataSource(dataSource);
  bean.setJpaVendorAdapter(jpaVendorAdapter);
  bean.setPackagesToScan("com.doj.restapi.bean");
  return bean;
 }

 @Bean
 public JpaTransactionManager transactionManager(EntityManagerFactory emf) {
  return new JpaTransactionManager(emf);
 }
}
@EnableJpaRepositories-It used to create the spring bean related to spring data jpa in the application i.e. those classes which implement spring data repository interfaces.

Step 4: Creating Web Application Initializer file for this application
Here we are using Java based configuration for web application i.e. here we do not have web.xml file in the application. For java based web configuration, we have to required at least tomcat 7 and servlet 3.0 or above.

RestApplicationInitializer.java
/**
 * 
 */
package com.doj.restapi.web;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import com.doj.restapi.config.InfrastructureConfig;
import com.doj.restapi.web.config.RestApplicationConfig;

/**
 * @author Dinesh.Rajput
 *
 */
public class RestApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

 @Override
 protected Class<?>[] getRootConfigClasses() {
  return new Class[] { InfrastructureConfig.class };
 }

 @Override
 protected Class<?>[] getServletConfigClasses() {
  return new Class[] { RestApplicationConfig.class };
 }

 @Override
 protected String[] getServletMappings() {
  return new String[] { "/" };
 }
}


Step 5: Creating Application classes
In this application, we will create and read account resource from account repository.
a) Create a Controller AccountController.java

/**
 * 
 */
package com.doj.restapi.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.doj.restapi.bean.Account;
import com.doj.restapi.service.IAccountService;

/**
 * @author Dinesh.Rajput
 *
 */
@RestController
public class AccountController {
 
 @Autowired
 IAccountService accountService;
 
 @GetMapping("/")
 public String home (){
  return "Spring REST Dinesh on Java!!!";
 }
 
 @GetMapping("/accounts")
 public List<Account> all (){
  return accountService.list();
 }
 
 @PostMapping("/account")
 public Account create (@RequestBody Account account){
  return accountService.create(account);
 }
 
 @GetMapping("/account/{accountId}")
 public Account get (@PathVariable Long accountId){
  return accountService.get(accountId);
 }
 
 @PutMapping("/account/{accountId}")
 public Account update (@RequestBody Account account, @PathVariable Long accountId){
  return accountService.update(account, accountId);
 }
 
 @DeleteMapping("/account/{accountId}")
 public void delete (@PathVariable Long accountId){
  accountService.delete(accountId);
 }
}


This controller class is annotated with @RestController annotation instead of @Controller annotation. As of spring 4.0, we can use @RestController which is combination of @Controller and @ResponseBody. Read my article RestController in Spring Framework 4.0 for more detail.

@RestController = @Controller + @ResponseBody

Before Spring 4.0, we have to use @Controller at the class level with @ResponseBody before the handler method as below:

@Controller
public class AccountController {
.....
.....

@RequestMapping("/account/{accountId}")
public  @ResponseBody Account get (@PathVariable Long accountId){
  return accountService.get(accountId);
}
.....
.....
}

In this example, we are using @GetMapping, @PostMapping, @PutMapping and @DeleteMapping annotations, these annotations are introduced from Spring 4.3 version in parallel of @RequestMapping with Http Methods annotation as below.

@GetMapping = @RequestMapping + Http GET method

b) Create a Bean class Account.java

/**
 * 
 */
package com.doj.restapi.bean;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author Dinesh.Rajput
 *
 */
@Entity
@Table
public class Account implements Serializable{
 
 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 @Id
 @GeneratedValue
 public Long accountId;
 public String name;
 public String city;
 public Double balance;
 
 public Account() {
  super();
 }
 public Account(String name, String city, Double balance) {
  super();
  this.name = name;
  this.city = city;
  this.balance = balance;
 }
 public Long getAccountId() {
  return accountId;
 }
 public void setAccountId(Long accountId) {
  this.accountId = accountId;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public Double getBalance() {
  return balance;
 }
 public void setBalance(Double balance) {
  this.balance = balance;
 }
 @Override
 public String toString() {
  return "Account [accountId=" + accountId + ", name=" + name + ", city=" + city + ", balance=" + balance + "]";
 }
 
}


c) Create a Service class AccountService.java
This class has CRUD method service for account resource.

/**
 * 
 */
package com.doj.restapi.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.doj.restapi.bean.Account;
import com.doj.restapi.repository.AccountRepository;

/**
 * @author Dinesh.Rajput
 *
 */
@Service
public class AccountService implements IAccountService{
 
 @Autowired
 AccountRepository accountRepository;
 
 @Override
 public Account create(Account account) {
  return accountRepository.save(account);
 }

 @Override
 public Account get(Long accountId) {
  return accountRepository.findOne(accountId);
 }

 @Override
 public Account update(Account account, Long accountId) {
  return accountRepository.save(account);
 }

 @Override
 public void delete(Long accountId) {
  accountRepository.delete(accountId);
 }

 @Override
 public List<Account> list() {
  return (List<Account>) accountRepository.findAll();
 }
}



d) Create a Repository class AccountRepository.java
This is an interface which extends an interface of Spring Data JPA for using CRUD operation over account class.

/**
 * 
 */
package com.doj.restapi.repository;

import org.springframework.data.repository.CrudRepository;

import com.doj.restapi.bean.Account;

/**
 * @author Dinesh.Rajput
 *
 */
public interface AccountRepository extends CrudRepository<Account, Long> {

}


This interface is extending an interface CrudRepository of Spring Data JPA library. As you seen, there is no method in the interface, so we are using default CRUD operation methods of CrudRepository interface.

Step 6: Deploying this application to tomcat server

Right click on project -> run as -> run on server

After starting of tomcat server, Let's check our application with Rest client Postman, it is UI based client for testing restful web applications, we have below URL of our application to provide start page:

a) Home Page
http://localhost:8080/restapi/

rest-home-page

Postman is chrome plugin. Launch postman.
b) POST method: CREATE Account Resource using POST http method
Post method is used to create new resource. Here we are adding new Account to the account database, so you can see we have used account json in post body.

Create-resource-POST-method

c) GET method: READ Account Resource using GET http method
Test our get method Spring REST service. You will get following output as below:

Read-Resource-Http-GET

d) PUT method: UPDATE Account Resource using PUT http method
Put method is used to update resource. Here we will update name of account holder of accountId=1 using put method. So we will update account json in body of request of accountId is 1 as below.

Spring Restful webservice Http PUT method

e) DELETE method: DELETE Account Resource using DELETE http method
Delete method is used to delete resource. So here we will pass accountId of account which needs to be deleted as Path Param. We are going delete the account who have accountId=3.

Spring Restful webservice Http DELETE method

f) Read All Account Resources using GET http method

All accounts