0% found this document useful (0 votes)
198 views31 pages

ReSTful Web-Services

The document discusses web services and microservices. It describes web applications, clients, servers, HTTP protocol including requests and responses. It also discusses RESTful web services and JSON data format for exchanging data between different applications.

Uploaded by

Java Pro
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
198 views31 pages

ReSTful Web-Services

The document discusses web services and microservices. It describes web applications, clients, servers, HTTP protocol including requests and responses. It also discusses RESTful web services and JSON data format for exchanging data between different applications.

Uploaded by

Java Pro
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Spring Boot Webservices and Microservices

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 Type:

- 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

Request Line Contain three elements


1. HTTP Methods like (GET, POST, PUT, DELETE, PATCH etc..) that describes the
action to be performed.

Example:
GET Indicate a resource should be fetched or POST indicate a resource
should be created or pushed to the server.

2. The request target usually HTTP URL


3. The HTTP Version
Request Header
- Contain Meta data in the form of key:value format
- To tell that what type of data format we send to the body
Example: Content-type: application/JSON, XML
Request Body
- Contain Payload means Business data.

HTTP Response:
1. Start line called as status line contain HTTP version, HTTP Status code and
HTTP Status text.

Example: http/1.1 200 ok


Spring Boot Webservices and Microservices
http/1.0 404 not found.

2. Header same as request Header


3. Body also same as request Body

**NOTE:
- Not all requests have body like GET, HEAD, DELETE or OPTION.

HTTP Status Code:


- When client send request to server then server will process that request
and server will send response to client with status code and Status text.
Type Code
Information 1XX
Success 2XX
Redirect 3XX
Client-Side Error 4XX
Server-side Error 5XX
Spring Boot Webservices and Microservices

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.

Q) What is the difference between PUT and PATCH?


Answer:
PUT: it is recommended to use when full resource is getting modified.
PATCH: used only for partial data update
Q) What is the difference between GET and HEAD?
Answer:
GET: GET Will not support request Body but support response Body and It
is used to fetch data from server
HEAD: Head will not support both request and response body. And just
used to call a task at server (do not know its message, we get only
response code)

Q) What is the difference between POST and PUT?


Answer:
Post is used to send data using its request body (Data is hidden here), that
creates a new resource at server.

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

Q) What is the difference between GET and POST?


Answer:
GET POST
1. It Will not support request Body. Data 1. Post is used to send data using its
will be appended into URL request body (Data is hidden here)
2. It is used to fetch data from server It is used to create a new resource at
server.
3. We cannot submit complex data like 3. We can submit complex data
binary data, image etc.
4. It is store in browser logs. 4. Not store in browser logs

=====================================================================================
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.

- Webservices is a way for two applications to communicate over a network.


Spring Boot Webservices and Microservices
- Web-services also called as integration

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.

What is the difference between Web-application and Web-services?


- In case of web-application, client application must be browser.
- In case of web-services, client application can be other applications.
Web-services there will be two actors-
Spring Boot Webservices and Microservices
 Provider/Producer (Server)
 Consumer (Client)
Provider:
- The application which is giving services to other applications is called as
Provider/Producer application.
- Provider/Producer application gives Response Back by using
Codes/Numbers called as Http Response Status Codes and Http status
message.
Consumer:
- The application which is accessing services from other applications is called
as Consumer application.
- Consumer (Client) always makes request to Producer (Server) application,
using Http Method and URL.
Note: Consumer and Provider will exchange data in the form XML / JSON.
Note: Java language can be a provider and Consumer.
All Languages or all technologies are provider and consumer?
- No, like Swift language or android is only consumer application they do not
provide any services.

Web -services are two types-


 SOAP [Simple Object Access Protocol]
 ReST [Representation State Transfer]
SOAP [Simple Object Access Protocol]:
- SOAP is Protocol (like HTTP) with fully dependent XML/XSD/DTD Standards.
- Slow in processing/ Heavy Code and Configuration.
ReST:
- It is a design of Client-Server using HTTP + Global Data.
Re – Representation means (Global data format)
Spring Boot Webservices and Microservices
S – State means data
T – Transfer means send/receive.
Send/receive data in global format.
====================================
JSON (Java Script Object Notation)
====================================
- JSON (JavaScript Object Notation) is lightweight global data exchange
format in the form of key-value.

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 Object:


- JSON into Java object using the readValue() method of the ObjectMapper
class.

Coding with JACKSON API


=========================

1. Create Maven Project

2. Add Maven Compiler Plugin


1. <properties>
2. <maven.compiler.source>1.8</maven.compiler.source>
3. <maven.compiler.target>1.8</maven.compiler.target>
4. </properties>

3. Add Jackson databind dependency in pom.xml file


1. <dependency>
2. <groupId>com.fasterxml.jackson.core</groupId>
3. <artifactId>jackson-databind</artifactId>
4. <version>2.14.2</version>
5. </dependency>
Spring Boot Webservices and Microservices
4. Create Binding class to represent data
1. @Data
2. @AllArgsConstructor
3. @NoArgsConstructor
4. public class Student {
5. private Integer sId;
6. private String sName;
7. private String sDept;
8. }

5. Create Converter classes


//(Java to JSON)
1. package org.nadim.converter;
2. import java.io.File;
3. import org.nadim.entity.Student;
4. import com.fasterxml.jackson.databind.ObjectMapper;
5. public class JavaToJson {
6. public static void main(String [] args) throws Exception {
7. Student st = new Student(101,"Nadim", "CSE");
8. ObjectMapper om = new ObjectMapper();
9. om.writeValue(new File("student.json"), st);
10. }
11. }

//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.

Working with Gson Api we need below dependency


Spring Boot Webservices and Microservices
1. <dependency>
2. <groupId>com.google.code.gson</groupId>
3. <artifactId>gson</artifactId>
4. <version>2.8.5</version>
5. </dependency>

GSON api we have predefined class i.e 'Gson'

Gson gson = new Gson ( );


gson.toJson(file, obj); // convert java obj to json
gson.fromJson(file, Type); // convert json to java obj

JAVA Object corresponding JSON data

Type -1 Java Normal Object:

Java Code JSON Data


1. public class Employee { {
2. private Integer empId; "empId" : 101,
3. private String empName; "empName" : "Asif",
4. private Double empSalary; "empSalary": 25500
5. } }

Type -2 Java List/Array/SET


Java Code JSON Data
1. public class Employee { {
2. private Integer empId; "empId" : 101,
3. private String empName; "empName" : "Asif",
4. private String [] gender; "gender": [
5. } "Male",
"female",
]
}

Type -3 Has a relationship


Java Code JSON Data
1. public class Employee { 1. {
2. private Integer empId; 2. "empId" : 101,
3. private String empName; 3. "empName" : "Asif",
4. private Double empSalary; 4. "empSalary": 25500,
5. // has a relation 5. "address":{
6. private Address address; 6. "house": "house#12, road",
7. } 7. "city": "Chapainawabgonj"
8. }
9. }
Type -4 Java Map
Spring Boot Webservices and Microservices
Java Code JSON Data
1. public class Product { 1. {
2. private Integer pId; 2. "models": {
3. private String pName; 3. "p1": "Dell 54ips",
4. private Double pPrice; 4. "p2": "Ideapad 320"
5. 5. },
6. private Map<String,String> models; 6. "pid": 101,
7. } 7. "pname": "Laptop",
8. "pprice": 45000.0
9. }

==================
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.

- In XML we have 2 types of elements


 Simple Elements
 Compound Elements
Example:

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.

Marshalling: Converting java obj to xml


Un-Marshalling: Converting xml to java obj

Note: To perform marshalling or Un-marshalling we need to create Binding class with


annotation @XMLRootElement.

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.

Coding With Jax-B API


======================

1. Create maven quick-start project

2. Add Maven Compiler Plugin


1. <properties>
2. <maven.compiler.source>1.8</maven.compiler.source>
3. <maven.compiler.target>1.8</maven.compiler.target>
4. </properties>

3. Add below dependencies


Spring Boot Webservices and Microservices
1. <dependency>
2. <groupId>com.sun.xml.bind</groupId>
3. <artifactId>jaxb-core</artifactId>
4. <version>2.3.0.1</version>
5. </dependency>

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. }

5. Create Converter classes


Java to XML
1. public class JavaToXml {
2. public static void main(String[] args) throws JAXBException {
3. Customer customer =
4. new Customer(101,"Nadim Mostafa","Male",1788050l);
5.
6. JAXBContext jaxb = JAXBContext.newInstance(Customer.class);
7. Marshaller marshaller = jaxb.createMarshaller();
8. marshaller.marshal(customer, new File("customer.xml"));
10. }
11. }
XML to Java
Spring Boot Webservices and Microservices
1. public class XmlToJava {
2. public static void main(String [] args) throws JAXBException {
3.
4. File f = new File("customer.xml");
5.
6. JAXBContext jaxb = JAXBContext.newInstance(Customer.class);
7. Unmarshaller unmarshaller = jaxb.createUnmarshaller();
8. Object object = unmarshaller.unmarshal(f);
9. Customer c = (Customer) object;
10. System.out.println(c);
11. }
12. }

===============+===============+====================+==================+=============
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

Step to create Producer Application:


- To Create ReST API/Producer Application we need to add “Spring-Web”
dependency in pom.xml file.
- Define one controller class.
Spring Boot Webservices and Microservices
- At Producer Application side, we use @RestController annotation over the
controller class.
- Define Required methods and map them to URL + HTTP protocol methods

============
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.

Q) Difference between @Controller and @RestController?

@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.

Case #1: at class level


1. @RestController
2. @RequestMapping("/v1/api/user")
3. public class UserController {
4. // some code
5. }
Case #2: at method level
Spring Boot Webservices and Microservices
1. @RestController
2. @RequestMapping("/v1/api/user")
3. public class UserController {
4.
5. @RequestMapping(value="/get", method = RequestMethod.GET)
6. public ResponseEntity<String> getUser(){
7. return null;
8. }
9. }

Q) What is URL ambiguity in Spring Web?


Answer:
- When multiple rest controller classes contain methods which are binding with
same http methods/request and same url pattern then we will get url ambiguity.

Example:

Open postman and enter URL- http:localhost:8080/get


We will get URL ambiguity problem.

Q) How to solve URL ambiguity in Spring Web?


Answer:
- By using class level mapping using @RequestMapping annotation we can solve
URL ambiguity problem.
Spring Boot Webservices and Microservices

Open postman and enter URL


- http:localhost:8080/v1/api/user/get/
- http:localhost:8080/v1/api/product/get/

Media Type Annotation:


- @RequaestBody
- @ResponseBody

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

Request URL: URL? Key=value


http://localhost:9090/employee/find?id=10&name=nadim

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. }

Here, T = DataType of Response Body.


Allowed or possible T types are-
Spring Boot Webservices and Microservices
-
String, ClassType, Collection, Object (Not recommended) even ? (wild card char) if
type is decided at runtime.
Case-01#(String):
- If T as String, then String object cannot convert to JSON or XML. String object
show on postman or browser as it is.
Case-02#(Class Type):
- If T as Class type, then Class Object convert as Json or XML. Return response as
Json or XML format on Postman or Browser.
- Like
{
“empId”:101,
“empName”: “Nadim”,
“empRole”: “Admin”
}

========================================
? (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

========================== Coding Example ========================


RestController code:
9. package org.nadim.rest;
8.
10. @RestController
11. @RequestMapping("/product")
12. public class ProductAPI {
13.
14. @GetMapping("/get/{id}")
15. public ResponseEntity<String> findProductById(@PathVariable("id") Integer pId)
16. {
16. ResponseEntity<String> response = null;
17. if(pId==101){
18. response = new ResponseEntity<>("Product Exit",HttpStatus.OK);
19. } else{
20. throw new RuntimeException("Product Not Found");
21. }
22. return response;
23. }
25. }

And Send request


http://localhost:8989/product/get/102
- BasicErrorController class error() method returns some pre-defined
response format.
1. {
2. "timestamp": "2022-11-21T01:42:22.666+00:00",
3. "status": 500,
4. "error": "Internal Server Error",
5. "trace": "java.lang.RuntimeException: Product Not Found 5586\r\n\tat
6. …………..
7. …………..
8. "message": "Product Not Found",
9. "path": "/product/get/102"
10. }
11.
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".

Global Exception Coding Step:


1. Create a package org.app.handler, under this package create a class with
any name.
2. Add an annotation @RestControllerAdvice
3. Define one method that return type anything (string, class, list
ResponseEntity)
4. Add annotation @ExceptionHandler (TypeOfExceptionName.class) over the
method.
Spring Boot Webservices and Microservices
Spring Boot Webservices and Microservices

Note: if we want to HttpStatus code as Response then return type should be


ResponseEntity.

======================
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.

1. ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object...


uriPathVariables)
(Or)
ResponseEntity<T> getForEntity(String url, Class<T> responseType)
 Used for GET request and return response as ResponseEntity<T> where T is
String, ClassType or ListType.
 Example:
 String url2 =
"http://localhost:8181/v1/api/book/showB/{id}/{name}";
 ResponseEntity<String> response =
 template.getForEntity(
 url2,
 String.class
 //101,"Java"//path variable for url2
 );

2. ResponseEntity<ResType> postForEntity(String url, HttpEntity<> reqEntity, ResType)


 Used for POST request and return response as ResponseEntity<T>
 HttpEntity = HttpHeaders + Body
 Example: below

3. ResponseEntity<ResType> exchange(url, HttpMethod.POST, reqEntity, String.class);


(Or)
ResponseEntity<ResType> exchange(url, HttpMethod.GET, null, String.class, 101,
"ABC" ); // for Get, we do to send data through body that’s why reqEntity is null
Spring Boot Webservices and Microservices

 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.

Coding Step for Consumer


1. Create URL
2. Create Request Headers (which type of data we send for this, setting header
content type only for Post and Update request.
3. Create Request Body (only for postForEntity())
4. Add 2+3 as HttpEntity<>(body, header) //(only for postForEntity())
5. Create RestTemplate object
6. Make HTTP call and Get Response back
7. print details

Code for postForEntity


======================

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

========================== Question ===============================


Q) What is Content-type header?
Answer:
- This header will represent in which format client sending data to server in request body.

Q) When should we use ResponseEntity<> and Direct Return Type?


Answer:
- If we want to return our own headers/Http status along with Body, then use
ResponseEntity. Else Just return Direct class/String/Collection type that indicates only
body. and HttpStatus and header take care by FrontController

Q) Can we create ResponseEntity object without HttpStatus?


Answer:
- Status is must in case of ResponseEntity object. it can never be null/empty.

Q) Can we create ResponseEntity object without Body?


Answer:
- Body can be null / empty

Q) Can we create ResponseEntity object without Headers?


Answer:
- Custom headers can be null / empty

Q) Which one is better to use PathVariable or RequestParam? And why?

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.

Q) when use @RequestParam (Query String) [or] @PathVariable and @RequestBody?


Spring Boot Webservices and Microservices
Answer:
- If I want to get the data based on input or if data is not store in db then we use Query
Parameter/String or PathVariable.
- Example: “SELECT * FROM employee WHERE empId=10 and empName=”nadim”

@RequestBody: If I want to process some data and store in Database.


Q) How client send data to the provider application using GET request?
Answer:
- Using query parameters and path variables

Q) can we config multiple URL pattern?


Answer:
- Yes, we can do that.
- Example:
 @GetMapping(value={“/create”, “/add”, “/”}

Q) What is the meaning of Accept = application/xml?


Answer:
- Means to tell the producer app or request the producer, please give me response
or output data in xml format.
- Accept means Which format the method give response xml or Json.

Q) what is produces={“application/xml”, “application/Json”}?


Answer:
- using in @GetMapping(produces={“application/xml”, “application/Json”}) for
provider to tell which format give the response.

Q) what is consumes={“application/xml”, “application/Json”}?


Answer:
- using in @PostMapping(produces={“application/xml”, “application/Json”}) to tell,
taking data from user/consumes app and that data comes in which format.

Q) How can we avoid one field/variable in JSON operations?


Answer:
- @JsonIgnore (used this annotation on entity class variable only)
 Is used to ignore a particular variable value to convert Json to java or Java
to Json. Like user passward.
Spring Boot Webservices and Microservices
- Ex:
@JsonIgnore
private String password;

Q) Do we need to apply @ResponseBody in Spring boot rest ?


Answer:
- Not required. By default, @RestController gives it.

Q) What will happen if variable holds null and in JSON Operations?


Answer.
- null is printed.

Q) how can we provide alias names to variables in JSON?


Answer:
- @JsonProperty (used this annotation on entity class variable only)
- Ex:
@JsonProperty("user-first-name")
private String userName;

Q) How do you handle exceptions in your Rest Applications?


Answer:
- Here Service Layer throw exception based on some conditions. Catch by RestController
and re-thrown to GlobalHandler. Global Exception Handler compares exception type and
returns Custom Error Message with status code.
Request->FrontController->HandlerMapper->RestController->call service -> call Repo -> No Data
-> Service throw exception -> catch in RestController -> throw exception obj -> Exception
Handler -> compare type-> Return custom message.

You might also like