"Welcome To Ashok IT" "Spring Boot & Microservices" Topic : Restful Web services Date : 03/06/2025 (Session-58) _____________________________________________________________________________________________________________________________ RestFul & Microservices |-> Part-1 (Rest API Development) Part-1 (Rest API Development) ============================= 1) Distributed Applications 2) Distributed Technologies 3) Webservices and Types of Webservices |-> SOAP WebServices |-> Restful webservices 4) SOAP Architecture 5) Rest Architecture 6) Differences between SOAP & Rest 7) Use Cases on Restful WebServices 8) Understanding XML and Marshalling(Java Obj -> XML),UnMarshalling(XML -> Java Obj) 9) JAXB-API 10) Understanding JSON and Serialization(Java Obj -> JSON),DeSerialization(JSON -> Java Obj) 11) Jackson-API 12) XML (VS) JSON 13) Http Protocal 14) Http Request & Http Response Structure 15) Http Methods(GET,POST,PUT,PATCH,DELETE....) 16) Http Status Codes & Status Messages 17) Introduction To Spring with Rest. 18) Understanding & Developing Rest Controller in Rest API. 19) Request Mappings 20) Response Entity 21) Request Body and Response Body. 22) Query Parameters 23) Path Parameters 24) Consumers & Producers 25) Complex Responses 26) Rest API For File Uploading & Downloading 27) Exception Handling in Rest API 28) Swagger Documentation 29) Rest Client Development 30) Rest Client & WebClient 31) Security 32) POSTMAN etc., ********************************** Rest API Development Completed********************************** Types of Applications in Java ============================== * Java is an Programming language we can developed several Kinds of Applications 1) Standalone Applications 2) Web Applications 3) Distributed Applications 1) Standalone Applications ========================== * The Applications which are specific to one and only one machine such applications called as "Standalone Applications". Examples: Notepad,Notepad++,Firefox,chrome,SQLDeveloper,Eclipse IDE etc., * J2SE Libraries (or) JSE Libraries(Thread API,CollectionAPI,IOStreams API,ExceptionHandling API,JDBC API,RMI API) 2) Web Applications =================== * The Application which can be available through out globe such applications called as "Web Application". * Web Application follow Model called "Client-Server Architectural Model". In this model Client always be fixed as "Browser". * Web Applications are always deals with "Customer to Business Communication". Examples: flipkart.com,amazon.com.naukri.com,facebook.com,gmail.com.Irctc,ashokit etc., * J2EE Libraries (or) JEE Libraries (or) Jakarta Libraries(Servlet API,JSP API) 3) Distributed Applications =========================== * If One Application is communicating with another Application then they are called as "Distributed Application". * Distributed Application are always deals with "Business-to-Business" Communication. Example :::::: Filpkart Website(Consumer) <------------------> Payment Gateway(Payment Services)(Producer) AshokIT Portal(Consumer) <------------------> Payment Gateway(Razor Pay)(Producer) AshokIT Portal(Consumer) <------------------> Weather Application(producer) IncomeTax Portal(Consumer) <------------------> Aadhar Application(Producer) * J2EE Libraries,JEE Libararies,Jakarta Libraries(RMI,EJB,WebServices) * RMI and EJB are Completed Outdated in Market and Majorly we are using WebServices for developing Distributed Applications. * WebServices is an Concept and we do have two models (SOAP WebServices,RestFul WebServices) * WebServices are used for establishing Communication between two Applications. * WebServices is platform independent and architecture Independent and Language Independent. WebServices =========== * Webservices is an concept of establishing the interoperable communication from one application to another application. * Interoperable communication means irrespective of programming language (or) irrepecitve of Architecture (or) irrespective of operating system communication will takes place between two applications. * In webservices world definetly we required two systems 1) The Application whose providing the services to another application called "Producer Application". 2) The Application whose consuming the services from provider application called "Consumer Application". * Producer application can be developed in "Java" can be consumed by .net/Java/Python,PHP Application and even viceversa also possible. Java Application <-----------------------------> .Net Application .Net Application <------------------------------> Java Application Java Application <------------------------------> Python Application Python Application<---------------------------> Java/.Net Application Example ======= Filpkart.com(Consumer Application) <--------------------------------> Payment Gateway(Producer Application) * Generally we do have two models in Webservices world 1) SOAP WebServices 2) Restful WebServices 1) SOAP WebServices =================== * SOAP Stands for Simple Object Access Protocal. * In Soap Webservices basically "Soap Messages" are transferred as part of request body through Http protocal. * Soap Message is strictly typed or complex XML messages which will be converted from XML content into Java Object and from Java Object into XML Content using "JAX-B" API. * The Process of Converting Java Object into XML Content called "Marshalling" and reverse process called as "Un-Marshalling". Example ======= Customer c = new Customer(); c.setCustomerId(123); 123 c.setCustomerName("Mahesh"); => Mahesh c.setCustomerLocation("Hyderabad"); <= Hyderabad * Basically in Soap based webservices we do have mainly three components 1) Service Provider (Producer Application) 2) Service Consumer(Consumer Application) 3) Service Registry(Soap Webservices to be registered) * Every Soap Web service is to be registered in Service Registry and Service Provider will maintain services related information in one xml document i.e.,WSDL(Web Services Descriptor Language File) Document it contains multiple details Service Class name,Service methods,parameters of method ,request modes etc., * We do have multiple API's for developing SOAP Webservices 1) JAX-RPC(Remote Procedure Call)is the first foremost API released by sun micro system for developing and deploying webservices in Java. 2) JAX-WS is an Other API as part of JSE Module which can be Used for developing SOAP based Webservices(Apache Axis,Apache CXF etc.,) ************************************************** Example Diagram on Soap Webservices Architecture ************************************************** Limitations of SOAP Webservices =============================== 1) Here we need to maintain the Service Registry is required for publishing and finding the webservices and its very heavy to maintain. 2) SOAP Messages in http request and http response are complex to build and heavy to send over the network because always SOAP Messages are formed in the XML format only. 3) As programmer we need to go through WSDL document to understand about webservice information. 4) Constructing the SOAP Messages are complex by the programmer. Restful Webservices =================== * Rest stands for "Representational State Transfer". * Rest is not protocal it is an architectural style of developing the Webservices and the author of Http protocal "Roy Fielding" provided some certain rules and guidelines for Restful webservices. * In Restful Webservices as well request and response of Producer & consumer Application will transfer through Http protocal. * Restful WebServices allows to send data in both global formats such as "XML & JSON" and it always recommended for sending data as "JSON" Format. * Converting Java Object into XML Content >>>>>>>>>>>>>>> Marshalling Converting XML Content into Java Object >>>>>>>>>>>>>>> Unmarshalling Marhsalling & Un-Marshalling can be performed with help of "JAX-B API". Converting Java Object into JSON >>>>>>>>>>>>>>> Serialization Converting JSON into Java Object >>>>>>>>>>>>>>> De-Serialization Serialization & De-Serialization can be performed with help of "JACKSON API" (or) "GSON API". * Inorder to develop the Restful webservices we have below options 1) JAX-RS Specifications provided by Sun microsystem and having some implementations "Jersey(Formely(GlassFish) and currently moved to Eclipse Foundation)" & "Rest Easy(JBOSS/RedHat)".(Traditional approach) 2) By Using Spring Rest Module For Developing the Restful Webservices.(Modern Approach) * In this kind of Webservices the provider application will expose their services using WADL(Web Application Description Language) Documentation or Swagger Documentation to get more information related Rest Services. REST >>>>>>>>>>> It is standard for developing RestAPI's RestFul >>>>>>>>>>> Creating API based on Rest. * Following are the below Rest Design Principles 1) Everything is to be Resource in Rest API's Ex: EmployeeResource,LoginResource,RegistrationResource,CustomerResource etc., 2) Each Resource in the Rest API's are identified by Unique URI. 3) Use the Standard Http Request Methods i.e.,Get,Post,Put,Patch,Delete. GET >>>>>> Getting the data from server >>>>> @GetMapping POST >>>>>> Sending data to server >>>>> @PostMapping PUT >>>>>> Updating data to server for completely >>>>> @PutMapping Example : Customer contains 5 properties we are trying to update only for 2 fields We need to pass the 5 fields to update the resources. PATCH >>>>>> Updating data to server for Partially >>>>> @PatchMapping Example : Customer contains 5 properties we are trying to update only for 2 fields We need to pass the 2 fields to update the resources. DELETE >>>>>> Deleting data from server >>>>> @DeleteMapping @RequestMapping(value="url pattern", method=RequestMethod.GET/POST/PUT/PATCH/DELETE) >>>>> up to spring 4.x 4) Allow Multiple Representations for same Resource 5) Communication should be always Stateless. |-> By default Http protocal is stateless protocal means that every request in webapplication (or) rest apis should be independent. |-> Http Protocal doesn't remember the previous requests related information. |-> If we want Http Protocal becomes as Stateful we need to apply "Session Tracking" mechanism. Differences between SOAP Vs Rest ================================ Soap Webservices ================ 1) It is traditional approach for developing Webservices. 2) To develop this kind of webservice required JAX-WS Library. 3) The Implementation for this library are Apache Axis,Apache CXF etc., 4) SOAP Messages are transferred over Http Protocal 5) Service Registry is required for storing webservices related information 6) Services Information will be provided through WSDL Documentation. Restful Webservices =================== 1) It is modern approach for developing webservices. 2) To develop this kind of webservice required JAX-RS Libary/Spring Rest. 3) The Implementation for this library are SpringRest,RestEasy,Jersery etc. 4) JSON Data will transfer over Http Protocal. 5) Here no Registry is required. 6) Services Information will be provided through WADL/Swagger Documentation. XML === * XML Stands for "Extensible Markup Language". * XML governed by W3C. * The intial version of XML is 1.0 & Current version of XML is also 1.0. * XML is used to store & Transfer the data. * XML is an Interoperable(Platform Independent,Language Independent). * Every XML tag should have opening & Corresponding closing tag mandatorly. * We can validate the XML document simply by opening in browser window and If we are able to see the xml content as tree structure in browser indicates "Valid XML" otherwise "Not a Valid XML". * Every XML Contains only one element. * In XML we can have below types of elements 1) Simple element 2) Compound element * If the element contains data then it is called "Simple Element" Example ======= 101 Mahesh * If the XML element contains child XMl elements then it is called "Compound Element" Example =======
mahesh mahesh.ashokit@gmail.com
* In order to convert the Java Object into XML content (or) XML content into Java Object as Java Programmer we need to apply "Marshalling & Un-Marshalling" * Converting from Java Object into XML Content called "Marshalling". * Converting from XML Content into Java Object called "Un-Marshalling". * To Perform the Marshalling & Unmarshalling we need to use library "JAXB API" (Jakarta XML Binding). * Using JAXB API we will perform two kinds of operations 1) One Time Operation 2) Run Time Operation One Time Operation ================== * The Process of creating binding classes is called One time operation. * The Java Class which is representing XML structure is called Binding Class. Run Time Operation ================== * Performing the Marshalling & Un-Marshalling Operations. Examples ======== Customer c = new Customer(); XML c.setId(123); >>>>>>>> 123 c.setName("Mahesh"); Mahesh c.setLocation("Hyderabad"); Hyderabad Maven dependencies for XML API =============================== jakarta.xml.bind jakarta.xml.bind-api 4.0.0 com.sun.xml.bind jaxb-impl 4.0.1 runtime Example Application =================== Customer.java ============= package com.ashokit; import java.util.List; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlElementWrapper; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlType; @XmlRootElement //root element to be represent in xml file @XmlAccessorType(XmlAccessType.FIELD) //performing the marshalling process at field level @XmlType(propOrder = {"name","id","location","order"}) //marhsalling ordering public class Customer { @XmlElement(name="customerId")//property name in marshalling process private Integer id; @XmlElement(name="customerName")//property name in marshalling process private String name; @XmlElement(name="customerLocation")//property name in marshalling process private String location; @XmlElementWrapper(name = "customerOrdersList") //wrapping orders into ordersList @XmlElement(name="customerOrder")//property name in marshalling process private List order; public Customer() { } public Customer(Integer id, String name, String location,List order) { super(); this.id = id; this.name = name; this.location = location; this.order = order; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public void setOrder(List order) { this.order = order; } public List getOrder() { return order; } @Override public String toString() { return "Customer [id=" + id + ", name=" + name + ", location=" + location + "]"; } } Order.java ========== package com.ashokit; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Order { @XmlElement(name="customerOrderId") private Integer orderId; @XmlElement(name="customerBillAmount") private double billAmount; public Order() { } public Integer getOrderId() { return orderId; } public void setOrderId(Integer orderId) { this.orderId = orderId; } public double getBillAmount() { return billAmount; } public void setBillAmount(double billAmount) { this.billAmount = billAmount; } public Order(Integer orderId, double billAmount) { super(); this.orderId = orderId; this.billAmount = billAmount; } } XmlClient.java ============== package com.ashokit; import java.util.Arrays; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.Marshaller; public class XmlClient { public static void main(String[] args) throws JAXBException { Order order = new Order(345,2500); Order order1 = new Order(645,3500); //Java Object is ready having data Customer c = new Customer(123,"Mahesh","Hyderabad",Arrays.asList(order,order1)); //Create object for JaxbContent JAXBContext context = JAXBContext.newInstance(Customer.class); //perform the marshalling Marshaller mar = context.createMarshaller(); //formatting purpose mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); mar.marshal(c, System.out); } } NOTE ==== 1) @XmlRootElement - It is particularly useful when you have a Java class that represents the entire XML document, and you want to specify it as the root element. 2) @XmlAccessorType - It is a Java annotation used in Java Architecture for XML Binding (JAXB) to specify how fields and properties of a Java class should be accessed and processed when performing XML marshaling and unmarshaling. * JAXB provides two main options for the XmlAccessType parameter of @XmlAccessorType: FIELD and PROPERTY. @XmlAccessorType(XmlAccessType.FIELD)- When you annotate a class with @XmlAccessorType(XmlAccessType.FIELD), JAXB will map fields directly to XML elements. This means that only fields marked with JAXB annotations will be considered for XML mapping, and property access methods (getters and setters) will be ignored. In this case, the name field will be mapped to an XML element directly, and the getter and setter methods for name will not be used for XML binding. @XmlAccessorType(XmlAccessType.PROPERTY)- JAXB will map the properties of the class (i.e., getter and setter methods) to XML elements. Fields can still be annotated with JAXB annotations to customize the XML mapping, but they are not required. In this case, the getName and setName methods are used for XML mapping, and the @XmlElement annotation on the getName method specifies that the name property should be mapped to an XML element. 3) @XmlElement - It is a Java annotation used in Java Architecture for XML Binding (JAXB) to customize the mapping of a field or property of a Java class to an XML element when marshaling (converting from Java objects to XML) and unmarshaling (converting from XML to Java objects) XML data. 4) @XmlElementWrapper - It is often used to wrap collections (e.g., lists, arrays, sets) of elements within a containing XML element. This can be useful when you want to represent a list of items as a child element within another XML element. This annotation allows you to specify the name, namespace, and other properties of the XML element that corresponds to the annotated field or property. Example ======= public class Book { private String title; private String author; private double price; // Constructors, getters, and setters @XmlElement(name = "bookTitle") public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @XmlElement(namespace = "http://ashokit.com/books") public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } @XmlElement public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } } pom.xml ======= 4.0.0 com.ashokit 43_Java_To_XML_Examples 0.0.1-SNAPSHOT 1.8 1.8 jakarta.xml.bind jakarta.xml.bind-api 4.0.0 com.sun.xml.bind jaxb-impl 4.0.1 runtime OUTPUT ====== Mahesh 123 Hyderabad 345 2500.0 645 3500.0 UnMarhshallingClient.java ========================= package com.ashokit; import java.io.File; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.Unmarshaller; public class UnMarhshallingClient { public static void main(String[] args) throws JAXBException { //create JaxBContext object JAXBContext context = JAXBContext.newInstance(Customer.class); //Creating Unmarshaller Object Unmarshaller unmarshaller = context.createUnmarshaller(); Customer customer =(Customer)unmarshaller.unmarshal(new File("customer.xml")); //Displaying the customer information System.out.println("Customer::::" + customer); } } OUTPUT ====== Customer::::Customer [id=123, name=Mahesh, location=Hyderabad, order=[Order [orderId=345, billAmount=2500.0], Order [orderId=645, billAmount=3500.0]]] ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++