"Welcome To Ashok IT" "Spring Boot & Microservices" Topic : Rest API Development Date : 24/12/2024 (Session - 92) _____________________________________________________________________________________________________________________________ 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 Hanlder Method are allowing only XML Data Format @PostMapping(value="\", consumes={"application/xml"}) @PostMapping(value="\",consumes=MediaType.APPLICATION_XML_VALUE) 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 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 Hanlder 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) 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 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++