Spring REST Introduction

Spring REST Introduction | We will discuss Spring REST, HttpStatus, ResponseEntity, Request Method, and e.t.c.

Webservices (ReST)

Web services represent the integration of Applications. Linking two or more applications that are running on the same/different servers.

2 different web services can be in different technologies/languages. For example, one web service uses Java and another one uses .net. Therefore they have to work with global format (XML/JSON).

Web services are implemented using HTTP Protocol and data in Global Format(XML/JSON).
Web services are not for UI design, they are used for integration. For UI use: ReactJS, JSF, Thymeleaf, etc.

Webservices are two types:-

  • SOAP web services (XML Concept – Simple Object Access Protocol)
  • ReST web services (Representation State Transfer)

In ReST (Representation State Transfer):-

  • State = Data
  • Transfer = Send/Receive
  • Representation = With Protocol(HTTP) + Global Format(XML/JSON)

ReST means the exchange of data between applications using HTTP protocol and data in Global Format.

To develop web(any)application we use 3 layers:-

  1. PL (Presentation Layer)
  2. SL (Service Layer)
  3. DAL (Data Access Layer)

To create link(communication) we use 4th layer:-

  1. IL (Integration Layer)

This layer (Integration Layer) must present in two applications:-

  • One application behaves like the Service Provider
  • And another one Service Consumer.

Ex: Shopify is using the service of Stripe. Shopify is a consumer and Stripe is a provider.

One Application can behaves like consumer for one integration and for another it might be producer even.

Spring ReST

To implement ReST Webservices, Spring F/w has provided one Web API ie called as Spring ReST (ReST API).

Sun has provided an API called JAX-RS (rules and guidelines). Implementation with new Annotations API is given by Spring ReST.

By using Spring ReST we can implement Provider and Consumer Applications

  • Provider using: RestController
  • Consumer using: RestTemplate

We can use Spring ReST in 3 ways:-

Case#1 Both different applications (Boot Applications only) are integrated using Spring Boot ReST.
Provider:- RestController
Consumer:- RestTemplate

Case#2 One application but designed as Frontend and backend.
Provider:- RestController
Consumer:- Angular/ React/ Andriod

Case#3 Both are two different applications(java and non-java) and integrated using Spring Boot REST.

Provider:- RestController
Consumer:- .net Client, PHP client

Or
Provider:- .net/PHP/Python
Consumer:- RestTemplate

Provider workflow Design:-

  • Client makes a request to Provider, taken by FC(DispatcherServlet).
  • With the help of HandlerMapping, FC gets RestController details and executes code.
  • RestController gives output in String/Object/Collection Format i.e. called as Entity(Final Output) and placed in Response object along with HTTP Status (1xx-information, 2xx-success, 3xx-redirect, 4xx-client side error, 5xx-server side error).
  • ResponseEntity is given back to FC, same is sent to the client.
  • If Entity is non-String (object or Collection) ex: List, Student, Product[] ..etc then data is converted into XML or JSON.
  • The string is sent as text format text/plain as Response Body.

HTTP Protocol has Request Method (9) and Response Status.

Request Method

  • GET: Fetch Resources (Data) From the Provider App. ex: getEmployees(), getEmployeeById().
  • POST: Create new Resource(Data) From Provider App. ex: saveEmployee(), createProduct()
  • PUT: Modify existing (HighLevel/Full Data) Resources (Data) From Provider App. ex: updateEmployee(), modifyEmpData().
  • DELETE: Remove existed Resource(Data) From Provider App. ex: deleteEmployeeByid()
  • PATCH: Modify Existing (LowLevel/Partial Data) Resource(Data) From Provider App. Example updateEmployeMailById().
  • HEAD
  • TRACE
  • OPTIONS
  • CONNECT

All the above methods are recommended standards given to all developers in the world. They are not MUST methods. They are good named methods. Even we can create resources using GET, delete using POST, partial updates using PUT, etc. But they are not the correct usage of code. For example in a house Bedroom, the Kitchen is there and you can cook in the bedroom, and sleep in the kitchen but that won’t be the correct usage of those rooms.

This is a contract between two developers, so naming standards are recommended to follow. If we use these guidelines in the wrong way and get output It doesn’t mean the Method Type is wrong.

Response Status

It represents what happened at the last.

CodeMessage
1xxInformation
2xxSuccess
3xxRedirect
4xxClient Side Error
5xxServer Side Error

To define our RestController code (class#method) must have the:-

  • One unique path
  • One Http Method
  • Must return Data In Global Format(JSON/XML)
  • HTTP Status

ResponseEntity<T>

Entity(Final Output) Placed inside Response. This is used as Controller#Method ReturnType. Here T = Type can be String/Class/Collection.

  • If the return type is String, then the HTTP Response is ‘Text Format’ (Content-Type: text/plain).
  • If the return type is non-String, then the HTTP Response is ‘JSON’ (Content-Type: application/json).

Since Spring Boot version 2.x, it supports only JSON Format. XML Supports default is not present, but we can add additional dependency to enable this.

Which is preferred for Object Format in Webservices JSON or XML? JSON because of the following reasons:-

  • Representation is easy { key:val }
  • Need less memory (compared to XML)
  • Execution/transfer is very fast.
  • XML is more complex in design if data gets increased.

XML:

<employee>
  <eid>10</eid>
  <ename>A</ename>
</employee>

JSON:

{
  eid: 10,
  ename: "A"
}

Media Type Annotations

ReST has provided two media type annotations:-

  • @RequestBody (Input MediaType)
  • @ResponseBody (Output MediaType)

@RequestBody: It reads the HTTP request first. Checks Header Param ‘Content-Type’. If Type is non-string(not text/plain, ex: application/json, application/xml) then data/content is converted into Object Format, given to Controller#method Param.

Spring MVC @ModelAttribute (FORM DATA) is the same as Spring ReST @RequestBody

@ResponseBody: It will take Controller#method return type first. If the type is non-String Ex: Employee, List then data is converted into JSON/XML (based on request type)
and give it to the HTTP Response Body Section and update the Content-Type Header Param even.

Spring MVC Model is the same as Spring ReST @ResponseBody

@ResponseBody Annotation is optional to apply over method. Because internally @RestController is applying @ResponseBody Annotation. It works only for non-String.

Adding XML Support in Spring REST

The default output type is JSON .ie @ResponseBody converts ReturnType as JSON Data only. XML support is not given by default.

To get XML output in place of JSON,

Step#1 add dependecy in pom.xml

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

Step#2 Provide Header param ‘Accept=__‘ in request

What is the Accept Header Param? It is added in the request, but it says what is expected response type. In simple words, the request is asking please accept my output type expected.

What is the diff b/w Content-Type and Accept? Content-Type (Request/Response) indicates what data exists in the Body(either Request or response). Accept (Request) says what is expected response Content-Type.

If the application does not support XML then still we are requesting using Accept: application/xml then FrontController returns Http Status – 406 Not Acceptable.

What is the meaning of the below Request header?
Accept = application/xml, */*
It is requsting for XML with 1st priority. if ‘Not Accepted’ then any data is fine. The client is ready to take any data.

Accept = application/xml, application/json
It is requesting XML output as 1st priority, if not supported then JSON output as 2nd priority, if not supported then 406 – Not Acceptable.

Q#1) Request Header Param?
Accept = application/xml

Case#1 XML Not Supported
Output: 406 Not Acceptable

Case#2 XML Supported
Output: XML Output (200-OK)

Q#2) Request Header Param?
Accept = application/xml, application/json

Case#1 XML Not Supported
Output: JSON (200-OK)

Case#2 XML, JSON Both not supported
Output: 406 Not Acceptable

Q#3) Request Header Param?
Accept = application/xml, /

Case#1 XML, JSON Not supported
Output: Any Format supported by the Provider.
Ex: HTML, TEXT, IMAGE…etc (200-OK)

Case#2 JSON only Supported
Output: JSON (200-OK)

Note: if the Accept Header Param contains / then the client never gets 406 from the Provider, it will get any one type of response.

Application Example

Dependencies: Spring web, lombok, devtools

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
   private Integer eid;
   private String ename;
   private Double esal;
}
public class EmployeeRestController {
    @GetMapping("/obj")
    public ResponseEntity<Employee> showDataB() {
        Employee body = new Employee(106, "SYED", 600.0);
        return new ResponseEntity<Employee>(body, HttpStatus.OK);
    }

    @GetMapping("/list")
    public ResponseEntity<List<Employee>> showDataD() {
        List<Employee> body = Arrays.asList(
            new Employee(101, "A", 30.0),
            new Employee(102, "B", 31.0),
            new Employee(103, "C", 32.0),
            new Employee(104, "D", 33.0)
        );
        return new ResponseEntity<List<Employee>>(body, HttpStatus.OK);
    }

    @GetMapping("/listb")
    public ResponseEntity<List<String>> showDataE() {
        List<String> body = Arrays.asList("ONE","TWO","ABC");
        return new ResponseEntity<List<String>>(body, HttpStatus.OK);
    }
}

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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