ReSTful Web-Services
ReSTful Web-Services
Web-Application:
- Any Application which is installed on a server and we can access that
Application on a Browser or Client App using the internet.
Client:
- Who made the request or who accessing the service from service provider
or server is called as client.
Ex: Web Browser act as a client.
Server:
- Server is a Software Which is going to run our applications.
Example:
Tomcat
Jboss
Web logic
Glassfish
WebSphere
=====================================================================================
HTTP Protocol:
=====================================================================================
- HTTP Stand for Hypertext Transfer Protocol.
- It is a protocol for transmitting hypermedia documents, such as html. It was
designed for communication between client (web browser) and server
(Web server).
- HTTP is stateless protocol, meaning that the server does not keep any data
between two requests.
- HTTP provide rules.
- HTTP messages are how data is exchanged between a server and a client.
There are two types of messages
Request: sent by the client to trigger an action on the server.
Response: Responses the answer from the server.
Spring Boot Webservices and Microservices
HTTP Requests:
- HTTP requests are messages sent by the client to initiate an action on the
server.
- HTTP Request sent information in bellow format
Request Line
Request Header
Request Body
Example:
GET Indicate a resource should be fetched or POST indicate a resource
should be created or pushed to the server.
HTTP Response:
1. Start line called as status line contain HTTP version, HTTP Status code and
HTTP Status text.
**NOTE:
- Not all requests have body like GET, HEAD, DELETE or OPTION.
HTTP Methods:
1. GET - Fetch/retrieve Resource from Server
2. POST – Create/insert a New Resource at Server
3. PUT – Modify existing resource at server.
4. DELETE - Remove existed Resource at Server.
5. PATCH - Partially Update existed Resource at Server
Others: TRACE, CONNECT, OPTIONS, HEAD
Resources: (File/Image/Doc/DB Data)
=========================== HTTP FQA ============================
Q) Can we use POST Method to Get Data from Server?
ANSWER: Yes, actually it supports getting data, but it is not a Http Standard.
Put is used to send data using its request body (Data is hidden here), that
modifies existed resource at server.
Spring Boot Webservices and Microservices
=====================================================================================
Web-Services:
=====================================================================================
- If we want to create communication link between two applications which
are running in different servers or same server using HTTP protocol and
Data as global format such type of process is called web-services.
OR
If two
applications use different technologies like one application use java and another is
.net. So, if we want to send java object to .net or .net object to java they can’t
understand.
So how to send java object to .net or .net object to java?
- By using interoperable format (XML, JSON, TEXT, CSV) to transfer the data
between applications.
- Interoperable format means any programming languages can read this type
of data format.
And how they will interact/communicate each other?
- By using HTTP protocol.
As part of REST API development, we need to convert Java Object data to JSON
format and JSON data to Java Object.
JAVA <---------------------------------------------------> JSON
In Java we don't have direct support to convert java to Json and vice versa.
These are below opensource 3rd party APIs which are used to convert
Java <<================>> Json
1. Jackson API
2. Gson API
=============
JSCKSON API
=============
- ObjectMapper class provided methods to convert java to Json and vice
versa.
Java Object To JSON:
- Java object into JSON using the writeValue() method of the ObjectMapper
class.
Spring Boot Webservices and Microservices
//Json to Java)
1. package org.nadim.converter;
2. import java.io.File;
3. import org.nadim.entity.Student;
4. import com.fasterxml.jackson.databind.ObjectMapper;
5.
6. public class JsonToJava {
7. public static void main(String [] args) throws Exception {
8. File f = new File("student.json");
9. ObjectMapper om = new ObjectMapper();
10. Student std = om.readValue(f, Student.class);
11. System.out.println(std);
12. }
13. }
==========
GSON API
==========
- GSON API Provided by Google.
- Gson class Provided methods to convert java to Json and vice versa.
==================
XML <----> Java
==================
- XML stands for Extensible Markup Language. XML is interoperable.
- XML will represent data in element format. Every element is combination of start
tag and end tag.
1. <Employee>
2. <empId>101</empId>
3. <empName>Nadim Mostafa</empName>
4. <empSalary>40500.00</empSalary>
5.
6. <Address>
7. <houseNo>#123,Chapainawabgonj</houseNo>
8. <location>Ramchadrapur,Chapainawabgonj</location>
9. </Address>
10. </Employee>
Simple Elements:
- Elements which contain data directly are called as Simple Elements.
- Example:
1. <empId>101</empId>
2. <empName>Nadim Mostafa</empName>
3. <empSalary>40500.00</empSalary>
Compound Elements:
Spring Boot Webservices and Microservices
- Elements which contain child elements are called as compound elements
Example: class name
<Employee> </Employee>
<Address> </Address>
Below opensource 3rd party APIs which are used to convert
Java <<====================>> XML
JAX-B API
===========
JAX-B API
===========
- JAX-B Stands for Java Architecture for XML Binding. Using JAX-B API we can
convert xml data to java object and vice versa.
Note: up to JDK 1.8v, JAX-B is part of JDK itself. But from Java 1.9 version it is not part of
JDK. If we want to work with JAX-B API from java 1.9v then we have to add dependency
in pom.xml file.
1. <dependency>
2. <groupId>javax.xml.bind</groupId>
3. <artifactId>jaxb-api</artifactId>
4. <version>2.3.1</version>
5. </dependency>
1. <dependency>
2. <groupId>com.sun.xml.bind</groupId>
3. <artifactId>jaxb-impl</artifactId>
4. <version>2.3.1</version>
5. </dependency>
1. <dependency>
2. <groupId>org.javassist</groupId>
3. <artifactId>javassist</artifactId>
4. <version>3.25.0-GA</version>
5. </dependency>
4. Create binding class (represent xml structure) and add one @XmlRootElement
annotation over the class.
1. @Data
2. @XmlRootElement
3. public class Customer {
4. private Integer id;
5. private String name;
6. private String gender;
7. private Long Phn;
8. }
===============+===============+====================+==================+=============
1. public class Employee {
2. private Integer empId;
3. private String empName;
4. private Double empSalary;
7. }
Rules:
- If any field/variable is missing data from JSON, then it holds default value based on
datatype (ex: null for String).
- Sending additional keys in JSON (Request) which are not present in Entity, then those are
ignored.
Example
{
"empId": 10,
"empName": "A",
"empSal": 300.0,
"empDept" : "DEV"
}
Here empDept is ignored , it is not exist in Employee.
- JSON Keys can be sent/receive in any order.
===========================================
ReSTful Producer/Provider Application:
============================================
- The app which is providing services to other apps is called as Provider.
- Provider application is also called ReST API.
- Producer should contain -- Service Provider code / Skelton / API
============
Annotations:
============
1. @RestController
Introduced spring 4.0v in order to simplify the creation of RESTful web
services.
It used to create ReSful application.
Return response body/ no view/no UI available
Data is exchanged using JSON or XML format.
It is combination of @Controller and @ResponseBody annotation.
Note: Before introduced @RestController, for create Restful API we used @Controller
and @ResponseBody annotation over the controller class.
@Controller @RestController
1. Used for WEB MVC Apps Used for Rest API Based Apps
2. It returns View (UI/Java based- JSP/ In @RestController, we cannot return view
Thymeleaf)
3. Data is Exchanged using Objects between UI Data is Exchanged using XML/JSON with
and Controller (Model/ModelAttribute..etc) Consumer Apps.
2. @RequestMapping
Used at class level to avoid URL ambiguity and also used at method level to
map URL with http methods.
Example:
3. @ResponseBody
It will write Http Response Body Section, If return type is non-String
type(ClassType, CollectionType) then object convert into JSON/XML format
-> given to Response Body.
Used for GET, HEAD, DELETE
When we add @RestController by default it internally adds
@ResponseBody
In @Controller class, If we add explicit @ResponseBody over the method
then DispatcherServlet(FC) think that, this method not returning any view.
It is returning the direct response.
4. @RequestBody
It will read Http Request Body Section, checks Content-type -> read data
from Body -> Convert JSON/XML to Java Object -> Give it input as method
param.
Request – consumer application make request to the producer app.
Body – tell that read data from body.
Used for creating new Records (POST, PUT..) and @RequestBody must be
used inside Method Parameter
We cannot use in GET, HEAD, DELETE http methods because they do not
have request body.
Spring Boot Webservices and Microservices
Note: @RequestBody, method param can’t a string type. Parameter must be class type
like Employee, Product. If we give parameter as String then, the String type data cannot
convert.
Example:
1. // create employee
2. // JSON to Java Object conversation
3. @PostMapping("/create")
4. public ResponseEntity<String> createEmp(@RequestBody Employee employee){
5. String emp = employee.toString();
6. ResponseEntity<String> response = new ResponseEntity<>(emp,HttpStatus.CREATED);
7. return response;
8. }
Query Parameter:
- Query parameters are parameters added to the end of a URL to provide extra
information to a web server when making requests.
5. @RequestParam
It is capturing the query parameter value from the URL.
Syntax:
@RequestParam("key") DataType variableName
(or)
@RequestParam DataType key
PathVariable:
6. @PathVariable
Sending data along with URL as Path.
Syntax: -
@PathVariable("key") datatype variableName,
Note:
I. Path Creation
@GetMapping("/employee/find/{id}/{name}")
Here, /employee/find is called as static path and /{id}/{name}
dynamic path (Data comes at runtime)
Spring Boot Webservices and Microservices
II. Data Reading
@PathVariable("id") Integer id,
@PathVariable("name") String empName,
III. Request URL
http://localhost:9090/employee/find/101/nadim
7. @RequestHeader
These are instructions/Additional Data (Security, Token data, Certificates,
Date and Time, Cookies etc.) exchanged by both Browser and Server.
It is a Key-value pair. Data is sent in String format.
There are pre-defined headers like Authorization, Accept, Content-Type
etc.
We can even pass our own key-val as header params.
Data Reading
@RequestHeader("Content-Type") String type
==============================
RestController Method Return Type
==============================
We can provide below types of return type
1. Standard Return type is ResponseEntity<T>
2. Class Type, Collection type, String type
ResponseEntity<T>
- The Standard return type is ResponseEntity<T>.
- If we return response with response Body + status code + header params our own
combination then we use ResponseEntity<T> as return type. (or) Return Our
customize response.
- Status is mandatory in case of ResponseEntity object. It can never be null/empty.
But Body or custom headers can be null / empty
1. @GetMapping("/data")
2. public ResponseEntity<T> showData() {
3. // Case-01 String msg="Welcome";
4. // Case-02 User user = new User(101,"Nadim","Admin")
5. ResponseEntity response = new ResponseEntity<>(T(Response body), HeaderParams,StatusCode);
6. return response
7. }
========================================
? (wild card char) if type T is decided at runtime
========================================
- I want to find a book based on bookId. If book is present then return
responseBody as book object with HttpStatus code 200 and Header= found: yes
- If book not found return responseBody as String with HttpStatus code 400 and
Header= found: no
Code:
1. @RestController
2. @RequestMapping("/book")
3. public class BookRestController {
4.
5. //Path variable id --> Book (200,book,found=yes),
6. //String(400,Sorry No Book found, found=no)
6. @GetMapping("/obj/{id}")
7. public ResponseEntity<?> findBookById(@PathVariable Integer id)
8. {
9. ResponseEntity<?> response = null;
10. HttpHeaders headers = new HttpHeaders();
11.
13. if(id == 501) {
14. headers.add("found", "yes");
15.
16. response = new ResponseEntity<Book>(
17. new Book(id, "DUMMY", 500.0), //body
18. headers, //headers
19. HttpStatus.OK); //http status
20. } else {
21.
22. headers.add("found", "no");
23. response = new ResponseEntity<String>(
24. "Sorry! No Book Found", //body
25. headers, //headers
Spring Boot Webservices and Microservices
26. HttpStatus.BAD_REQUEST); //http status
27. }
28.
29. return response;
30. }
32. }
Note: We can even return direct type (Class Type, Collection type, String type) without
ResponseEntity<>.In this case we cannot provide our Status code and Headers, that is
considered only as body.
Example:
1. @GetMapping("/getAll")
2. public List<User> getAllUser(){
3. List<User> list = repo.allUser()
4. return list;
5. }
=====================
Exception Handling:
=====================
- Spring Boot has given one pre-defined class "BasicErrorController" which takes
care of Default Error and Exception Handling.
- if any exception is occurred in RestController/Controller and programmer not
handled (using try/catch block) then it is taken care by BasicErrorController(C)
and method error().
Spring Boot Webservices and Microservices
************************
Custom Exception Handling:
************************
- We can define our own Response Format in case of Any exception occurred
in application by two ways
Using try/catch
By using annotations @RestControllerAdvice and @ExceptionHandler.
@RestControllerAdvice:
- It is a global class for exception handling.
- Introduce in Spring 4.3 version
- It is executed by FC in the place of BasicErrorController.
- Class level annotation
@ExceptionHandler:
- Every Exception type is compared with this annotation on given methods, if
matched execute, else redirect back to "BasicErrorController".
======================
Consumer Application
======================
- The application which is accessing services from other applications is called as
Consumer application.
- So that, to connect with provider application we use HTTP client “RestTemplate”
class that support HTTP protocol.
Spring Boot Webservices and Microservices
==============
RestTemplate
=============
- It is a class that support http protocol and also called http client.
- It is constructing a request object and executing that request over network and
get the response and store.
- Supports Request Body and Headers creation.
- Reads Response into ResponseEntity or DirectType(String, Employee).
- Auto-type conversion of global Data (JSON/XML-->Object).
RestTemplate Methods:
- RestTemplate has given Methods that support Http methods GET, POST, PUT etc.
exchange() method support all http method call like get, post, put etc.
There is no direct methods for put() and delete() that return
ResponseEntity<>. In that case we use exchange() method.
1. @Component
2. public class PostBookRunner implements CommandLineRunner {
3.
4. @Override
5. public void run(String... args) throws Exception {
6.
7. // 1. create URL
8. String URL = "http://localhost:8585/v1/api/book/create";
9.
10. // 2. Create Headers
11. HttpHeaders header = new HttpHeaders();
12. header.setContentType(MediaType.APPLICATION_JSON);
13.
14. // 3. create Body
15. String body =
16. "{\"bookId\" : 101,\"bookName\" : \"Java\",\"bookPrice\": 3003}";
17. //4. add 2+3
18. HttpEntity<String> requestEntity = new HttpEntity<>(body,header);
19.
20. //5. create Rest Template Object
21. RestTemplate template = new RestTemplate();
22. ResponseEntity<String> res = template.postForEntity(URL, reqEntity, String.class);
23.
24. //6. print on console
25. System.out.println(res.getBody());
26. System.out.println(res.getStatusCode().toString());
27. System.out.println(res.getHeaders());
28. }
Spring Boot Webservices and Microservices
Answer:
- PathVariable is better over RequestParam.
- Because,
Clean URLs (NO SYMBOLS LIKE? and &)
URL LENGTH AND SIZE is reduced
No Overloaded Symbols (NO BURDEN ON SERVER WHILE PARSING URL)
Follows Data/Path sending order.
PathVariableURL: …./employee/find/10/A
Query Parameter/String URL: ………./employee/find?id=10&name=A
Note: Java EE Supports only RequestParam, No PathVariable. It exists in Spring Boot apps.