Rest
Rest
txt
===================
Java Microservices
===================
----------------
Course content
---------------
=================
RESTFul Services
=================
1) What is Distributed Application ?
2) Distributed Technologies
3) REST Architecture
- Provider
- Consumer
4) HTTP Protocol
- Request
- Response
- Methods
- Status Codes
7) Provider Development
- @RestController
- @RequestParam
- @PathVariable
- @RequestBody
- @GetMapping
- @PostMapping
- MediaTypes ( consumes & produces )
- RestTemplate (Sync)
- @RestControllerAdvice
- @ExceptionHandler
https://ashokitech.com/uploads/notes/29651410_1683292222.txt 1/19
6/6/23, 12:16 PM ashokitech.com/uploads/notes/29651410_1683292222.txt
==============
Microservices
===============
================
Spring Security
=================
1) Basic Auth
2) OAuth 2.0
3) JWT
=============
Integrations
=============
=================
RestFul Services
================
=================================================================
Why one application should communicate with another application?
=================================================================
==========================
Distributed Technologies
==========================
https://ashokitech.com/uploads/notes/29651410_1683292222.txt 2/19
6/6/23, 12:16 PM ashokitech.com/uploads/notes/29651410_1683292222.txt
1) CORBA
2) RMI
3) EJB
4) SOAP Webservices
5) RESTFul Services (Trending)
===================
REST Architecture
====================
1) Provider / Resource
2) Consumer / Client
Provider: The application which is giving services to other applications is called as Provider
application.
Consumer : The application which is accessing services from other applications is called as
Consumer application.
=============================================================
How communication will happen between Provider & Consumer ?
=============================================================
-> HTTP protocol will act as mediator between Consumer and Provider
-> Consumer and Provider will exchange data in the form XML / JSON
==============
HTTP Protocol
==============
1) Http Request
2) Http Response
3) HTTP Methods
4) HTTP Status Codes
==============
HTTP Methods
==============
==================
HTTP Status Codes
===================
-> When client send request to server then server will process that request and server will send
response to client with status code.
https://ashokitech.com/uploads/notes/29651410_1683292222.txt 3/19
6/6/23, 12:16 PM ashokitech.com/uploads/notes/29651410_1683292222.txt
=============
HTTP Request
==============
===============
HTTP Response
===============
====================================
JSON (Java Script Object Notation)
====================================
Synax:
"id" : 101,
"name" : "Ashok",
"gender" : "Male",
"phno" : 463413
"address" : {
"city" : "Hyd",
"state" : "TG"
}
=> As part of REST API development, we need to convert Java Obj data to JSON format and JSON data
to Java Object
=> In Java we don't have direct support to convert java to json and vice versa.
https://ashokitech.com/uploads/notes/29651410_1683292222.txt 4/19
6/6/23, 12:16 PM ashokitech.com/uploads/notes/29651410_1683292222.txt
=> We have below third party apis to work with JSON data in Java applications
1) Jackson api
2) Gson api
==============
Jackson API
==============
=> ObjectMapper class provided methods to convert java to json and vice versa
========================
Working with JACKSON API
========================
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.14.2</version>
</dependency>
@Data
public class Address {
@Data
public class Customer {
https://ashokitech.com/uploads/notes/29651410_1683292222.txt 5/19
6/6/23, 12:16 PM ashokitech.com/uploads/notes/29651410_1683292222.txt
addr.setState("TG");
addr.setCountry("India");
}
}
System.out.println(c);
==========
GSON API
=========
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
===============
XML and JAX-B
===============
Ex: <id>101</id>
https://ashokitech.com/uploads/notes/29651410_1683292222.txt 6/19
6/6/23, 12:16 PM ashokitech.com/uploads/notes/29651410_1683292222.txt
1) Simple Elements
2) Compound Elements
<person>
<id>101</id>
<name>smith</name>
<address>
<city>Hyd</city>
<state>TG</state>
</address>
</person>
-> Elements which contains data directley are called as Simple Elements
<id>101</id>
<name>smith</name>
<city>Hyd</city>
<state>TG</state>
-> Elements which contains child elements are called as compound elements
<person>
<address>
==========
JAX-B API
===========
-> Using JAX-B API we can convert xml data to java object and vice versa
Note: Upto 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
=======================
Working with JAX-B API
=======================
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
https://ashokitech.com/uploads/notes/29651410_1683292222.txt 7/19
6/6/23, 12:16 PM ashokitech.com/uploads/notes/29651410_1683292222.txt
<artifactId>jaxb-core</artifactId>
<version>2.3.0.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.25.0-GA</version>
</dependency>
@Data
@XmlRootElement
public class Customer {
System.out.println("xml created....");
}
JAXBContext context =
JAXBContext.newInstance(Customer.class);
https://ashokitech.com/uploads/notes/29651410_1683292222.txt 8/19
6/6/23, 12:16 PM ashokitech.com/uploads/notes/29651410_1683292222.txt
System.out.println(c);
}
}
=====================
Provider Development
=====================
-> The app which is providing services to other apps is called as Provider
a) web-starter
3) Write the Required methods and map them to URL + HTTP protocol methods
@PostMapping("/msg")
public ResponseEntity<String> saveMsg() {
// logic to save msg
String responseBody = "Msg Saved Successfully";
return new ResponseEntity<String>(responseBody, HttpStatus.CREATED);
}
@GetMapping("/welcome")
public ResponseEntity<String> getWelcomeMsg() {
String msg = "Welcome to REST API..!!";
return new ResponseEntity<String>(msg, HttpStatus.OK);
}
@GetMapping("/greet")
public String getGreetMsg() {
return "Good Evening";
}
}
======================================================================================
@Data
public class User {
https://ashokitech.com/uploads/notes/29651410_1683292222.txt 9/19
6/6/23, 12:16 PM ashokitech.com/uploads/notes/29651410_1683292222.txt
@RestController
public class UserRestController {
@PostMapping("/user")
public ResponseEntity<String> addUser(@RequestBody User user) {
System.out.println(user);
dataMap.put(user.getId(), user);
return new ResponseEntity<String>("User Saved", HttpStatus.CREATED);
}
}
=======================================================================================
{
"id" : 202,
"name" : "John",
"email" : "john@gmail.com"
}
=====================================================================
===================================
Query Parameters & Path Parameters
===================================
=> Query Parameters & Path Parameters are used to send data in URL
QP Ex : https://www.youtube.com/watch?v=8eVaci9WvP8
PP Ex : www.ashokitech.com/courses/java
Note: When client is sending GET request then client can use Query Params or Path Params to send
data to Server
Note: GET request will not contain Request Body so we have to use either Query Param or Path Param
to send data to server.
================
Query Parameters
================
https://ashokitech.com/uploads/notes/29651410_1683292222.txt 10/19
6/6/23, 12:16 PM ashokitech.com/uploads/notes/29651410_1683292222.txt
=> To read Query Params from URL we will use @RequestParam annotation
@GetMapping("/user")
public User getUser(@RequestParam("userid") Integer userId) {
User user = dataMap.get(userId);
return user;
}
URL : http://localhost:8080/user?userid=202
----------------
Path Parameters
----------------
-> Path Param will start with '/' and will be seperated by '/'
-> We need to represent Path Parameters position in the URL pattern like below
Ex: @GetMapping("/user/{id}/data")
@GetMapping("/user/{id}/data")
public User getUser(@PathVariable("id") Integer userId) {
User user = dataMap.get(userId);
return user;
}
====================
Consumes & Produces
===================
consumes : It represents in which format REST API method can accept input data from client
produces : It represents in which format REST API method can provide response to clients
Content-Type : This header will represent in which format client sending data to server in request
body
Accept : This header will represent in which format client expecting response from server
https://ashokitech.com/uploads/notes/29651410_1683292222.txt 11/19
6/6/23, 12:16 PM ashokitech.com/uploads/notes/29651410_1683292222.txt
@Data
@XmlRootElement
public class Book {
}
------------------------------
@RestController
public class BookRestController {
@PostMapping(
value="/book",
consumes = {"application/xml", "application/json"}
)
public ResponseEntity<String> addBook(@RequestBody Book b){
System.out.println(b);
//logic to save in db
String msg = "Record Saved";
return new ResponseEntity<>(msg, HttpStatus.CREATED);
}
@GetMapping(
value="/book",
produces = {"application/xml", "application/json"}
)
public Book getBook() {
Book b = new Book();
b.setId(101);
b.setName("Java");
b.setPrice(130.00);
return b;
}
}
----------------------------------------------------------------------
=============
Requirement
=============
https://ashokitech.com/uploads/notes/29651410_1683292222.txt 12/19
6/6/23, 12:16 PM ashokitech.com/uploads/notes/29651410_1683292222.txt
consumes : application/json
produces : application/json
======================
Development Procedure
======================
a) web-starter
b) lombok
c) devtools
-------------------
Request data
-------------------
{
"name": "John",
"from": "Hyd",
"to": "Delhi",
"doj" : "15-May-2023",
"trainNumber" : "46464"
}
======================
Swagger Configuration
======================
=> Swagger is a third party Library (we need to add in our app)
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
https://ashokitech.com/uploads/notes/29651410_1683292222.txt 13/19
6/6/23, 12:16 PM ashokitech.com/uploads/notes/29651410_1683292222.txt
<version>2.4.0</version>
</dependency>
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket apiDoc() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("in.ashokit.rest"))
.paths(PathSelectors.any())
.build();
}
}
Note: If we are getting NPE when we run the application, then add below property in
application.properties file
spring.mvc.pathmatch.matching-strategy = ANT_PATH_MATCHER
=================================================================
IRCTC CLOUD API URL : http://13.232.253.164:8080/swagger-ui.html
=================================================================
=====================
Consumer Development
======================
=> The application which is accessing services from other applications is called as Consumer
application.
=====================================================
Steps To develop Make My Trip Application (Consumer)
=====================================================
a) web-starter
b) thymeleaf-starter
c) lombok
d) devtools
https://ashokitech.com/uploads/notes/29651410_1683292222.txt 14/19
6/6/23, 12:16 PM ashokitech.com/uploads/notes/29651410_1683292222.txt
============================================================================
@Service
public class MakeMyTripServiceImpl implements MakeMyTripService {
@Override
public Ticket bookTicket(Passenger passenger) {
return ticket;
}
@Override
public Ticket getTicketByNum(Integer ticketNumber) {
ResponseEntity<Ticket> respEntity =
rt.getForEntity(GET_TICKET_URL, Ticket.class, ticketNumber);
return ticket;
}
=================================================================================
========================================================================
=> Using WebClient we can send HTTP Requests (GET, POST, PUT, DELETE)
https://ashokitech.com/uploads/notes/29651410_1683292222.txt 15/19
6/6/23, 12:16 PM ashokitech.com/uploads/notes/29651410_1683292222.txt
@Service
public class MakeMyTripServiceImpl implements MakeMyTripService {
@Override
public Ticket bookTicket(Passenger passenger) {
return ticket;
@Override
public Ticket getTicketByNum(Integer ticketNumber) {
return ticket;
}
}
============================
Sync & Async Communication
============================
Sync Communication : After sending the request thread will wait for Response
ASync Communication : After sending the request thread will not wait for response
@SpringBootApplication
public class Application {
https://ashokitech.com/uploads/notes/29651410_1683292222.txt 16/19
6/6/23, 12:16 PM ashokitech.com/uploads/notes/29651410_1683292222.txt
webClient.get()
.uri(url,6)
.retrieve()
.bodyToMono(String.class)
.subscribe(Application::handleResponse);
----------------------------------------------------
How to send Request Header and Body using WebClient
----------------------------------------------------
@Override
public Ticket bookTicket(Passenger passenger) {
return ticket;
}
------------------------------------------
=====================================================
application.properties file Vs application.yml file
=====================================================
-> In Spring Boot we will use .properties or .yml file to configure application properties
https://ashokitech.com/uploads/notes/29651410_1683292222.txt 17/19
6/6/23, 12:16 PM ashokitech.com/uploads/notes/29651410_1683292222.txt
1) POM starters
2) Dependency Version management
3) Auto Configuration
4) Embedded Server
5) Actuators
============
Actuators
============
-> Actuators are used to provide production-ready features for our application
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
-> We can write below configuration in application.yml file to expose actuator endpoints
-------------------------------application.yml----------------------
management:
endpoints:
web:
exposure:
include: '*'
exclude: 'beans'
endpoint:
shutdown:
enabled: true
---------------------------------------------------------------------
health : http://localhost:8080/actuator/health
mappings : http://localhost:8080/actuator/mappings
beans : http://localhost:8080/actuator/beans
heapdump : http://localhost:8080/actuator/heapdump
threaddump : http://localhost:8080/actuator/threaddump
Shutdown : http://localhost:8080/actuator/shutdown
https://ashokitech.com/uploads/notes/29651410_1683292222.txt 18/19
6/6/23, 12:16 PM ashokitech.com/uploads/notes/29651410_1683292222.txt
Note: Shutdown is a special endpoint which is used to stop our application and it is mapped to
POST request.
====================================================================
https://ashokitech.com/uploads/notes/29651410_1683292222.txt 19/19