Restfull Services and Micro Services
Restfull Services and Micro Services
Restfull Services and Micro Services
1) Distributed Applications
2) Distributed Technologies
3) RestFull service Introduction
4) Rest Principles
5) XML
6) XSD
7) One time operation
8) Run Tine operation(a. Marshalling b. un-Marshalling)
9) JAX-B Introduction
10) JAX-B Architecture
11) Application development with JAX-B
12) JSON
13) XML VS JSON
14) JACKSON API
15) Converting Java object to JSON and Vice versa(JSON to java object)
16) GSON API
17) Converting java object to JSON and vice versa using GSON
18) HTTP Protocal Details
19) HTTP Methods(GET,POST,PUT,DELETE
20) HTTP Status codes
21) @RestController
22) @RequestBody
23) @ResponseBody
24) @RequestParam
25) @PathVariable
26) Media Types
27) Consumes(JSON data)
28) Produces(JSON Data)
29) Accept Header
30) Content-Type header
31) RestAPI Development Using Spring Boot
32) POSTMAN
33) SWAGGER & SWAGGER UI
34) Exception handling in Rest API
35) REST Security(JWT,OAuth2.0)
36) Mono Objects
37) Flux Objects
38) Rest Client Introduction
39) RestTemplate
40) WebClient
41) Synchronous and Astnchronous Calls
42) Apache Kafka in Spring Boot
43) Redis Cache Spring Boot
Micro Services:
1) Monolith Introduction
2) Monolith Architecture case study
3) Monolith Application Development Process
4) Load balancer(Cluster)case study
5) Load Balancing Algoritham(a.Round Robin, b)IP Hashing, c)Sticky Session)
6) Monolith Drawbacks
7) Micro Services Introduction
8) Micro Services Advantages
9) Micro Services Dis-Advantages
10) Micro Services Case study
11) Micro Services Architecture
12) Micro Services Development(a.API-1, b.API-2)
13) Inter service communication case study
14) Feign Client
15) Cloud Introduction.(AWS,AZURE,PCF)
16) PCF CLI Installation
17) Deploying Micro Services to PCF using CLI
18) Auto Scalling
19) Service Registry case study(Netflix Edurekha)
20) Gateway API(Zuul Proxy)
21) Hystrix(Circuit Breaker)
22) Hystrix Dashboard
23) Spring Boot Admin services.
RESTful Web Services Tutorial
RESTful Web Services are client and server applications that communicate over the WWW. RESTful Web
Services are REST Architecture based Web Services. In REST Architecture, everything is a resource. RESTful
Web Services provides communication between software applications running on different platforms and
frameworks. We can consider web services as code on demand. A RESTful Web Service is a function or
method which can be called by sending an HTTP request to a URL, and the service returns the result as the
response. In this tutorial, you will learn the basics of RSETful Web Services with suitable examples and
projects.
o It should be interoperable.
o Web services can be used to link data between two different platforms.
XML Format: XML is the popular form as request and response in web services. Consider the following XML
code:
1. <getDetail>
2. <id>DataStructureCourse</id>
3. </getDetail>
The code shows that user has requested to access the DataStrutureCourse. The other data exchange format
is JSON. JSON is supported by wide variety of platform.
JSON Format: JSON is a readable format for structuring data. It is used for transiting data between server and
web application.
1. [
2. "employee":
3. {
4. "id": 00987
5. "name": "Jack",
6. "salary": 20000,
7. }
8. ]
Now a question arises, how does the Application A know the format of Request and Response?
The answer to this question is "Service Definition." Every web service offers a service definition. Service
definition specifies the following:
o Request/ Response format: Defines the request format made by consumer and response format
made by web service.
o Service Definition
Request and Response: Request is the input to a web service, and the response is the output from a web
service.
Message Exchange Format: It is the format of the request and response. There are two popular message
exchange formats: XML and JSON.
Service Provider or Server: Service provider is one which hosts the web service.
Service Consumer or Client: Service consumer is one who is using the web service.
Service Definition: Service definition is the contract between the service provider and service consumer.
Service definition defines the format of request and response, request structure, response structure, and
endpoint.
Transport: Transport defines how a service is called. There is two popular way of calling a service: HTTP and
Message Queue (MQ). By tying the URL of service, we can call the service over the internet. MQ
communicates over the queue. The service requester puts the request in the queue. As soon as the service
provider listens to the request. It takes the request, process the request, and create a response, and put the
response back into MQ. The service requester gets the response from the queue. The communication
happens over the queue.
Characteristics of Web Services
Web services have the following characteristics:
o XML-based
o Coarse-grained
o Loosely coupled
o Capability to be synchronous and asynchronous
o Supports RPC
XML-based
A web service uses XML at information representation and record transportation layer. Using XML, there is
no need of networking, operating system, or platform binding. Web offering based application is highly
interoperable application at their middle level.
Coarse-grained
In the coarse-grained operation, a few objects hold a lot of related data. It provides broader functionality in
comparison to fine-grained service. It wraps one or more fine-grained services together into a coarse-grained
service. It is fine to have more coarse-grained service operations.
Loosely Coupled
A web service supports loosely coupled connections between systems. It communicates by passing XML
message to each other via a web API. Web API adds a layer of abstraction to the environment that makes the
connection adaptable and flexible.
Capability to be synchronous and asynchronous
Synchronous Web services are invoked over existing Web protocols by a client who waits for a response.
Synchronous Web services are served by RPC-oriented messaging.
Asynchronous Web services are invoked over existing Web protocols by a client who does not wait for a
response. The document-oriented messaging often used for asynchronous Web services. Asynchronous Web
Service is a crucial factor in enabling loosely coupled system.
Supports RPC
A web service supports RPC through offering services of its personal, equivalent to those of a traditional
aspect.
o A web service is a web resource. We can access a web service using platform-independent and
language-neutral web protocols, such as HTTP. HTTP ensures easy integration of heterogeneous
environment.
o A web service is typically registered. It can be located through a web service registry. A registry
enables service consumers to find service that matches their needs. The service consumers may be
human or other application.
o A web service provides an interface (a web API) that can be called from another program. The
application-to-application programming can be invoked from any application.
The architecture of web service interacts among three roles: service provider, service requester, and service
registry. The interaction involves the three operations: publish, find, and bind. These operations and roles
act upon the web services artifacts. The web service artifacts are the web service software module and its
description.
The service provider hosts a network-associable module (web service). It defines a service description for the
web service and publishes it to a service requestor or service registry. These service requestor uses a find
operation to retrieve the service description locally or from the service registry. It uses the service description
to bind with the service provider and invoke with the web service implementation.
The following figure illustrates the operations, roles, and their interaction.
Roles in a Web Service Architecture
There are three roles in web service architecture:
o Service Provider
o Service Requestor
o Service Registry
Service Provider
Service Requestor
Service requestor is the application that is looking for and invoking or initiating an interaction with a service.
The browser plays the requester role, driven by a consumer or a program without a user interface.
Service Registry
Service requestors find service and obtain binding information for services during development.
Publish: In the publish operation, a service description must be published so that a service requester can find
the service.
Find: In the find operation, the service requestor retrieves the service description directly. It can be involved
in two different lifecycle phases for the service requestor:
o At design, time to retrieve the service's interface description for program development.
o And, at the runtime to retrieve the service's binding and location description for invocation.
Bind: In the bind operation, the service requestor invokes or initiates an interaction with the service at
runtime using the binding details in the service description to locate, contact, and invoke the service.
o Service
o Service Registry
o Requirements Phase
o Analysis Phase
o Design Phase
o Coding Phase
o Test Phase
o Deployment Phase
Requirements Phase
The objective of the requirements phase is to understand the business requirement and translate them into
the web services requirement. The requirement analyst should do requirement elicitation (it is the practice of
researching and discovering the requirements of the system from the user, customer, and other
stakeholders). The analyst should interpret, consolidate, and communicate these requirements to the
development team. The requirements should be grouped in a centralized repository where they can be
viewed, prioritized, and mined for interactive features.
Analysis Phase
The purpose of the analysis phase is to refine and translate the web service into conceptual models by which
the technical development team can understand. It also defines the high-level structure and identifies the
web service interface contracts.
Design Phase
In this phase, the detailed design of web services is done. The designers define web service interface contract
that has been identified in the analysis phase. The defined web service interface contract identifies the
elements and the corresponding data types as well as mode of interaction between web services and client.
Coding Phase
Coding and debugging phase is quite similar to other software component-based coding and debugging
phase. The main difference lies in the creation of additional web service interface wrappers, generation of
WSDL, and client stubs.
Test Phase
In this phase, the tester performs interoperability testing between the platform and the client's program.
Testing to be conducted is to ensure that web services can bear the maximum load and stress. Other tasks
like profiling of the web service application and inspection of the SOAP message should also perform in the
test phase.
Deployment Phase
The purpose of the deployment phase is to ensure that the web service is properly deployed in the
distributed system. It executes after the testing phase. The primary task of deployer is to ensure that the web
service has been properly configured and managed. Other optional tasks like specifying and registering the
web service with a UDDI registry also done in this phase.
o Transport Protocol
o Messaging Protocol
o Description Protocol
o Discovery Protocol
(Service) Transport Protocol: The network layer is the foundation of the web service stack. It is responsible
for transporting a message between network applications. HTTP is the network protocol for internet available
web services. It also supports other network protocol such as SMTP, FTP, and BEEP (Block Extensible
Exchange Protocol).
(XML) Messaging Protocol: It is responsible for encoding message in a common XML format so that they can
understand at either end of a network connection. SOAP is the chosen XML messaging protocol because it
supports three operations: publish, find, and bind operation.
(Service) Description Protocol: It is used for describing the public interface to a specific web service. WSDL is
the standard for XML-based service description. WSDL describes the interface and mechanics of service
interaction. The description is necessary to specify the business context, quality of service, and service-to-
service relationship.
(Service) Discovery Protocol: It is a centralized service into a common registry so that network Web services
can publish their location and description. It makes it easy to discover which services are available on the
network.
The first three layers of the stack are required to provide or use any web service. The simplest stack consists
of HTTP for the network layer, SOAP protocol for the XML-based messaging, and WSDL for the service
description layer. These three-layer provides interoperability and enables web service to control the existing
internet infrastructure. It creates a low cost of entry to a global environment.
The bottom three layers of the stack identify technologies for compliance and interoperability, the next two
layer- Service Publication and Service Discovery can be implemented with a range of solutions.
It does not define the standard message exchange format. We can build REST services with both XML and
JSON. JSON is more popular format with REST. The key abstraction is a resource in REST. A resource can be
anything. It can be accessed through a Uniform Resource Identifier (URI). For example:
The resource has representations like XML, HTML, and JSON. The current state is captured by
representational resource. When we request a resource, we provide the representation of the resource. The
important methods of HTTP are:
For example, if we want to perform the following actions in the social media application, we get the
corresponding results.
SOAP: SOAP acronym for Simple Object Access Protocol. It defines the standard XML format. It also defines
the way of building web services. We use Web Service Definition Language (WSDL) to define the format
of request XML and the response XML.
XML Request
1. <Envelop xmlns=?http://schemas.xmlsoap.org/soap/envelop/?>
2. <Body>
3. <getCourseDetailRequest xmlns=?http://udemy.com/course?>
4. <id>course1</id>
5. <getCourseDetailRequest>
6. </Body>
7. </Envelop>
XML Response
1. <SOAP-ENV:Envelope xmlns:SOAP-ENV=?http://schemas.xmlsoap.org/soap/envelope/?>
2. <SOAP-ENV:Header /> <!?empty header-->
3. <SOAP-ENV:Body> <!?body begin-->
4. <ns2:getCourseDetailsResponse xmlns:ns2=?http://in28mi> <!--content of the response-->
5. <ns2:course>
6. <ns2:id>Course1</ns2:id>
7. <ns2:name>Spring<ns2:name>
8. <ns2:description>10 Steps</ns1:description>
9. </ns2:course>
10. </ns2:getCourseDetailResponse>
11. </SOAP-ENV:Body> <!?body end-->
12. </SOAP-ENV:Envelope>
Points to remember
o SOAP defines the format of request and response.
o SOAP does not pose any restriction on transport. We can either use HTTP or MQ for communication.
o In SOAP, service definition typically done using Web Service Definition Language (WSDL). WSDL
defines Endpoint, All Operations, Request Structure, and Response Structure.
The Endpoint is the connection point where HTML or ASP pages are exposed. It provides the information
needed to address the Web Service endpoint. The operations are the services that are allowed to access.
Request structure defines the structure of the request, and the response structure defines the structure of
the response.
It describes service as a collection of network endpoint, or ports. It is often used in combination with SOAP
and an XML schema to provide XML service over the distributed environment. In short, the purpose of WSDL
is similar to type-signature in a programming language.
The current version of WSDL is 2.0. Version 1.1 does not endorse by W3C.
Elements of WSDL
WSDL 1.1 WSDL Description
Term 2.0
Term
Port Endpoin It is an endpoint that defines a combination of binding and network addresses.
t
Binding Binding It specifies the interface and defines the SOAP binding style. It also defines the operations.
Operation Operati Abstract detail of an action supported by the service. It defines the SOAP actions and the way of encodi
on
Message N/A An abstract, typed definition of data to communicate. W3C has removed the message in WSDL 2.0, in w
bodies of inputs, outputs, and faults are referred directly.
Types Types It is a container for data type definition. The XML Schema language (XSD) is used for this purpose.
Universal Description, Discovery, and Integration (UDDI)
UDDI acronym for Universal Description, Discovery, and Integration. It is an XML-based registry for
businesses word wide to list themselves on the internet. It defines a set of services supporting the description
and discovery of the business, organizations, or other web service providers. The UDDI makes the services
available and the technical interfaces which may be used to access those services.
The idea behind UDDI is to discover organizations and the services that organizations offer, much like using a
telephone directory. It allows the business to list themselves by name, product, location, or the web
service they offer. A UDDI works in the following manner:
o A service provider registers each service separately with the UDDI registry.
o The consumer looks up the business and service in the UDDI registry.
o The consumer binds the service with the service provider and uses the service.
The UDDI business registry system has three directories are as follows:
o White Pages
o Yellow pages
o Green Pages
White Pages: The white pages contain basic information such as company name, address, phone
number, and other business identifiers such as tax numbers.
Yellow Pages: The yellow pages contain detailed business data organized by relevant business classification.
The version of the yellow page classifies business according to the newer NAICS (North American Industry
Classification System).
Green Pages: The green pages contain information about the company's crucial business process, such
as operating platform, supported programs, and other high-level business protocols.
SOAP acronym for Simple Object Access Protocol. REST acronym for REpresentational State Transfer.
In SOAP, the data exchange format is always XML. There is no strict data exchange format. We can use JSON, XML, etc.
XML is the most popular data exchange format in SOAP JSON is the most popular data exchange format in RESTful web services.
web services.
SOAP uses Web Service Definition Language (WSDL). REST does not have any standard definition language.
SOAP does not pose any restrictions on transport. We can RESTful services use the most popular HTTP protocol.
use either HTTP or MQ.
SOAP web services are typical to implement. RESTful services are easier to implement than SOAP.
SOAP web services use the JAX-WS API. RESTful web services use the JAX-RS API.
SOAP protocol defines too many standards. RESTful services do not emphasis on too many standards.
SOAP cannot use RESTful services because it is a protocol. RESTful service can use SOAP web services because it is an architectural
approach that can use any protocol like HTTP and SOAP.
JAXB is an acronym for Java Architecture for XML Binding. It allows java developers to map Java class to XML
representation. JAXB can be used to marshal java objects into XML and vice-versa.
Advantage of JAXB
No need to create or use a SAX or DOM parser and write callback methods.
1. Employee.java
2. applicationContext.xml
3. Client.java
download all the jar files for spring including core, web, aop, mvc, j2ee, remoting, oxm, jdbc, orm etc.
Employee.java
If defines three properties id, name and salary. We have used following annotations in this class:
1. package com.javatpoint;
2. import javax.xml.bind.annotation.XmlAttribute;
3. import javax.xml.bind.annotation.XmlElement;
4. import javax.xml.bind.annotation.XmlRootElement;
5.
6. @XmlRootElement(name="employee")
7. public class Employee {
8. private int id;
9. private String name;
10. private float salary;
11.
12. @XmlAttribute(name="id")
13. public int getId() {
14. return id;
15. }
16. public void setId(int id) {
17. this.id = id;
18. }
19. @XmlElement(name="name")
20. public String getName() {
21. return name;
22. }
23. public void setName(String name) {
24. this.name = name;
25. }
26. @XmlElement(name="salary")
27. public float getSalary() {
28. return salary;
29. }
30. public void setSalary(float salary) {
31. this.salary = salary;
32. }
33. }
applicationContext.xml
It defines a bean jaxbMarshallerBean where Employee class is bound with the OXM framework.
1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans xmlns="http://www.springframework.org/schema/beans"
3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4. xmlns:oxm="http://www.springframework.org/schema/oxm"
5. xsi:schemaLocation="http://www.springframework.org/schema/beans
6. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
7. http://www.springframework.org/schema/oxm
8. http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">
9.
10. <oxm:jaxb2-marshaller id="jaxbMarshallerBean">
11. <oxm:class-to-be-bound name="com.javatpoint.Employee"/>
12. </oxm:jaxb2-marshaller>
13.
14. </beans>
Client.java
It gets the instance of Marshaller from the applicationContext.xml file and calls the marshal method.
1. package com.javatpoint;
2. import java.io.FileWriter;
3. import java.io.IOException;
4. import javax.xml.transform.stream.StreamResult;
5. import org.springframework.context.ApplicationContext;
6. import org.springframework.context.support.ClassPathXmlApplicationContext;
7. import org.springframework.oxm.Marshaller;
8.
9. public class Client{
10. public static void main(String[] args)throws IOException{
11. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
12. Marshaller marshaller = (Marshaller)context.getBean("jaxbMarshallerBean");
13.
14. Employee employee=new Employee();
15. employee.setId(101);
16. employee.setName("Sonoo Jaiswal");
17. employee.setSalary(100000);
18.
19. marshaller.marshal(employee, new StreamResult(new FileWriter("employee.xml")));
20.
21. System.out.println("XML Created Sucessfully");
22. }
23. }
1. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2. <employee id="101">
3. <name>Sonoo Jaiswal</name>
4. <salary>100000.0</salary>
5. </employee>
JSON vs XML
A list of differences between JSON and XML are given below.
No JSON XML
.
1) JSON stands for JavaScript Object XML stands for eXtensible Markup Language.
Notation.
2) JSON is simple to read and write. XML is less simple than JSON.
5) JSON doesn't provide display XML provides the capability to display data because it is a markup language.
capabilities.
8) JSON files are more human XML files are less human readable.
readable than XML.
9) JSON supports only text and XML support many data types such as text, number, images, charts, graphs etc. Mor
number data type. transferring the format or structure of the data with actual data.
JSON Example
1. {"employees":[
2. {"name":"Vimal", "email":"vjaiswal1987@gmail.com"},
3. {"name":"Rahul", "email":"rahul12@gmail.com"},
4. {"name":"Jai", "email":"jai87@gmail.com"}
5. ]}
XML Example
1. <employees>
2. <employee>
3. <name>Vimal</name>
4. <email>vjaiswal1987@gmail.com</email>
5. </employee>
6. <employee>
7. <name>Rahul</name>
8. <email>rahul12@gmail.com</email>
9. </employee>
10. <employee>
11. <name>Jai</name>
12. <email>jai87@gmail.com</email>
13. </employee>
14. </employees>
JACKSON API:
Jackson is a simple java based library to serialize java objects to JSON and vice versa.
Features
Easy to use. - jackson API provides a high level facade to simplify commonly used use
cases.
No need to create mapping. - jackson API provides default mapping for most of the
objects to be serialized.
Performance. - jackson is quiet fast and is of low memory footprint and is suitable for
large object graphs or systems.
Clean JSON. - jackson creates a clean and compact JSON results which is easy to read.
No Dependency. - jackson library does not require any other library apart from jdk.
Open Source - jackson library is open source and is free to use.
Three ways of processing JSON
Jackson provides three alternative ways to process JSON
Streaming API - reads and writes JSON content as discrete events. JsonParser reads the
data whereas JsonGenerator writes the data. It is most powerful approach among the
three and is of lowest overhead and fastest in read/write opreations. It is Analogus to
Stax parser for XML.
Tree Model - prepares a in-memory tree representation of the JSON document.
ObjectMapper build tree of JsonNode nodes. It is most flexible approach. It is analogus
to DOM parser for XML.
Data Binding - converts JSON to and from POJO (Plain Old Java Object) using property
accessor or using annotations. It is of two type.
o Simple Data Binding - Converts JSON to and from Java Maps, Lists, Strings,
Numbers, Booleans and null objects.
o Full Data Binding - Converts JSON to and from any JAVA type.
ObjectMapper reads/writes JSON for both types of data bindings. Data Binding is most
convenient way and is analogus to JAXB parer for XML.
Example 1:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
Pojo class:
package com.madhu.Entity;
package com.madhu.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.madhu.Entity.Employee;
@RestController
public class Controller {
@GetMapping("/hello")
public String sayHello() {
return "Hello";
}
@GetMapping("/emp")
public List<Employee> getEmployeeDetails(){
ArrayList<Employee> arrayList = new ArrayList<>();
arrayList.add(new Employee(111, "madhu", 5000, "hyd"));
arrayList.add(new Employee(222, "ramesh", 6000, "hyd"));
return arrayList;
}
}
package com.madhu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
SpringApplication.run(App02Application.class, args);
Rest Architecture: