"Welcome To Ashok IT" "Spring Boot & Microservices" Topic : Rest API Development Date : 26/12/2024 (Session - 93) _____________________________________________________________________________________________________________________________ Post Request in Rest API Development ==================================== * Post Request is used for posting/sending data to server and for every Post Request always we do have "Request Body". * In Spring MVC/Spring Boot MVC Concepts we are able to send the data to Server through Html Form page/JSP page/Thymeleaf Page. * In REST API Development of an Post Request always using RequestBody Section for sending Data from Consumer Application to Producer Application. * In order to map the Request Handler Method of an Post Request we need to use the @PostMapping Annotation. * In Post Request Handler Method to Accept the Data either XML (or) JSON and convert into Java Object we need to use another annotation i.e.,@RequestBody Request Body (raw >>> JSON) Producer Application =========================== ===================== { @PostMapping(value="/create") "customerId" : 123456, public ResponseEntity createRecord(@RequestBody Customer customer){ "customerName" :"Mahesh", >>>> ------------------------------- "customerLocation":"Hyderabad" } } NOTE ==== * Post Request Can't be tested through Browser Window always it should be tested through PostMan Tool. Application =========== package com.ashokit.controller; import java.util.List; import java.util.Optional; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.ashokit.dto.Customer; import com.ashokit.util.CustomerUtils; @RestController @RequestMapping(value = "/customers") public class CustomerController { @GetMapping(value="/") public ResponseEntity> getAllCustomers(){ List customers = CustomerUtils.getAllCustomers(); return new ResponseEntity>(customers,HttpStatus.OK); } @GetMapping(value="/{customerId}") public ResponseEntity getCustomerDetailsById(@PathVariable("customerId") Integer customerId){ Customer customerDetails = CustomerUtils.getCustomerDetailsById(customerId); return new ResponseEntity(customerDetails,HttpStatus.OK); } @PostMapping(value="/",consumes = {"application/json","application/xml"}) //@PostMapping(value="/",consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) public ResponseEntity createNewCustomer(@RequestBody Customer customer){ System.out.println("Customer Object:::::" + customer); Optional custOpt = Optional.of(customer); int customerId=0; if(custOpt.isPresent()) { customerId = customer.getCustomerId(); } return new ResponseEntity(customerId+" Record Created Successfully",HttpStatus.CREATED); } } Execution For Testing POST Request API ====================================== 1) We need to open the POST Man in our Machine. 2) Select our API Collection in left side navigation and clicke on "three dots" button and select "Add Request" Option. 3) Select Request types from Dropdown "POST" and specify the API URL in int address bar as below http ://localhost:8787/customers/ 4) Select "Request Body" option and Again we need to select "raw" option and again select "JSON" option from dropdown and find below sample Request body for testing POST Request API { "customerName":"Mahesh", "customerLocation":"Hyderabad" } 5) Finally click on "Send" but to Hit our request of Our API. 6) If we want to test our POST Request API with XML Request body we need select Request Body >>>> raw option >>>> XML Option AIT1232323 Test Hyderabad NOTE ==== * By default every handler method in Rest Controller class will accept only JSON data and will return as JSON only. * When we wanted to accept xml data or returning xml data from Rest API then definetly need to add the below dependency in pom.xml file com.fasterxml.jackson.dataformat jackson-dataformat-xml NOTE ==== * Here Serialization will be taken care by @RequestBody Annotation and we no need to perform explictly(JSON To Java Object). 400 >>>>>>>>>>>> Bad Request (When you forgot to send Request body for Post Request) 404 >>>>>>>>>>>> Resource Not Found(When you made mistake in Request URL) 415 >>>>>>>>>>>> Unsupported MediaType Error (Request Handler method only accepting JSON data but client sending xml data) Consumes Attribute ================== * It Representing the Input Format allowing by Request Handler Method/Resource Handler Method. * If your Request Handler Method are allowing only JSON Data Format @PostMapping(value ="\", consumes ={"application/json"}) >>>> application/json (MEDIATYPE For JSON DATA) @PostMapping(value="\",consumes= MediaType.APPLICATION_JSON_VALUE) * Suppose If the client is sending Data through Request body in xml format and our request handler method is allowing JSON data format only in this case data format will be mismatched and get error as "415(UnsupportedMediaType)". * If your Request Handler Method are allowing only XML Data Format @PostMapping(value="\", consumes={"application/xml"}) @PostMapping(value="\",consumes=MediaType.APPLICATION_XML_VALUE) Produces ======== * It Represents the Output Format suppported by the Resource Method/Request Handler Method. * If your Resource Handler Method sending back the JSON as Output then we need to use below annotation @PostMapping(value="\",produces ={"application/json"} consumes={"application/json"}) >>>> Input (JSON),Output(JSON) * If your Resource Handler method sending back the XML as outuput then we need to use below annotation @PostMapping(value="\",produces={"application/xml"},consumes={"application/xml"}) >>>>> Input (XML),Output(XML) * If your Resource Handler method sending as JSON as ouput but input receiving as XML we need to use below annotation @PostMapping(value="\",produces={"application/json"},consumes={"application/xml"}) >>>>> Input (XML),Output(JSON) * If your Resource Handler method sending as XML as ouput but input receiving as JSON we need to use below annotation @PostMapping(value="\",produces={"application/xml"},consumes={"application/json"}) >>>>> Input (JSON),Output(XML) ContentType =========== * ContentType is one of Implict Request Header in Request. * ContentType header represents Client Sending Data Format. * For this Header automatically POSTMAN Tool will pick value of MEDIATYPE based data available in Request Body. Request Body(JSON) >>>>>>>>>>>>>> content-type(application/json) >>>>> automatically Request Body(XML) >>>>>>>>>>>>>> content-type(application/xml) >>>>> automatically Accept ====== * It representing the Client Expected Response format from Resource Handler method. * By default this header in POSTMAN tool as "Accept:*/*" (Post Man Can process any type of data). * If you want this customize simple disable the POSTMAN Given header by clicking on checkbox and add new entry for same header key(Accept) : (application/json (or) application/xml) NOTE ==== * If input formats are got mismatched(Client-> xml , Producer -> JSON) >>>>>>>>>>>>> 415 UnSupported Media Type * If output formats are got mismatched(Client -> JSON, Producer -> XML) >>>>>>>>>>>>> 406 Not Acceptable Lombok ====== * Lombok is a popular Java library that provides a set of annotations and code generation tools to help simplify and streamline Java code. * It is designed to reduce boilerplate code, enhance code readability, and make Java development more concise and efficient. * The importance of Lombok can be understood through several key points 1.Reduces Boilerplate Code ========================== * Lombok eliminates the need to write repetitive and verbose code, such as getters, setters, constructors, and toString methods. This simplifies the codebase and makes it more maintainable. 2.Improves Code Readability =========================== * By reducing the clutter of boilerplate code, Lombok can make your code more concise and easier to read. This can lead to better code comprehension and faster development. 3.Saves Development Time ======================== * Lombok automates the generation of common code patterns, which saves developers time and effort. This is especially valuable in large and complex codebases where manually writing repetitive code can be error-prone and time-consuming. 4.Minimizes Errors: =================== * Since Lombok-generated code is automatically generated and updated, it reduces the risk of human error in writing and maintaining common code patterns. 5.Enhances Code Maintainability =============================== * Lombok encourages the use of immutable objects and other best practices, which can lead to more maintainable and bug- resistant code. 6.Integrates with IDEs: ======================= * Lombok seamlessly integrates with popular Java IDEs like IntelliJ IDEA and Eclipse, providing code assistance and tooling support, such as code completion and refactoring. NOTE ==== * Lombok is important in Java development because it helps developers write cleaner, more readable, and less error-prone code while saving time and effort. * Its ability to reduce boilerplate code and integrate with popular IDEs makes it a valuable tool for Java developers looking to improve their productivity and code quality. Configuring the Lombok ====================== Process-1 ========= 1) Download the Lombok.jar file from lombok.org website with below link https://projectlombok.org/download 2) After downloading the Jar File,Simply double click on it will get Installer window Select Appropriate IDE'S to install/configure lombok Library by checking checkboxes Click on Install/Update button it will install automatically Finally click on "Quit installer" Button. 3) After completion of installation to ensure Lombok configure correctly or not in our IDE Goto Help Menu >>>> About STSIDE/Eclipse IDE >>>> Find lombok entry after copyrights message. Process-2 ========= 1) Goto STS IDE Select Help Menu >>>> Install New Software >>> Click on Add Button and fill the below Details Name ::: Lombok API Location::: https://projectlombok.org/p2 Finally Click "Ok" Button 2) Select Entry from dropdown "Lombok API" and click button "Install" >>>> Accept the Licences >>> Click On Finish Button Lombok Annotations ================== 1. @Getter 2. @Setter 3. @NoArgsConstructor 4. @AllArgsConstructor 5. @ToString 6. @Builder 7. @EqualsAndHashCode 8. @Data = @Getter + @Setter + @NoArgsConstructor + @EqualsAndHashCode + @ToString NOTE ==== * After Installaing the Lombok to IDE make sure we need add lombok dependencies to our projects. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++