REST API Development Material
-> Webservices is a distributed technology which is used to develop distributed
applications.
-> If one application is communicating with another application then those applications
are called as distributed applications.
Ex- :
[Link] -------> Whatsapp / RazorPay / Teachable
Gpay ----------> SBI Bank App
MakeMyTrip ------> IRCTC App
frontend app -------> Backend App
(angular) (Java SB)
=> Distributed applications are used for Business 2 Business Communication (B 2 B).
-> Distributed applications should have interoperability.
-> Interoperability means language independent & platform independent.
java app <--------> python app
java app <--------> dot net app
java app <---------> php app
java app <---------> Angular app
java app <---------> React app
=> Web Services we can develop in 2 ways
1) SOAP Web services (xml based and out-dated)
2) Restful web services (Trending)
What is REST API ?
=> REST API means one distributed application which will provide services to other
applications.
REST API = REST Service / Restful Web services / Micro services
REST API Architecture
=> Provider means the application which is providing business services to other
applications.
=> Consumer means the application which is accessing business services from other
applications.
Note: Consumer and Provider applications will exchange data using JSON format.
What is JSON
=> JSON stands for Java Script Object Notation.
=> JSON represents data in key-value format.
Ex :
Note: Key is a string so we will keep it in double quotes. If value is also a string then keep
it in double quotes.
=> JSON is very light weight.
=> JSON is platform independent & language independent.
=> JSON is interoperable.
=> JSON is used to transfer data over a network.
=> Distributed applications will use JSON data for request & response.
Ex : MakeMyTrip <---------- json ----------> IRCTC
Working with JSON in Java Applications
=> In java applications we can represent data in json format.
=> To work with JSON in Java app, we have third party libraries
a) Jackson
b) Gson (google)
=> By using above libraries we can convert JSON data to Java Object and vice versa.
=> The process of converting java obj to json is called as Serialization.
=> The process of converting json data to java obj is called as de-serialization.
Jackson API
1) Create Maven Project using IDE
2) Add below dependency in [Link] file
3) Create binding class to represent data
public class Customer {
private Integer id;
private String name;
private Long phno;
// setters & getters
// toString ( )
}
GSON API
### Git Hub Rep : [Link]
<dependency>
<groupId>[Link]</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
Gson gson = new Gson ( );
[Link](Object obj);
[Link](File file);
How to Consumer and Provider will Communicate
=> End User will communicate with MakeMyTrip application to book Train ticket.
=> MakeMyTrip application will take passenger and will send to IRCTC to book train ticket.
=> IRCTC will book train ticket and will send ticket information to MakeMyTrip
application.
=> Make My Trip app will give ticket to end user.
HTTP Protocol
=> HTTP stands for Hyper Text Transfer Protocol.
=> HTTP acts as mediator between Client & Server.
=> HTTP is stateless protocol.
=> HTTP Protocol can't remember the conversation happened between client and server.
HTTP Methods
GET ---------> It is used to get data from server
POST ---------> It is used to send data to server
PUT ---------> It is used to update the data at server (full update)
PATCH ---------> It is used to update partial data
DELETE --------> It is used to delete resource at server
HTTP Status Codes
1xx ------ (100 - 199) : Information
2xx ------- (200 - 299): Success
3xx ------- (300 - 399): Redirection
4xx ------- (400 - 499): Client Error
5xx ------- (500 - 599): Server Error
What is PostMan
Postman is a popular tool used by developers to test APIs (Application
Programming Interfaces).
It provides a user-friendly interface for sending HTTP requests, such as GET, POST,
PUT, and DELETE, to APIs and receiving responses.
This helps developers to understand how APIs work, debug issues, and ensure that
they are functioning correctly.
Provider Endpoint : [Link]
Spring Boot Rest API Development Process
To develop Rest API we will use @RestController annotation
@RestController annotation will represent our java class as Distributed Component
@RestController = @Controller + @ResponseBody
To develop Consumer we have below 3 options
RestTemplate
WebClient
FeignClient
Provider (Rest API) Application Development
Step-1: Create Spring Boot application with below starter
a) Web-starter
Step-2: Create Rest Controller class like below
Step-3: Run the application and test it using Postman
How to send JSON response to client application
=> When we return Object (s) from Rest Controller method then springboot internally
converts Java Object into JSON using Jackson api and will send JSON response to client.
=> In below BookRestController we are returning Object as response
HTTP GET Request
=> GET request is used to get data from Server/Provider.
=> GET request will not contain request body.
Ex : GET [Link]
=> If we want to send data to server using GET request then we need to use
1) Query Parameters
2) Path Parameters
Ex-1(query Param) : [Link]
Ex-2 (Path param) : [Link]
Ex-4 (Path Param) : [Link]
What is Query Parameter?
=> It is used to send data from client to server in URL
=> It represents data in key-value format
id=101
name=Ashok
=> It will start with '?' and it will be seperate by '&'
=> It will present only at end of the URL
URL : [Link]
Note: To read query parameters from URL we will use @RequestParam.
What is Path Parameter?
=> It is used to send data from client to server in URL
=> Path Parameter will represent data directly (No Key)
Ex: [Link]
=> Path Parameter can present anywhere in the URL
=> Path Parameter position will be represented in Method URL pattern
Note: To read path parameters we will use @PathVariable annotation.
HTTP Post Request
=> HTTP POST method is used to send data from client to server
=> We can send payload from client to server in Request Body
Ex: json or xml or text or form data or binary data
=> To map our Rest Controller method to POST request we will use @PostMapping annotation
Note: To read data from request body we will use @RequestBody annotation
produces : Represents rest api method response body data format
consumes : Represents rest api method request body data format
HTTP PUT Request
=> PUT method is used for updating resource/record
=> Using HTTP Put Request, we can send data to server in below 3 ways
a) Query Params
b) Path params
c) Request Body
=> To map our Rest Controller method to PUT request we will use @PutMapping
annotation.
HTTP DELETE Request
=> DELETE method is used for deleting resource/record
=> Using HTTP DELETE Request, we can send data to server in below 3 ways
a) Query Parameters
b) Path Parameters
c) Request Body
=> To map our Rest Controller method to DELETE request we will use @DeleteMapping
annotation.
Assignment: Develop Spring Boot REST API to perform Crud operations with Database
table using Spring Data jpa.
@@ Reference Video : [Link]
How to support both XML & JSON data in REST API
To support both xml and json for input and output formats we need to know about below 4
concepts
o Consumes
o Produces
o Accept Header
o Content-Type Header
Consumes is used to specify in which format REST API method can accept request payload.
Produces is used to specify in which format REST API method can produce response
payload.
Content-Type header is used to specify in which format consumer sending Request payload.
Accept Header is used to specify consumer expecting response payload.
Note: If we develop REST API with both xml and json data then it will be more flexible and
consumers can decide in which format they want to send and receive data.
What is XML ?
-> XML stands for extensible mark-up language
-> XML is free and open source
-> XML governed by w3c org.
-> XML represents data in the form of elements
Ex: <name>ashok it</name>
-> XML is used to represent the data
-> XML is interoperable (language and platform independent)
-> We have 2 types of elements in xml
1) Simple element (element which contains data directly)
2) Compound element (element which contains child elements)
Dealing with xml data in java applications
=> Up to java 1.8v we have JAX-B api in jdk to deal with xml files in java.
=> Using JAX-B api we can convert java object to xml and vice versa.
Note: From java 9 onwards jax-b api is not part of JDK software.
=> If we want to deal with xml data in java applications, we need to add dependency.
Marshalling : Converting java object to xml data
Un-Marshalling : Converting xml data to java object
=> To deal with xml data in spring boot rest api we need to add below dependency in
[Link] file.
Below GET request method can produce both json and xml response to consumer.
Consumer can send request with Accept header to receive response in particular format
Sending GET request with Accept = application/json using POSTMAN
Sending GET request with Accept = application/xml using POSTMAN
Below POST request method can consume both xml and json data
Sending POST request with XML data in request body using POSTMAN
Below PUT request method can consume both xml and json and can produce both xml and
json.
Sending PUT request with both Content-Type and Accept header using POSTMAN
What is Swagger ?
=> Swagger is used to generate documentation for REST API
=> Using Swagger UI we can test rest api.
=> Add below dependency in [Link] file and update maven project.
=> After running the application use below url to access swagger-documentation
URL : [Link]
Consumer Development
=> The application which is accessing services from other applications is called as Consumer
application.
=> Using Spring Boot we can develop Consumer in 3 ways
1) Rest Template (sync)
2) Web Client (sync + async)
3) Feign Client
=> "RestTemplate" is a predefined class in 'spring-web-mvc' module. It supports only
Synchronus communication.
=> "WebClient" interafce introduced in spring 5.x version and it is part of 'spring-web-flux'. It
supports both sync & async communication.
=> FeignClient is part of 'spring-cloud-libraries'. It supports interservice communication.
What is Synchronus Communication ?
=> After sending request to provider if consumer is waiting for the response then it is called
as Synchronus communication.
What is Asynchronus Communication ?
=> After sending request to provider if consumer is not waiting for the response then it is
called as asynchronus communication.
Note : Weather we need to use sync client or async client is depends on project
requirement.
Consumer Application Development
1) Create SpringBoot application with 'web-starter'
2) Create Service class to access provider api using RestTemplate
Provider URL (GET) : [Link]
3) Call the service method in start class for testing.
Developing Consumer (MakeMyTrip) application with below functionalities
1) View Tickets
2) Book Ticket
View Tickets Page design
Book Ticket Page Design
Make My Trip application will communicate with IRCTC provider to deal with tickets booking.
Below is the provider Swagger Documentation.
Consumer Application Architecture and Development Process
1) Understand provider swagger documentation
2) Create Consumer Application with required dependencies
a) web-starter
b) thymeleaf
3) Design Request and Response binding classes to perform B2B communication
Request : [Link]
Response : [Link]
4) Develop Service component to send request to provider
Method-1 : bookTicket ( )
input : passenger
output : ticket
Method-2 : getTickets ( )
input : NA
output : tickets
5) Develop Controller with required methods
- index () -> to display all tickets
- loadBookTicketPage () -> display ticketBooking form
- bookTicket() -> handle ticket booking functionailty
6) Create UI pages
- [Link]
- [Link]
What is WebClient
=> It is pre-defined interface which is part of 'spring-webflux-starter' (reactive-web)
=> Using WebClient interface we can send HTTP requests to provider applications.
=> WebClient supports both sync & async communications.
Sending GET request using WebClient (Synchronus)
Sending GET request using WebClient (Synchronus) and map response to Java Object
Sending GET request using WebClient (Asynchronus)
Sending POST request using WebClient