Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Spring RESTFul Web Services Example using RestTemplate

REST stands for Representational State Transfer.It is REST Architecture based Web Services which is used to create APIs for web-based applications, that can be consumed from a variety of clients. like java, .net, php etc. The core idea is that, In Restfull web service simple Http is used to make calls between machine.
RESTful web services are light weight, highly scalable and maintainable.


In RESTful basically keep focus on Resource. Here resources are being manipulated using a common set of methods POST, GET, PUT, DELETE operations which are similar to Create, Read, update and Delete(CRUD) operations.


To Create a resource : HTTP POST should be used
To Retrieve a resource : HTTP GET should be used
To Update a resource : HTTP PUT should be used
To Delete a resource : HTTP DELETE should be used


Mostly we used JSON or XML as return type in response in Rest based Web services, although it is not limited to these types only. Clients can specify other type of resource as well (using HTTP Accept header) if they are interested, and server may return the resource , specifying Content-Type of the resource it is serving.



Below Technologies is used in our example:

Spring 4.2.0.RELEASE
Maven 3
JDK 1.8
Tomcat 8.0.38
Eclipse Oxygen


In our example we have create Rest based controller, 

We have created below 6 API to manipulate resource:

GET Request to /api/emp/ returns a list of emps
GET request to /api/emp/1 returns the emp with ID 1
POST request to /api/emp/ with a emp object as JSON creates a new emp
PUT request to /api/emp/3 with a emp object as JSON updates the emp with ID 3
DELETE request to /api/emp/4 deletes the emp with ID 4
DELETE request to /api/emp/ deletes all the emps
===================================================

package com.javacoderhint.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
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.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import com.javacoderhint.model.Emp;
import com.javacoderhint.service.EmpService;

@RestController
public class EmpRestController{

    @Autowired
    EmpService empService;  //Service which will do all data retrieval/manipulation work

     
    //-------------------Retrieve All Emps--------------------------------------------------------
     
    @RequestMapping(value = "/emp/", method = RequestMethod.GET)
    public ResponseEntity> listAllEmps() {
        List emps = empService.findAllEmps();
        if(emps.isEmpty()){
            return new ResponseEntity>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
        }
        return new ResponseEntity>(emps, HttpStatus.OK);
    }


    //-------------------Retrieve Single Emp--------------------------------------------------------
     
    @RequestMapping(value = "/emp/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity getEmp(@PathVariable("id") long id) {
        System.out.println("Fetching Emp with id " + id);
        Emp emp = empService.findById(id);
        if (emp == null) {
            System.out.println("Emp with id " + id + " not found");
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity(emp, HttpStatus.OK);
    }

     
     
    //-------------------Create a Emp--------------------------------------------------------
     
    @RequestMapping(value = "/emp/", method = RequestMethod.POST)
    public ResponseEntity createEmp(@RequestBody Emp emp,    UriComponentsBuilder ucBuilder) {
        System.out.println("Creating Emp " + emp.getName());

        if (empService.isEmpExist(emp)) {
            System.out.println("A Emp with name " + emp.getName() + " already exist");
            return new ResponseEntity(HttpStatus.CONFLICT);
        }

        empService.saveEmp(emp);

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/emp/{id}").buildAndExpand(emp.getId()).toUri());
        return new ResponseEntity(headers, HttpStatus.CREATED);
    }

     
    //------------------- Update a Emp --------------------------------------------------------
     
    @RequestMapping(value = "/emp/{id}", method = RequestMethod.PUT)
    public ResponseEntity updateEmp(@PathVariable("id") long id, @RequestBody Emp emp) {
        System.out.println("Updating Emp " + id);
         
        Emp currentEmp = empService.findById(id);
         
        if (currentEmp==null) {
            System.out.println("Emp with id " + id + " not found");
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }

        currentEmp.setName(emp.getName());
        currentEmp.setAge(emp.getAge());
        currentEmp.setSalary(emp.getSalary());
         
        empService.updateEmp(currentEmp);
        return new ResponseEntity(currentEmp, HttpStatus.OK);
    }

    //------------------- Delete a Emp --------------------------------------------------------
     
    @RequestMapping(value = "/emp/{id}", method = RequestMethod.DELETE)
    public ResponseEntity deleteEmp(@PathVariable("id") long id) {
        System.out.println("Fetching & Deleting Emp with id " + id);

        Emp emp = empService.findById(id);
        if (emp == null) {
            System.out.println("Unable to delete. Emp with id " + id + " not found");
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }

        empService.deleteEmpById(id);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

     
    //------------------- Delete All Emps --------------------------------------------------------
     
    @RequestMapping(value = "/emp/", method = RequestMethod.DELETE)
    public ResponseEntity deleteAllEmps() {
        System.out.println("Deleting All Emps");

        empService.deleteAllEmps();
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

}

Detailed Explanation :

Basically you need to know  @RestController , @RequestBody, ResponseEntity & @PathVariable anotation to implement a REST API in Spring 4

@RestController : @RestController annotation is itself annotated with @Controller and @ResponseBody, it means you no longer need to add @ResponseBody to all the request mapping methods. The @ResponseBody annotation is active by default with @RestController

Spring3.0 - @Controller + @ResponseBody



@RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody Employee getEmployeeInJSON(@PathVariable String name) {

    employee.setName(name);
    employee.setEmail("[email protected]");

    return employee;

    }

Spring4.0 - @Restcontroller


@RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "application/json")
    public Employee getEmployeeInJSON(@PathVariable String name) {

    employee.setName(name);
    employee.setEmail("[email protected]");

    return employee;

    }


Note that we no longer need to add the @ResponseBody to the request mapping methods. In both case you will get same output.



@RequestBody : If a method parameter is annotated with @RequestBody, Spring will bind the incoming HTTP request body(for the URL mentioned in @RequestMapping for that method) to the method parameter. While doing that, Internally Spring use HTTP Message converters to convert the body of HTTP request into domain object [deserialize request body to domain object], depend on Content-Type present in request header.



ResponseEntity is a real deal. It represents the entire HTTP response. here you can control anything that goes into it. You can specify status code, headers, and body. It comes with several constructors to carry the information you want to sent in HTTP Response.



@PathVariable This annotation indicates that a method parameter should be bound to a URI template variable [the one in '{}'].

download complete example of Spring Restful Web Service form out git hub repository:




This post first appeared on Java Programming Tutorials Online For Java Coder, please read the originial post: here

Share the post

Spring RESTFul Web Services Example using RestTemplate

×

Subscribe to Java Programming Tutorials Online For Java Coder

Get updates delivered right to your inbox!

Thank you for your subscription

×