0% found this document useful (0 votes)
103 views25 pages

RESTFul Services

The document discusses RESTful services and their use in developing distributed applications with interoperability. It defines key terms like REST, distributed applications, providers, consumers, and describes how RESTful services use HTTP and JSON/XML formats to allow applications developed in different languages and platforms to communicate and exchange data.
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)
103 views25 pages

RESTFul Services

The document discusses RESTful services and their use in developing distributed applications with interoperability. It defines key terms like REST, distributed applications, providers, consumers, and describes how RESTful services use HTTP and JSON/XML formats to allow applications developed in different languages and platforms to communicate and exchange data.
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/ 25

RESTFul Services

+++++++++++++++

-> REST stands for 'Representational State Transfer'

-> RESTFul services are used to develop Distributed Applications with

Intereoperability

-> If one application is communicating with another application then

those are called as 'Distributed Apps'

-> Intereoperability means irrespective of the platform and language

applications can communicate

java app <-----------> .Net app

.Net app <----------> Python app

Python app <---------> Java App

-> Distributed applications are used for B 2 B communications

-> B2B means Business to Business Communication

-> Distributed Application will re-use services of one application in

another application

-> RESTful Services are providing 'Intereoperability'

-> Two Actors will be involved in Distributed Applications development

1) Provider

2) Consumer

-> The application which is providing business services is called as

Provider Application

-> The application which is accessing business services is called as

Consumer Application

Note: One provider application can have multiple consumer applications

-> Provider and Consumer will communicate using HTTP as a mediator


-> Provider and Consumer will exchange the data in Text / XML / JSON

format

Note: In Industry we will use JSON format to exchange data from one

application to another application

-> To start our journey with RESTFul services development we should be

good in below areas

1) HTTP Protocol (Methods, Status Codes, Req structure & Res Structure)

2) XML and JAX-B Api

3) JSON and Jackson Api

################

What is HTTP ?

################

-> HTTP stands for Hyper Text Transfer Protocol

-> It acts as a mediator between client & server ( Consumer & Provider )

-> Consumer application will send HTTP Req to Provider application

-> Provider application will process the request and it will send HTTP

response to Consumer

###############

HTTP Methods

###############

-> HTTP methods are used to send request from Consumer application to

Provider application

-> HTTP method will represent what type of operation client / consumer

wants to perform with Provider

a) GET

b) POST
c) PUT

d) DELETE

-> GET request is used to retrieve data from Server / Provider

application.

-> GET request will not have body to send data in the request

-> To send any data using GET request then we will use Path Params & Query Params

Note: Path Params & Query Params data will be displayed in the URL

Note: It is not recommended to send sensitive / secret data using Path

Params & Query Params

-> GET request is Idempotent (means if you send same GET request for

multiple times also nothing will change at server)

-> POST request is used to create a new record at server

-> When consumer wants to send huge data/ sensitive data then Consumer

will use POST request

-> POST request contains request body

-> POST request is Non-Idempotent

Note: In POST request we can send data in URL and in Request Body.

Note: Request Body is the recommended approach to send sensitive data to

server

-> PUT request is used to update a record at server

-> When consumer wants to update a record at then consumer will send PUT

request to Provider

-> PUT request contains request body

-> PUT request is Idempotent

Note: In PUT request we can send data in URL and in Request Body.

Note: Request Body is the recommended approach to send sensitive data to


server

-> DELETE request is used to delete a record at server

-> DELETE request contains request body

-> DELETE request is Idempotent

Note: In DELETE request we can send data in URL and in Request Body.

######################

HTTP Request Structure

#######################

1) Intial Request Line ( HTTP method + URL )

2) Request Headers ( key-value )

3) Blank Line to seperate Header & Body

4) Request Body (Request Payload)

######################

HTTP Response Structure

#######################

1) Initial Response line (Protocl Version + Status Code + Status msg)

2) Response Headers (Key-value)

3) Blank Line to seperate Header & Body

4) Response Body (Response Payload)

##################

HTTP Status Codes

##################

-> HTTP Status codes will represent how the request process by server /

provider

1xx (100 - 199) ---> INFO

2xx (200 - 299) ---> OK (success)


3xx (300 - 399) ---> Redirect

4xx (400 - 499) ---> Client Error

5xx (500 - 599) ---> Server Error

XML & JAX-B

#############

-> XML stands for Extensible Markup Language

-> XML is free & open source

-> XML is intereoperable (Language independent & Platform indenpendent)

-> XML we can use to transfer data from one application to another

application

-> XML introduced by w3c org

-> The initial version of xml is 1.0 and the current version of xml is

also 1.0

-> XML will represent data in the form of elements

-> An element is the combination of start tag and end tag

Ex: <name> Jensoft </name>

-> We will have 2 types of elements in the XML

1) Simple Element

2) Compound Element

-> The element which contains data directley is called as Simple Element

<name> Jensoft </name>

<type> Educational </type>

-> The element which contains child element(s) is called as Compound

Element

<person>
<id> 101 </id>

<name> raju </name>

</person>

Note: here <person> is a compound element and <id> <name> are simple

elements

-> We can have attributes also for the element

<student branch="CSE">

<id> 101 </id>

<name> Mahesh </name>

</student>

Note: XML should have only one root element. Inside the root element we

can have multiple child elements

<persons>

<person>

<id> 101 </id>

<name> raju </name>

</person>

<person>

<id> 101 </id>

<name> raju </name>

</person>

</persons>

###########

JAX-B

############

-> JAX-B stands for Java Architecture For XML Binding


-> JAX-B is used to convert Java object to xml and xml to java object

-> JAX-B is free and open source

-> JAX-B given by sun microsystem

-> JAX-B is part of JDK upto 1.8v

-> If you are using JDK 1.8+ version of java then you need to add JAX-B

dependency in pom.xml file

-> The process of converting Java Object into xml is called as

"Marshalling"

-> The process of converting XML data to Java Object is called as "UnMarshalling"

-> To perform Marshalling and Un-Marshalling We need to design Binding

Classes.

-> The java class which represents the structure of XML is called as

Binding class.

-> JAX-B provided annotations to represent java class as Binding Class.

Note: Binding Class creation is one time operation.

Note: Earlier people used to create Binding Classes using XSD. XSD

represents structure of xml.

#####################

Marshalling Example

#####################

@Data

@XmlRootElement

public class Person {

private Integer id;

private String name;

private Integer age;


private Long phno;

private Address adress;

----------------------------------

@Data

public class Address {

private String city;

private String state;

private String country;

----------------------------------------

public class ConverJavaToXml {

public static void main(String[] args) throws Exception {

Address addr = new Address();

addr.setCity("Hyd");

addr.setState("TG");

addr.setCountry("India");

Person person = new Person();

person.setId(101);

person.setName("John");

person.setAge(25);

person.setPhno(12575757l);

person.setAdress(addr);

JAXBContext instance = JAXBContext.newInstance(Person.class);

Marshaller marshaller = instance.createMarshaller();


marshaller.marshal(person, new File("Person.xml"));

System.out.println("Marshalling Completed....");

-------------------------------------------------------------------------

----

@XmlAccessorType(XmlAccessType.FIELD) : Controls marshalling and unmarshalling using fields of


entity class

@XmlAccessorOrder : Follow order of variables in the class to marshall

and un-marshall

@XmlElement(name = "PhoneNum") : It is used to change the name of element

@XmlAttribute : It represents variable as attribute in xml

@XmlTransient : To skip a variable in marshalling

Note: By default every variable will be considered as Element and

variable name will be considered as element name.

@Data

@XmlRootElement

@XmlAccessorType(XmlAccessType.FIELD)

@XmlAccessorOrder

public class Person {

private Integer id;

private String name;

@XmlTransient

private Integer age;

@XmlElement(name = "PhoneNum")

private Long phno;

@XmlAttribute
private String type;

private Address adress;

-------------------------------------------------------------------------

------------------------------

public class ConvertXmlToJava {

public static void main(String[] args) throws Exception {

File xmlfile = new File("Person.xml");

JAXBContext context = JAXBContext.newInstance(Person.class);

Unmarshaller unmarshaller = context.createUnmarshaller();

Object object = unmarshaller.unmarshal(xmlfile);

Person person = (Person) object;

System.out.println(person);

-------------------------------------------------------------------------

------------

########

JSON

########

-> JSON stands for Java Script object notation

-> JSON will represent data in key-value format

Ex :

"id" : 101,
"name: "raju",

"age" : 20

-> JSON is intereoperable (language in-dependent & platform independent)

-> JSON is light weight

-> JSON is both human readable and machine readable format

-> In today's world people are using JSON format to exchange the data in

B2B communications

-> Now a days JSON is having more demand than XML because of its

simplicity and light weight

-> XML represents data in tags format (open tag & closed tag)

-> Meta data will be more than actual data in XML

-> XML occupies more memory to represent data

-> JSON will take less memory

-> JSON is light weight

-> To work with JSON data in Java Applications we have below 3rd party

APIs

1) JACKSON API

2) GSON API

-> By using above apis we can convert JSON data to Java Object and vice

versa

-> The process of converting Java Object into JSON is called as

Serialization

-> The process of converting JSON data to Java Object is called as DeSerialization

1) Create Maven project with below dependencies

<dependencies>
<dependency>

<groupId>com.fasterxml.jackson.core</groupId>

<artifactId>jackson-databind</artifactId>

<version>2.13.3</version>

</dependency>

<dependency>

<groupId>org.projectlombok</groupId>

<artifactId>lombok</artifactId>

<version>1.18.24</version>

<scope>provided</scope>

</dependency>

</dependencies>

2) Create Java classes to represent data (Use lombok)

@Data

public class Author {

private String authorName;

private String authorEmail;

private Long authorPhno;

@Data

public class Book {

private Integer id;

private String name;

private Double price;

private Author author;


}

3) Create Java class to convert Java Obj to JSON file

public class JavaToJsonConverter {

public static void main(String[] args) throws Exception {

Author author = new Author();

author.setAuthorName("Rod Johnson");

author.setAuthorEmail("[email protected]");

author.setAuthorPhno(86868686l);

Book book = new Book();

book.setId(101);

book.setName("Spring");

book.setPrice(450.00);

book.setAuthor(author);

ObjectMapper mapper = new ObjectMapper();

// converting java obj to json and store into a file

mapper.writeValue(new File("book.json"), book);

System.out.println("Conversion Completed....");

4) Create Java Class To Convert JSON to Java Object

public class JsonToJavaConverter {

public static void main(String[] args) throws Exception {

File jsonFile = new File("book.json");

ObjectMapper mapper = new ObjectMapper();

Book book = mapper.readValue(jsonFile, Book.class);

System.out.println(book);
}

++++++++++++++++++++++

Working with GSON API

+++++++++++++++++++++++

1) Create a maven project with below dependency

<dependency>

<groupId>com.google.code.gson</groupId>

<artifactId>gson</artifactId>

<version>2.9.0</version>

</dependency>

-> GSON api provided by google

-> In GSON api we have 'Gson' class to perform conversions

toJson ( ) -> to convert java object to JSON

fromJson ( ) -> to convert json data to java object

+++++++++++++++++++++++++++++++

How to develop REST API using Java

+++++++++++++++++++++++++++++++++

-> To develop RESFul Services/ REST APIs using java SUN Microsystem

released 'JAX-RS' API

-> JAX-RS api having 2 implementations

1) Jersey (Sun Microsystems)

2) REST Easy (JBOSS)

Note: We can develop RESTFul Services using any one of the above

implementation

-> Spring framework also provided support to develop RESTFul Services


using 'Spring Web MVC' module.

+++++++++++++++++++++++++

RESTFul Services Architecture

+++++++++++++++++++++++++

-> We will have 2 actors in RESTful services

1) Provider / Resource

2) Consumer / Client

-> The application which is providing services to other applications is

called as Provider or Resource application

-> The application which is accessing services from other applications is

called as Consumer or Client application

-> Client application and Resource application will exchange data in

intereoperable format (like XML & JSON)

request

client app <------------------------>

resource app

response

Note: RESTful Services are used to develop B2B communications (No

presentation logic, No view Resolver)

+++++++++++++++++++++++++++++++++++

Develop First REST API Using Spring Boot

+++++++++++++++++++++++++++++++++++

1) Create Spring starter application with below dependencies

a) web-starter
b) devtools

2) Create RestController with Required methods

Note: To represent java class as Rest Controller we will use

@RestController annotation

@RestController = @Controller + @ResponseBody

Note: Every RestController method should be binded to HTTP Protocol

method

Ex: @GetMapping, @PostMapping, @PutMapping & @DeleteMapping

3) Run the application and test it.

Note: To test REST APIs we will use POSTMAN tool (It is free)

Note: Download postman tool to test our REST API functionality

+++++++++++++++++++++++++++++++++++

@RestController

public class WelcomeRestController {

@GetMapping("/welcome")

public ResponseEntity<String> getWelcomeMsg() {

String respPayload = "Welcome to Jensoft";

return new ResponseEntity<>(respPayload, HttpStatus.OK);

@GetMapping("/greet")

public String getGreetMsg() {

String respPayload = "Good Morning..!!";

return respPayload;

+++++++++++++++++++++++++++++++++++
Note: GET Request will not contain Request Body to send data

-> We can use Query Params and Path Params to send data in GET Request

-> Query Params & Path Params will represent data in URL directlry

++++++++++++++

Query Params

++++++++++++++

-> Query Params are used to send data to server in URL directly

-> Query Params will represent data in key-value format

-> Query Params will start with '?'

-> Query Parameters will be seperated by '&'

-> Query Parameters should present only at the end of the URL

-> To read Query Parameters from the URL we will use @RequestParam

annotation

@GetMapping("/welcome")

public ResponseEntity<String> getWelcomeMsg(@RequestParam("name")

String name) {

String respPayload = name + ", Welcome to Jensoft";

return new ResponseEntity<>(respPayload, HttpStatus.OK);

URL : http://localhost:8080/welcome?name=Jensoft

+++++++++++++++++++++++++++++++++

Working with 2 Query Params in URL

+++++++++++++++++++++++++++++++++++

@RestController

public class CourseRestController {

@GetMapping("/course")
public ResponseEntity<String> getCourseFee(@RequestParam("cname")

String cname,

@RequestParam("tname") String tname) {

String respBody = cname + " By " + tname + " Fee is 7000 INR";

return new ResponseEntity<>(respBody, HttpStatus.OK);

URL : http://localhost:8080/course?cname=JPDT&tname=Jensoft

++++++++++++++++++++++++++++

Path Parameter or URI variables

+++++++++++++++++++++++++++++

-> Path Parameters are also used to send data to server in URL

-> Path Params will represent data directley in URL (no keys)

-> Path Params can present anywhere in the URL

-> Path Params will be seperated by / (slash)

-> Path Params should be represented in Method URL pattern (Template

Pattern)

-> To read Path Parameters we will use @PathVariable annotation

@RestController

public class BookRestController {

@GetMapping("/book/{name}")

public ResponseEntity<String> getBookPrice(@PathVariable("name")

String name) {

String respBody = name + " Price is 400 $";

return new ResponseEntity<>(respBody, HttpStatus.OK);

}
@GetMapping("/book/name/{bname}/author/{aname}")

public ResponseEntity<String> getBook(@PathVariable("bname") String

bname,

@PathVariable("aname") String aname) {

String respBody = bname + " By " + aname + " is out of stock";

return new ResponseEntity<>(respBody, HttpStatus.OK);

URL-1 : http://localhost:8080/book/spring

URL-2 : http://localhost:8080/book/name/spring/author/rodjohnson

+++++++++++++++++++++++++++++++++++++++

Q) When to use Path Params & Query Params ?

++++++++++++++++++++++++++++++++++++++++

-> To retrieve more than one record/resource we will use Query Params

(filtering)

-> To retreive specific/unique record we will use Path Params (single)

################

What is Produces

#################

-> "produces" is a media type

-> It represents the response formats supported by REST Controller Method

-> One method can support multiple response formats (xml and json)

produces = { "application/xml", "application/json" }

-> Client should send a request with "Accept" http header

-> Accept header represents in which format client expecting response


from the REST api

-> Based on Accept header value 'Message Converter' will convert the

response into client expected format

@Data

@XmlRootElement

@NoArgsConstructor

@AllArgsConstructor

public class Product {

private Integer pid;

private String pname;

private Double price;

@RestController

public class ProductRestController {

@GetMapping(

value = "/product",

produces = { "application/xml", "application/json" }

public ResponseEntity<Product> getProduct() {

Product p1 = new Product(101, "Monitor", 8000.00);

return new ResponseEntity<>(p1, HttpStatus.OK);

@GetMapping("/products")

public ResponseEntity<List<Product>> getProducts(){

Product p1 = new Product(101, "Monitor", 8000.00);


Product p2 = new Product(102, "RAM", 6000.00);

Product p3 = new Product(103, "CPU", 15000.00);

List<Product> products = Arrays.asList(p1,p2,p3);

return new ResponseEntity<>(products, HttpStatus.OK);

##############################

Working with HTTP POST Request

#############################

-> HTTP POST request is used to create new resource/record at server

-> POST request contains request body

-> Client can send data to server in Request Body

-> To bind Rest Controller method to POST request we willl use

@PostMapping

-> To read data from Requet body we will use @RequestBody annotation

-> "consumes" represents in which formats method can take input

-> "Content-Type" header represents in which format client sending data

in request body.

@Data

@XmlRootElement

public class Book {

private Integer id;

private String name;

private Double price;


}

---------------------------

@RestController

public class BookRestController {

@PostMapping(

value = "/book",

consumes = { "application/json", "application/xml" }

public ResponseEntity<String> addBook(@RequestBody Book book) {

System.out.println(book);

// logic to store in DB

String msg = "Book Added Succesfully";

return new ResponseEntity<String>(msg, HttpStatus.CREATED);

----------------

"id" : 101,

"name" : "Java",

"price" : 450.00

------------------------

-> produces vs consumes

-> Content-Type vs Accept

-> produces attribute represents in which formats Method can provide

response data to clients


-> consumes attribute represents in which formats Method can take request

data from clients

-> Accept header represents in which format client expecting response

from REST API

-> Content-Type header represents in which format client is sending

request data to REST API

Note: We can use both Consumes & Produces in single REST API method.

Develop IRCTC REST API to book a train ticket:

----------------------------------------------------------------

-> To develop any REST API first we have to understand the requirement

-> Identify input / request data

-> Identify output / response data

-> Create request & response binding classes

-> Create REST Controller with required methods.

-> Test REST API methods behaviour using Postman

@Data

public class PassengerInfo {

private String name;

private Long phno;

private String jdate;

private String from;

private String to;

private Integer trainNum;

}
@Data

public class TicketInfo {

private Integer ticketId;

private String pnr;

private String ticketStatus;

@RestController

public class TicketRestController {

@PostMapping(

value = "/ticket",

produces = {"application/json"},

consumes = {"application/json"}

public ResponseEntity<TicketInfo> bookTicket(@RequestBody

PassengerInfo request){

System.out.println(request);

//logic to book ticket

TicketInfo tinfo = new TicketInfo();

tinfo.setTicketId(1234);

tinfo.setPnr("JLJL6868");

tinfo.setTicketStatus("CONFIRMED");

return new ResponseEntity<>(tinfo, HttpStatus.CREATED);

-------------------------------

{
"name" : "Jensoft",

"phno" : 12345678,

"jdate" : "05-08-2022",

"from" : "hyd",

"to" : "pune",

"trainNum" : 8574

"ticketId": 1234,

"pnr": "JLJL6868",

"ticketStatus": "CONFIRMED"

You might also like