[go: up one dir, main page]

0% found this document useful (0 votes)
24 views131 pages

REST API USING SPRING

The document explains the concept of web services, emphasizing their role in enabling communication between applications on different platforms. It details the types of web services, specifically RESTful and SOAP, and outlines REST principles such as statelessness and resource representation. Additionally, it introduces the Richardson Maturity Model for categorizing REST services and provides insights into developing REST APIs using Spring Boot.

Uploaded by

Appana Rajesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
24 views131 pages

REST API USING SPRING

The document explains the concept of web services, emphasizing their role in enabling communication between applications on different platforms. It details the types of web services, specifically RESTful and SOAP, and outlines REST principles such as statelessness and resource representation. Additionally, it introduces the Richardson Maturity Model for categorizing REST services and provides insights into developing REST APIs using Spring Boot.

Uploaded by

Appana Rajesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 131
| 38.1KB/s © ull B ray @ lex.infosysapps.com $= 6 Page _1 of + Why Wedserces? Many a times, you would want to use an already existing functionality of an application into other ‘applications running on a different platforms and devices, For example, applications running on different platform can interact with Google Maps to provide lacation services. Google Maps for every platform e ° @ ° ‘Similarly, users of Instagram, a photo sharing application, can share photographs not only with Instagram friends but also with friends on other social networking applications such as Twitter and Facebook, ESO Have you ever wandered how allthis is possible? How application running on different platforms using different technologies can communicate with each other? All these are achieved using Web Services, So, lets learn what is a web service. Note: All trademarks belong to ther respective owners. CT 10.0KB/s © ray @ lex.infosysapps.com $+ 6 Pape 2 oft + Whats en Seniean Web service is a standard way of communication between web applications running on diverse platforms and frameworks. In our scenario, Google Map is expased as web service and consumed by different applications running on different devices. Web services are usualy enclosed in the Web ‘AP| layer of API layer, which communicates directly with the service layer. The Web Service layer provides the logic to convert software objects into aifferent representations that can be sent to destination applications. == = — = \When an application is developed as a web service following are the benefits: «+ Integrates with other systems easily + Creates reusable components, > + Cost savings q «Application bult using different technologies can interact with each other, for example a Java based! ‘application can send data to a.NET application, [As web services provides way for communication between web application let us understand some concepts of web applications. 9:51 PM 0.2KB/s © ull ray @ lex.infosysapps.com el 20+ 4 Page 3. of4 > Sometemincoges Web Client ‘A web client is a software using which you can interact with the server where the web application is hosted. The most commonly used web clients are web browsers such as Google Chrome, Mozilla Firefox, Internet Explorer, et, Web Server ‘A web server is a software where the web application is hosted. It processes the request received from the client and sends the response back tothe client. It runs an some physical system and listens to client request ona specific port. Apache Tomcat is one of the most widely used web server Uniform Resource Locator (URL) URL stands for Universal Resource Locator. It used by the web client to locate the web server and resource. Every resource on the web has its own unique URL. The following is an example of URL; hntpyinfy.com 8080/InfyBank/jsps/welcome|sp itp ~ itis the communication protocol used for server-lient communication infycom ~ It isthe hostname ofthe server that maps to a unique IP address. ‘8080 ~ This is the port on which server is listening. tis optional and if not provided request will goto the default port of the protocol Hypertext Transfer Protocol (HTTP) It is a protocal of communication between client and server. A client sends an HTTP request for a resource and the server returns an HTTP response withthe desired resource. The HTTP request contains information about the action that the client is requesting the server to perform. This information is ‘mentioned in HTTP request as the following methods: Pee Description ‘Add an existing resource toa server “Transfers 2 resource to the server and overwrites fer the existing resource DELETE delete | discards resources GET method ‘The HTTP GET method is used to retrieve a resource. It means, ‘get the resource identified by this URL* If parameters have to be passed along with GET request then they are passed by appending @ query string to the URL. For example, the following is a URL for passing tom as a username: |ntp/nfy.com 8080/InfyBank?username=Tom In above URL the part after the question mark is called @ query string It consists of parameter name and value pairs separated by an ampersand (8). In HTTP GET request the form data gets appended to the URL which will be visible to the user POST method 'APOST request s used to send data to the server in order to be processed. It means,post the data to the resource identified by this URL. The data s sent as a body of the message. ‘An HTTP message sent by a server to @ client is called an HTTP response. The inital ne of an HTTP response is called the status line. It has three parts, separated by spaces: the HTTP version, a response status code that tells the result of the request, and an English phrase describing the stalus code. Some Important response codes are as follows: ya 92.8KB/s © ray @ lex.infosysapps.com el In above URL, the part after the question mark is called a query tring It consists of parameter name and value pairs separated by an ampersand (8). In HTTP GET request the form data gets appended to the URL which will be visible to the user POST method 'APOST request s used to send data to the server in order to be processed. It means,post the data to the resource identified by this URL. The data s sent as a body of the message. ‘An HTTP message sent by a server to a client is called an HTTP response. The initial ine of an HTTP response is called the status line. It has three parts, separated by spaces: the HTTP version, a response status code that tells the result of the request, and an English phrase describing the status code, Some Important response codes are as follows: rere ea 200 - OK “The request Is succeeded 208 ~ No Content ‘Document contains no data 301 ~ Moved Permanently | The resources have been moved permanently to other URL 401 - Not Authorized | The request stil needs user authentication 403 ~ Forbidden “The server has refused to fulfil the request 404 - Not Found “The requested resource does not exston the server 408 - Request Timeout | The cllent has faledto send requestn the time allowed by the server 500 - Server ror Bue to malfunctioning spt, server configuration erors are similar Web Container ‘components gets executed to generate content based on client request. So they need ar environment for their execution. This execution environment is called as a web container. Web server takes the help of web container for generating dynamic content. Some commonly used web containers > ‘Web applications are composed of web components such as servlets, Java Server Page (JSP). These, + Apache Tomeat + GlassFish Jetty Application Server ‘A web apolication resides in an application server. The application server provides the web application with easy and managed access tothe resources ofthe system. I also provides low-level services, such as the HTTP protocol implementation and database connection management, A web container is just a patt of an application server. Discussion Forum, TN) thomasNe Fag ns 22 ‘ha abou UR a have seni ere ut coun pace when eed WS) espondtothstheod MS Mohammed Shoal Shak FD Fag ns 2022 Lntis norm resource lotro universal? n@agatuiconmiion. 9:52 PM 4.4KB/s © ull ray @ lex.infosysapps.com p> 4 Page _4 ols yperotensentes ‘Web Services are of two types: RESTful Web Services RESTful web services are based on REST principles. As per REST principle everything is a resource. ‘SOAP based Web Services SOAP based web services are services that are descrived, discovered and accessed using standards recommended by W3C (not covered as part ofthis course) In this course, you willbe learning about RESTful Web Services. ya 14.2KB/s © @ ray @ lex.infosysapps.com What is REST? REST stands for REpresentational State Transfer. This term was coined by Roy Fielding in his doctoral dissertation in 2000. t specifies a set of architectural principles for web which uses HTTP protocol for ‘communication REST Principles ‘The following figure shows five important REST principles: = CT 7] Co ices Le Nie Uniform Interface In REST anything that can be accessed or manipulated is a resource. For example, customer’, "order, "Dog all are resources. Every resource has a representation (XML/JSON) and are uniquely identified by 2 Uniform Resource Identifier (URI). Resources are manipulated using GET, POST, PUT and DELETE ‘methods of HTTP to perform read, create, update and delete of the resource. You can perform different ‘operation on resources using different HTTP methods but with same URI. Example : fa customer is a resource, then customer details can be added, deleted, updated or retrieved. {a blag is another resource, then the operations we can perform on the blog can be create a blog, read @ blog, update blog or delete a blog Stateless ‘The communication between service consumer (client) and service provider(server) must be stateless between requests. Stateless requires each request from a service consumer to contain all the necessary information for the service to understand the meaning of the request and all session state data should then be retumed tothe service consumer atthe end of each request. ‘Advantage: Statelessness ensures that each service consumer request can be treated independently by the serviee. Client Server Client-Server enforces the separation of concerns in the form of a client-server architecture, this helps establish a distributed architecture. This is the most foundational constraint cach Service consumers can cache and reuse response message data. HTTP GET, PUT and DELETE operations are cacheable. RESTTUul Web Services use HTTP protocol as a cartier for the data, they can se the metadata available in HTTP headers to enable caching. For example: Cache-Control headers are sed to optimize caching for enhancing performance. Layered system REST based solution can comprise of multiple architectural layers. This constraint builds on client-server here in we add middleware component(s). Consumer may be communicating with a service residing in ‘a middleware layer or the actual provider. A service does nat need to be aware of whether its consumer is further communicating with other services or acting 2s a provider for another consumer, What is RESTful Web Service? Any web service which satisfies REST principles is called REST(ul web service. These web services are Lsually exposed 0 thiréparty applications as application prograrnming interface (AP). Popular sites such as Facebook, Twitter, and Linkedin offer REST web services for accessing stored data Pye) 30.4KB/s © @.utl ray @ lex.infosysapps.com 4 Page 2 of» Resta arices REST Resources In REST everything is a Resource (data/functionalty/web page) and is uniquely identified by @ Uniform Resource Identifier (URD, The following table shows examples of URIs and the aifferent resources they represent Nd nbancconvestoners Represents calection of stone sous it nbarkconvestonen Ti Represents store resource ierified wi stoner iT tp fnibekconvetomer/7 REST URI Templates Represent sess of tomer eau ented wth When creating REST APIS, you need to represent the structure of a URI rather than the URI itself. For example, in InfyBank application, the URI httpy/infyeank.com/custorners/2001 would fetch details of the customer whose id 's 2001. Simitary, the URI hitpz/infybank com/customers/2002 would fetch details of the customer whose id is 2002. In this scenario structure of URI is important. URI templates provides a standard way for describing structure of URI. The URI template for this scenario could be: ‘The curly braces () indicate that the customerid part of the template is @ variable, often called as fa path variable. The clients consuming the web service can take thsi URI template as input, retrieve the value of path variable, and use ito retrieve the corresponding customer details, Pye) 2.5KB/s © ull & ray @ lex.infosysapps.com p> 4 Page _aof4 y Resthawedserces Representation Resources can be represented in many ways le: JSON/ XML/ HTML or any other type Inthe above example of http /wwwinty.com/emplayees/john, suppose you rake a request with the URL Using HTTP GET, the server may send back a JSON data having employee Johns information as below: Orit can also be represented as XML as below: ‘This means the server can represent the resource in many ways, ‘What does State Transfer mean? e asking for the current “state” of this resource or its desired ‘state’. You can use the same URI tof ae you make a request toa resource like hitp:/wivinfyconvemployees/jonn using HTTP we mq indicate tha, we want to Retrieve tne current value of an Employee John (current state) Perform Update operation on employee Johns data (desired state) etc ‘The server will understand which operation has to be invoked based on the HTTP method that was used to make a call. In short it means that a client and server exchange, representation of a resource, which reflects its current state(GET) or its desired state(PUT), In next module, ou will learn how to create RESTIul web services using Spring 9:52 PM 8.4KB/s © Bull ray @ lex.infosysapps.com > 4 Page_4 off + Retarson Maury Mosel Richardson Maturity Model (RMM) ‘The Richardsorts Maturity Models used to divide REST based web services in different categories based ‘on how much they follow REST principles. It was developed by Leonard Richardson, It has following levels: evel? Levelo This is the basic level for a REST based web service. In this level single URI is used to expose the entire {AP| Ituses a single HTTP method (Iypically POST or GET) to make remote procedure call on a single URI to perform operation on resources, SOAP based and XML RPC based web services comes in this level Level ‘The services in this level have multiple URIs for every resource but uses only one HTTP method — generally POST ~ to perform all the operations. Sinoe specific resource is identified by @ unique URI a inthis level are closer to REST principles than services in level zero. q Level 2 ‘The services in this level uses HTTP protocol and its methods end status codes along with URIs to perform all the operations, For example, to get the employees, we send a GET request with the URI ‘employees, and the server sends proper response 200 OK and to add a customer, we send a POST request with the URI /employees, and the server sends proper response 201 CREATED. Services which implements CRUD operations are Level 2 services. Level This isthe most mature evel fora servic. It is the combination of Level 2 and HATEOAS (Hypermedia as the Engine of Application State), Services in this level provides responses with links to related resources ‘and controls which tells service client what to do next 9:53 PM 6.5KB/s © ull & ray @ lex.infosysapps.com Pee eee pO ss poe ote Spring Boot provides the spring-boot-starter-web starter for developing REST API, This starter can be ‘added using following dependency in parm xm This starter adds Tomcat as the embedded serviet container which runs on port 8080. You can set @ different port numiver using property server port in application properties fie. For example, the following code sets port number as 3456: Spring Boot by default reads the static resources such as HTML pages, CSS, Java script, images, lc. present in following locations in classpath: + static + fpublic + /resources | /METAINF/resources During application development, you might need to change code many times and for these changes to reflect in application, the application needs to be restarted. Spring Boot provides developer tools using Which you can automate this process, To use developer tools, add Spring Boot Dev Too's dependency \while creating Spring Boot project. I adds following dependency in pom xral ile: 2+ 4 Page 2. of2 > Dewoping RESTA ‘Suppose for InfyBank application you want to develop REST API to expose is following functionalities: 1. Add a customer 2 Get allcustomers 3, Update customer detalls 4, Fetch details of particular customer §,Delete a customer ‘To do this you have to create Spring controller class and implement the REST API endpoints in it. The ‘methods in controller class which implement REST endpoints ate called as REST controller methods, Now to implement above requirements you will create CustomerAPI Spring controller class, The following table shows the REST end points, HTTP methods and REST controller methods that you are going to implement inthis class: fasanee GET eterno Teeter soateotatecemane Testonen/astone |GET | eure Deter one [Fetches etter tend on atone estes — a a [ewiorsom) [BAF | dennmeregeonrer ‘The following is implementation of CustomerAPI class: Seecra) Ceca a0 4 Page 2 of2 + DewipingRESTAP, Email Perret acy }Now let us understand above class in detail @RestController This annotation is used to define REST controllers. it is a combination of @Controller and @ResponseBody annotation, @Controller annotation marks a class for discovery by ‘component scanning, @ResponseBody tells Spring that all handler methods in the controler should have their return value written directly tothe body of the response, rather than being carried in the model to @ view for rendering @RequestMapping ‘This annotation is used to map the HTTP requests to handler methods of REST controllers. You can use It at claceevel or method-level in a contraler. The clase-level @RequestMapping specifies that any handler methods in this controler will handle requests with specific request path or pattern while ‘method-level makes mappings more specific to handler methods, By default, this annotation matches to all HTTP methods. But usually controller methods should be mapped to a specific HTTP method. For this, you can use method attribute in this annotation, For example, to map an HTTP POST request you can use this annotation as follows: Spring 43 introduced new annotations for mapping handler methods with specific HTTP requests. These ‘methods are as follows: + @GeIMapping + @PostMapping + @PulMapping + @DeleteMapping 9:53 PM 0.2KB/s © @.ull ray @ lex.infosysapps.com aa er E 4 Page 2 of2 + DevipingRESTAP! + @DeleteMapping @GetMapping ‘This annotation handles HTTP GET request. In CustomerAPI when an HTTP GET request is received for infybank/customers, getAllCustomerDetails() will be called so @GetMapping is used as follows: ‘The return type of getAliCustomerDetails() method is ResponseEntity. ResponseEntity represents the entire HTTP response which includes HTTP response code, response body and response headers, In ‘method implementation, details of all the customers are fetched using CustomerService and then ‘an instance of ResponseEntily is created with customer data and the HttpStatus OK status code as follows: @Pathvariable ‘This annotation is used to extract values from URI template into a method parameter. It indicates that @ ‘method parameter should be bound to @ URI template varable the one in fn getCustomerDetal() ‘method, the value atibute of GetMapping annotation takes URI template /custorners/{customeria) as parameter where the {customerld) portion ofthe paths a placeholder. The actual value inthe request is given to the customerid parameter, which is mapped to the (customer) placeholder by @Pathvariable. So when HTTP GET request is received for infybank/customers/1 then detaits of only that customer whose customerlds 1 is fetched Drones name, then you coud specsythe path variable name inthe annotation a follows: q You can also use @PathVariable(‘customerle) or @PathVariable(name="customerlG’). This annotation can be used in any type of request method (GET, POST, DELETE, etc) @PostMapping ‘This annotation handles HTTP POST request. In CustorerAPI when an HTTP POST request is received for infybank/customers, then addCustamer() method will be called so @PastMapping is used as follows: ‘You know that along with the POST request we have to send customer data, For this customer parameter of addCustomer) method is annotated with @RequestBody annotation, It ensures that JSON data about ‘customer in the request body is converted to a Customer obj @PutMapping ‘This annotation handles HTTP PUT request. In CustomerAPI when an HTTP PUT request is received for 0.1KB/s © CTSA ‘of addCustomer() method is annotated with @RequestBody annotation, it ensures that JSON data about customer in the request body is converted to a Customer abject, @PutMapping ‘This annotation handles HTTP PUT request. In CustomerAPI when an HTTP PUT request is received for infybank/customers/{customeri, then updateCustomer() method will be called so @PutMapping is used as follows @DeleteMapping ‘This annotation handles HTTP DELETE request. In CustomerAPI when an HTTP DELETE request is recelved for infybank/customers/{customerid), then deleteCustomer) method will be called so @DeleteMapping is used as follows: Prraret @RequestParam So far you have learned that using path variable you can extract values from URI template. But ‘sometimes the request contains information as query string. A query string in part of URL and contains key-value pai. For example, consider the following URL: a In above URL customerid=12348name=Smith is query string with key customerld and name. The value of cutomerid is 1234 and value of name is Smith Using @RequestParam annotation you can bind values of query string to the controller method parameters. Far example following handler method is mapped with the request /customners?customerla = 12345 Discussion Forum, 1) Deepa Prakash Kanage FS Fag ort tare Should thse ews gen in Rinadson matty models Usd acordngtothe requirements? WS espanstotnsitvend 2 emo. sping REST Using Spring Boot Objectives: ‘To create a Spring REST READ service using Spring Boot Steps: ‘Step 1 : Create a Spring Boot project Using Spring Initial, create a Spring Boot project with following specifications + Spring Boot Version: 2.3.1 (The version keeps on changing, always choose the latest release) + Group: cominfy + Artfact: Demo_SoringREST + Name: Demo. SpringREST + Package name: cominfy + Java Version: 11 + Dependencies: Spring Data JPA, MySQL Driver, Spring Web and Devtools Now import this project in Eclipse, ‘Step 2 Create the database and table Open MySQL. terminal and execute the following command Cee ometcrzy il_id, name, dat Ber emenirineyy ‘Step 3 : Configure the data source and JPA iz aT ‘Open application properties in src/main/tesources folder and add following properties for MySQL: er) 36.3KB/s © ray @ lex.infosysapps.com Pe Oe ae eee re ‘Step 3 : Configure the d ‘open application properties in stc/malnvtesources folder and ad follow Pee! Pere Pau ete spring. jpa.show-sql=t ae et ase Caer ‘Step 4 : Add the following property in application.pr Saat iEs ‘step 5:C 4 GreeacH Cer) dateofBirth; getCustomerId() £ circus tt} rea cle Crcirisc hed Tee Cees PerreeeclOned eye ieeersstc) Poe setName ome Peoria ate mn era) Pecan eae Ores ret are ray tostring() ¢ ae 9:54 PM 0.1KB/s © (OMe Mane) cxeo) oe hate ea minty entity package ara IDENTITY) custonerId Petty Pacts Ce me Gretsch Porter CrcrisC hed rece! ona) PxCTeeclOn CirbcH Eeearstnt Essen PaO Pact Peele! estas Execute CCT Cre teen aed encom erreres conn CD) Peer per ecatts C10) (other.getCustomerId() ! Capes Cenc cure 9:54 PM 0.1KB/s © & (OMe MACS) xeon) ten tia er rate the fol 6 In cominfyexception package: ‘ Pecan) crores ‘step 9 Create an aspect LoggingAspect class in com infy.utlity package Pacer cons aos rear oc stoTt Se ester ree Retest) ‘Step 10: C1 package Pete recy Sats eG) ‘Step 11 : Create the fl ustomerServicelmpl class in com infy rena eseciay 20+ bemoon Sring REST Using Spring Boot ‘Step 12: Modify the application properties and ad the below properties: ea a eee ae rosea tcc cat ‘Step 14: Deploy the service by executing class containing sin method. ‘So you have successfully created and deployed a Spring REST READ service . Let us test itusing Postman client Testing REST Services using Postman ‘Step 1: Launch Postman. You will get following screen ‘Step 2: Testing GET request + Enter htip/locathost 8765 /infybank/customers in the URI field and click on send. Pte) 1.3KB/s © (OMe Mane) cxeo) cat ‘Step 1 : Open the pro ‘Step 2: Add the adi Create Operation in Spring REST Using Spring Boot siomer() method in CustomerSer Demo ated in previous demo. joe interface as fe > getAllCustoners() erred teeta Pecetcad recy roca TE este p RELL CCE aC) preores Seca sCeTae) Dy getCustonerId¢)) Pacer raareb) 1d) Creed Petersen pees coy Perec ier Beare aS} iecarte) Eire cesta ee Ur elg) > getAllCustoners() ce oy ere eres er aones ieee cctetae Cleat Rede reto pobre crs sberetenr Peco eN) Pec yetcey) presen crete tes prencee manne ) Crercries ase st) yoo oer tae Inte carat ‘Stop 6 : Deploy the service by executing class containing main method, So you have successfully created and deployed @ Spring REST CREATE service . Let us test ‘tusing Postman client Testing REST Services using Postman ‘Step 1: Launch Pastman and follow the below mentioned steps: cl POST as HTTP method from drop down 2 Gato the Body tab. Peta) ‘Step 6 : Deploy the service by executing class containing main method, So you have successfully created and deployed @ Spring REST CREATE service . Let us test Itusing Postman client ‘Testing REST Services using Postman ‘Step 1: Launch Postman and follow the below mentioned steps: 1. Select POST as HTTP method from drop down, 2.Go to the Body tab. 3, Select the media ype as ra 4, Select USON from the dropdown fend @renctnecansi fom] © im [eee] + Enter the following JSON data in Body. + Enter httpz/localhost 8765/infybank/customers in the URI field and click on send, + You will get below output: rt teri | TY na You can download this demo fram ere. Discussion Forum, SC Sandeep chouhan Pa rag. tsa 2oazae aoa Pyeng nates nt rr FAR Rohan Rajendra Pag tsa 20st one 9:56 PM 18.7KB/s © (OMe Mane) cxeo) ee ea Later Ded ‘Steps ‘Step 1 : Open the project created in previous demo, Step 2: Add the updateCustomer() method in Customer > getAllCustoners() erred Pte CrrsecD) Tete esta Pecetcad erecy e Seti TCS REUL pC tema TeC} Creme sr Rese ceed t Ny eretae 0) Sree aera Cicer aCe) ustoner2. setDateOfBirth(custoner .getateOfBirth()) pie eue serra Tbe (erectus: crete Tey) pier eer gear ties) etney a > getAllcustomers() . ec rca stc peur ers) : ects 20 customers. forEach(c cust. setCustoner Id(customer .getCustonerTd()) reser ence eer aap) rere eect art Sen Ciepy prreere citrate ey) prey (cust) ) Ceci ereee Lap) 9:56 PM 0.1KB/s © (OMe Mane) cxeo) ee ea Later Ded rears TCC Seetec ets es Q » GEntarstclc TECH ipdateCustomer() in Customer erences eas >> getAllCustomers() ees RoC eeat Stat Eel erga oe Sea ge custonerId) { ec Sere nate certo ere Creag n ( D Se arcag customer) rt Creech Cire ene CeeL eee geese prereer eet Pe cag as ees C) Semcon reyes ry Beer Crcac prrecares) ‘ Pree Cem ect eee Crecare Te cie ye Ptoree eed SR eae age ok) AT) 1.1KB/s © ull & ray @ lex.infosysapps.com a eee ed ‘Step 5 : Add below properties in application properties: ‘Step 6 : Deploy the service by executing class containing main method So you have successfully created and deployed a Spring REST UPDATE service . Let us test itusing Postman client. Testing REST Services using Postman ‘Step 1: Launch Postman and follow the below mentioned steps: 1, Select PUT as HTTP method from drop down, 2. Gato the Body tab. 3, Select the media ype as ra 4, Select USON from the dropdown + Enter hitp:/lacalhost 8765/infybank/customers/? into the URI field and click on send, + You will get below output: ry tor rok | Tet © ma ene cy a You can download this demo fram here. Discussion Forum, SA) Smet Menta FB Rag, an nese nts coe tomertepostory sa lemsngaterline namberS2 NE) Nayan chopra Pa hag yuan nt ersceu From this line "Optional customer eee: mre etme Miata deere on deem a Yea 2408.6KB/s © (OMe Mane) cxeo) ae ae jectives: Steps: ‘Step 1 : Open the pro ‘Step 2: Add the delet pected ercecoy > getAllCustoners() Eten cr Peete rciech corvenC Dy Potccetiicag Srecrisc dy ‘Step 3 Add th svicelmpl Crea ey Peete Craters) 4 e Seerscry| Siero ag Ces tep Re pCCese aC) Pieareennts CeCe ceed » eretare 0) Peeper eC at ceric aCe) ustoner2. setDateOfBirth(custoner .getOateOfBirth()) Pree sererar eee (eteciremrrsc crete Ten) prereset testes Pacey oirey : Serer . < Sc maT pretiteenat elt ria Piranesi reine CCST) reser ance eer eae) reer eect iar ct rSenCiep) preset are rey) tee y Senco) Yea PPL CO) (OMe Mane) cxeo) ae ae omerAPI class as show Pierre Orns Sever ees custonerServ ete Coren ok) Sone cies) { Ceci Tea eee eet) * Serer customer) i Erecrar eae Creer onic nnaetteecnrea eee eet Cee ates 7a ea aC eten ere oy Sartore race customer) i ere epee eet eee Cicer ae cc Teece ee Pre ee Pe cag 7s ) Setecee eres ok) Brora 7 | eae Tag ‘Step 5 : Add below properties in application properties: Ronee str ‘Step 6 : Deploy the service by executing class containing main method, So you have successfully created and deployed a Spring REST DELETE service . Let us test Itusing Postman client ‘Testing REST Services using Postman ‘Step 1: Launch postman and follow the below steps + Select DELETE as HTTP method from drop down + Enter http/localhost'3557/customers/1 into the URI field and click on send + You will get below response: download this demo fram, Discussion Forum, There arent any conversations yet Start a new thread aie 2+43.5KB/s © s.com/en/viev () plate ne ‘So far, you have learnt how to create REST services that can be consumed by some other applications but sometimes, you need to consume REST APis using Spring application. For this, Spring provides RestTemplate class. It takes care of the necessary plumbing needed to communicate with REST APIs and automatically marshals/unmearshals HTTP request and response bodies and provides ‘methods for interacting with REST resources, To use RestTemplate, you need to create its object as follows: Handling HTTP GET ‘Suppose that you want to fetch details of customer based on customer id. For this you can make an HTTP GET request using getForObject0) method of RestTempiate class as follows: In above code snippet, the getForObject0 sends an HTTP GET request using specified URL and an object mapped from a response body. The first parameter is the URL. The second parameter is type of response. In this case, the response data which isin JSON format is deserialized into Customer object ‘and that will be returned. The third parameter is used to fill in the {customerld} placeholder in the given URL Handling HTTP POST ‘Suppose you want to add new customer to database, For this you can make an HTTP POST request sing postFarObject) method of RestTemplate class as follows: In above code snippet, the postForObject() method POST's data to a URL and returns an object mapped {rom the response body The first parameter is the URL, second parameter is object to be posted to the server and third parameter is type of return value, Handling HTTP PUT ‘Suppose you want to update detals of a customer frorn database based on customer, For this you can make an HTTP PUT request using put) method from RestTemplate as folows ++40.0KB/s © s.com/en/viev () In above code snippet, the getForObject() sends an HTTP GET request using specified URL and an object, mapped from a response body, The first parameter is the URL. The second parameter is type of response. In this case, the response data which isin JSON format is deseriaized into Customer object ‘and that will be returned. The thd parameter is used to fill in the {customerld} placeholder in the given URL Handling HTTP POST ‘Suppose you want to add new customer to database. For this you can make an HTTP POST request sing postForObject) method of RestTemplate class as follows In above code snippet, the postForObject() method POST's data to a URL and retumns an object mapped {rom the response body The first parameter is the URL, second parameter is object to be posted to the server and third parameter is type of return value, Handling HTTP PUT ‘Suppose you want to update details of a customer frorn database based on custome, For this you can ‘make an HTTP PUT request using put) method from RestTemplate as folows: Poereesty(tel cree CIOS) Handling HTTP DELETE ‘Suppose you want to delete @ customer from database based on custometld. For this you can make ‘an HTTP DELETE request using delete) method of Rest Template class as follows: Discussion Forum, There arent any conversations yet Start a new thread Objectives: ‘To consume GET request using Spring Rest template Steps: ‘Step 1 : Create a Spring Boot Maven project Using Spring Initial, create a Spring Boot project with following specifications + Spring Boot Version: 2.3.1 (The version keeps on changing, always choose the latest release) + Group: cominfy + Artfact: Demo_SpringRestTemplate + Name: Demo_SpringRest Template + Package name: cominfy + Java Version: 11 + Dependencies: Spring Web Now import this project in Eclipse, ‘Step 2 : Modify the application properties file and add the below property ory ao DE SeCerst NCL Ceas Teen oe ererare cr) pete ‘Step 5 : Execute the application created in previous demo (Dero_SpringREST), Make sure that the REST API services are running so atthe consumer can use the services Step 6: Execute tis application (Demo SpringRestTemplte You should see the following output on execution Custaner 010 (eustmere2, mabey con, nner] download this demo from ere Discussion Forum, ‘There avert any conversations yet 0.0KB/s © ea ae Ue aa Ce Objectives: ‘To consume POST request using Spring Rest template Steps Step 1: Open the project create in previous demo ‘Step 2 : Modify the application class as shown below: peer Serre age al Sere Reraered ‘Step 3 : Execute the applicator created in previous demo (Demo-SpringREST) ‘Make sure that the REST API services are running so that the consumer can use the services, Step 4:5 cut tis application (Demo. SpringRestTemplate). You should see the following output on execution Custoner ded successfully with customer id : 4 ‘You can download this demo fram ce a 0.7KB/s © (OMe Mane) cxeo) a Objectives: sme PUT reques ‘Steps ‘Step 1 : Open the project created in previous demo, ‘Step 2 : Modify the application class as shown bek occa rT Peeper otra) reer st ec lg eee teretett istomerDTO! ) Peete or Parser Perro ace ctny customerId) oa Cee) icc stra) } err terngg orcs oo oer rceee oO erence ecm Set nets ces ee Teccs eUr ran) i Preece Cred ot aT CustomerDT0 customerDTO1 eet eT estbel Peetearctesnsn rit ec ses ey ores) cTenplate TO ‘Step 3 : Execute the application created in previous demo (Derno_SpringREST), Make sure that the REST API services are running so thatthe consumer can use the services ‘Step 4 : Execute this application (Demo_SpringRest Template) ‘You shoul see the following output on execution Customer updated successfully You can download this demo from here. Discussion Forum, There arent any conversations yet Start a new thread _ _ aC 11.3KB/s © (OMe Mane) cxeo) ee Gane ‘Steps ‘Step 1 : Open the project created in previous demo, ‘Step 2 : Modify the application class as shown bek occa oe Pree ras) Poets rce Tees rat Preeti Cries CEC Teme Seager) Peete) icc eet ao) iio trae) rtrd erent url eae ee ) er eC eC Sais rs ) LOGGER. info(response) ; icc tran) Pc ecettcge Cried aC coe eyes Stem Stacia! nee enplate . cTenplate.put(url, customerDT¢ ‘Step 3 : Execute the application created in previous derno (Derno_SpringREST), Make sure that the REST API services are running so thatthe consumer can use the services ‘Step 4 : Execute this application (Demo_SpringRestTempiate). You should see the following autput on execution download this demo fram. Discussion Forum, There arent any conversations yet Start a new thread a -15.7KB/s © Bull ray @ lex.infosysapps.com Cet eda For security reasons, browsers dort allow you to make cross-origin request. Cross origin requests are requests to those resources which resides outside the the current origin. For example, if a dacument ‘served from xyz.com makes a request to domain abe.com for some images then this request is called as cross origin request. [EE] sone on newer = == gen |= |} Ss (com ng Rewer a) Se ‘To allow cross-origin requests, Cross-Origin Resource Sharing (CORS) is useé. Its an specification which provides a way to specify which crossorigin requests are__permitted Spring provides @CrossOrigin annotation for enabing CORS for REST API so that the API clients can ‘make calls to REST APIs, This annotation can be applied at class level as follows: When applied at the class level, the same @CrossOrigin configuration is applied to all the @RequestMapping methods. Ha -0.5KB/s © & ray @ lex.infosysapps.com aon = © omsas Qiot6 BR Which of the following statements are true? Choose 3 correct options. 1. erequestapping annotation by deat handles al ypes of HTP requests 1. eestconrler annotations combination of @cotoler nd @ResponseBodyennetation 1D eRequesiapping annotation can ony be ured atl ve D_@responsesoy annotation indicates that value returned by a method's bound to body of HTTP response coors Rp Consider the following controller class: eeestcontcolter @Requestiapping(valve="/9pi") public class UseraPl4 eetlapping( value = “user/(userid)*) public String getUser(ePathvariable Integer userId) ( Uirest of the code > Which of the following HTTP GET requests are mapped to above controller? © mpinocanosenenapnsesestos (© mpinocanasenenapnserserst0s (© pnacanncs0evapiseras (O hpinocamesconsnaprusersuenyi0s sors RP Consider the following controller class: eeestconteoller leequestiapping(value="/9pi") public elses CistonerAPl( ‘inet Dublie String getCostoner(@Pathvariable"custid") Integer custonerI4) 4 Uirest of the code > Which of the following statement can be inserted at Line 1 to map following HTTP GET request to above controller? Choose 2 correct options. http://localhost:8080/api/customer/1001 1 ecerappingdste="/ustomereustar) 1 ecetmapingbatie="/austomerfaustomet") 3 mmeetneenmeeseneenee enemas matte etme ee cra +00.0KB/s © Bull Ball CD ray @ lex.infosysapps.com eee sors RP Consider the following controller class: eeesteonteoller feRequestiapping(valuen"/api") public class castonerAPT( public String getCustoner(@Pathvariable(“custid") Integer eustonerta) 4 Uirest of the code > Which of the following statement can be inserted at Line 1 to map following HTTP GET request to above controller? Choose 2 correct options. http://localhost:8080/api/customer/1001 1D ecermappingvalue=yeustomersteustid’) De cetmappingvalue=/eustomer/(ustomerid)) 1D eRequestMappingvaue = "/customer/(custld", method = Request Method. GEN) D_erequestmappingvalue = eustomer/fustomerdy’, method = RequestMethod.GET) cuore Rp Consider the following controller class: > ecestontroller q feu taping value=/op" public late Cartons ‘eGethapping(value = "/custoner") Dublie String getCostoner(@tequertParan Integer cstonerId) ( Virest of the Code , > Which of the following HTTP GET requests are mapped to above controller? (O mipsnecanoscsaearpicustamerestomend-101 O mpinecanesconeaaprausomercstomeris-001 (O hep:ecahneseoenepiustomertcutomers001 O hrsonastateapucutomert001 sore Pp Which of the following is correct use of RestTemplate class to get details of customer whose customerld = 1001 using GET URI api/customer/{customerld} ? Assumptions: 1. restTemplate is valid reference of RestTemplate class. “vest of tna code > > Which of the following HTTP GET requests are mapped to above controller? (© tmcanosentpcramerttemens=100 (© tmocanoseneipcramercaorei=100 © tnpecinossneopresomeresomeri00 O hretosnasateapucutomert001 wots Pp Which of the following is correct use of RestTemplate class to get details of customer whose customerld = 1001 using GET URI api/customer/{customer|d} ? Assumptions: 1. restTemplate is valid reference of RestTemplate class. 2. CustomerDTO is a Java bean class. © resent ger pecan okopcomesael Cust cs 10 © restate gator npr Epona 0" Cusome IO sk © restate gator pamelor Custos 101, (O restenplt geforbjeYaplesiorer 101, CuxomerTO.cast esots p Which of the following statements are CORRECT about RestTemplate class: 1. RestTemplate class can be autowired even if it is not configured as a Spring bean. 2. RestTemplate class can be autowired only if it is configured as a Spring bean. 3. RestTemplate class cannot be configured as a Spring bean. Oo oO: oO: O None ottnese cra -10.0KB/s © ull ray @ lex.infosysapps.com ed Problem Statement InfyCabs is an application for booking cabs. Its following functionalities needs to be exposed as REST A 1. Book a cab 2, Get booking details 3, Cancel booking ‘The service and persistence layer of this application is already implemented. You have to implement the [AP\ layer ofthis application for exposing the above functionalities, Follow the below mentioned steps to get started 1. Click here to download and import the project in Eclipse. 2, Change the database credentials in application properties file 3. Execute TableScript sql file to upload sample data to your database 1. CabBookingAPI Implement the CabBookingAP! class based on the class diagram and instructions given below: 1. Annotate this class with proper annotation to deoiare it as REST controller class. 2. Annotate this class with proper annotation so that all its methads are mapped with /bookings as base URI 5 inject BookingService and environment using appropriate annotation. Method description: ‘bookCab(CabBookingDTO cabBookingDTO) «This isa REST controller method to book a cab. «+ liplement it using proper annotations according to description given below: © Resource endpoint: / © HTTP method: POST «© Input: Booking details as part of HTTP request body. «+ It should invoke the bookCab() method of BookingServicelmp! class which returns a booking i. ‘Retrieve the success message associated with property APLBOOKING SUCCESSFUL from application properties files using environment and append i to booking id in folowing format booking id ‘sit retums an object of ResponseEntty created using above message and HTTP status code as CREATED. ‘getBookingDetails(Long mobileNo) “+ This isa REST controller method to get cab booking details based on mobile number of user. «+ Implement it using proper annotations according to description given below: » Resource endpoint: mobileNo} © HTTP method: GET © Input: mobileNo as path variable, ‘+t should invoke the getDetails() method of BookingServicelmp! class which returns a ListeCabBookingDTO>. + Itreturns an object of ResponseEntity created using List obtained in previous step and HTTP status code as OK. ccancelBooking( Integer bookinglé) ‘+ This isa REST controller method to cancel cab booking based on bookingld + Implement it using proper annotations according to description given below: © Resource endpoint: /foookingla} © HTTP method: PUT ata {getBookingDetails(Long mobileNo) + This is @ REST controller method to get cab booking details based on mobile number of user, + Implement it using proper annotations according to description given below: > Resource endpoint: (mobileNo} > HTTP method: GET © Input mobileNo as path variable. lt should invoke the getDetails) method of BookingServicelmpl class which returns a List + Itretums an object of ResponseEntty created using ListeCabBookingDTO> obtained in previous step ‘and HTTP status code as OK ccancelBooking( Integer bookinglé) « This isa REST controller method fo cancel cab booking based on bookingld + Implement using proper annotations according to description given below: > Resource endpoint: /{oookinglc) © HTTP method: PUT = Input: bookingld as path variable + It should invoke cancelBooking) method of BookingServiceimpl class + Retrieve the message associated with property ‘APL BOOKING. CANCELLED" from the properties fle + Itretums an object of ResponseE:ity created using above message and HTTP status code as OK 2. Use the Postman tool to test the API using following data: + Resource URL -hitp//localhost'8765/bookings/9877766756 © HTTP Method : GET © Expected output + Resource URL -http//localnost8765/bookingsy © HTTP Method : POST © Input + Expected output Booking successfully with booking id: 3 + Resource URL. tpy/localhost8765/bookings/T © HTTP Method : PUT o Expected output Booking cancelled successfully, st Why to do exception handling? In infyBank application, consider the following REST controller ever Petree Crea) This controller i customer details if customeriais pr Infybank/custorer/{customerla} mapping which takes customerid and returns the ent If no customer is present with given customer id and Service class throws an exception with message Service CUSTOMER_UNAVAILABE for non existent customer then this controller returns the following response: a In above response, the HTTP status code is 500 which conveys that there is some internal server error which is incorrect. Since the resource is not present the status code should be 404 which means resource not found. So, we can modify the controller code as shown below: st Hl o ‘This controller has infybank/customer/{customerld} mapping which takes customerid and returns the customer details if customer is present. If no customer is present with given customer id end Service class throws an exception with message Service CUSTOMER_UNAVAILABE for non existent customer then this controller returns the following response: o In above response, the HTTP status code is 500 which conveys that there is some internal server error which is incorrect. Since the resource is not present the status code should be 404 which means resource not found. So, we can modify the controller cade as shown below. But this solution adds more code to the controller and makes it complex. Also if multiple handler ‘methods are present in controle, then this code you may have to repeat inal those methods. Also, there is no way to send more detailed description of exception to the client, So proper exception handing in REST APIS is very important. Spring provides multiple ways of exception handling in REST API. in this course, you will eam following two ways of exception handling 1. Using @RestControllerAdvice 2 Using ResponseStatusException class Discussion Forum, 2 sO Page 1 of2 In this approach, a central exception handler class is created to handle all the unhandled exceptions thrown from your cade. So ll the unhandled exceptions will be handled at one central place which makes ‘exception handling easier. Now let us see how to do this, ‘To do this the first create a central exception handler class and annotate it with it @RestControllerAdvice annotation as shown below ‘Then add handler methods to this class to handle cifferent types of exceptions and annotate them with @ExceptionHandler annotation, Now to handle InfyBankException exception, add exception handler method as folows: eee send Now if your code throws InfyBankException the infyankExceptiontandler() method will execute. Now if you to fetch details of non existent customer you will get following response with correct HTTP status ‘cade from controller You can also have multiple handler methods in the Advice class to handle exceptions of different types ‘and retum the response accordingly. For example, to handle all types of exception you can also add a {general exception handler method as follows: cease ption) noes Srey erin sO O @ lexin € Le _ Exception Handling using @RestControllerAdvice Now If your code throws InfyBankException the infyBankExceptionHandler() method will execute. Now if you to fetch details of non existent customer you will get following response with correct HTTP status Cade from controller You can also have multiple handler methods in the Advice class to handle exceptions of different types {and relum the response accordingly. For example, to handle all types of exception you can also add a general exception handler method as follows: Hevpstatus. INTERNAL SEI Pete exception) Ifyou want one method to handle both Exception and InfyBankException, then you can write one handler method as follows Discussion Forum ‘There are’ any conversations yet Start a new thre: sO 4 Page 2 of? You have seen that when exception is thrown the response from the controller only contains message and the HTTP status code. But sometimes you want to provide more information to the client about the exception. For example, you want to provide details about date and time of exception also along with message and HTTP status code. To do this you have to create @ custom error class with desired information as follows: Now, modify the handler methods of RestExceptionHandler class to include object of Erroinfo class as part of response as shown below INTERNAL_SERVER_ERROF nae eye cy etTimestanp(l "0 eau Ty Now if you fetch details of non existent customer you will get folowing response from controller a 0.1KB/s © @.utl & ray @ lex.infosysapps.com ee eer ea) ne Objective: Toillustrate how todo global exception handling in Spring REST application Steps ‘Step 1: Using Spring Initaizr, create a Spring Boot project with folowing specifications: + Spring Boot Versior * Group: cominfy + Artfact: Demo01_SpringREST_ExceptionHandling + Name: Demo01_SpringREST_ExceptionHandling + Package name: + Java + Dependencies: Spring Data JPA MySQL Driver Spring Web Spring Boot DevTools Now, import this project in Eclipse ‘Step 2: Modify the imported project according to the following project structure cert Spin cpeninding 2 comin 3 comme, 2 coniton 3S eetieeer 3S oemmee cua pony Ds ‘Step 3: Create the database and Open MySQL terminal and execute the following command Cee eee eet tae? aero serena ae Steen Cat cS Peet n eet mC) customer (customer_id, email_id, name, date_of_birth’ al CeCe a eC Ce aaa} PEoMeuoarsl Pera email_id, name, dat Vere oneticraas) aOR 0.4KB/s © (OMe Mane) cxeo) eee er ed ‘Step 4: Configure the data source ‘open application properties in src/malnvtesources folder and add folk aCe ete aes ee eae eect area aCe ee Sau eee aus ee eC ‘step 5: Create the folowing CustomerDTO class in com infy.dto package fi recrrac} eect, getCustomerId() ¢ Eireeara ct! Eoatene eC Crcrisc hing Teac ees getEmailld() ¢ enailld = enailld: Pens Pence aon Poe reO nee dateofBirth; Erecting Cc! presi rat eae era Coenen + customerId + career Te aOR 0.2KB/s © (OMe Mane) cxeo) eee er ed Porton ee Ce reece ae) asters wing Customer class in com infyentityp easy custonerId thee Ceca getCustomerId() £ peoutact Peceteecat Crcirasching Tec eect Erssechine eeserciearrric] Poms cecue can Puree nee eit Pei tanG Pate ee ta ear acta rencront enon Pca Ces a 0.4KB/s © (OMe Mane) cxeo) cat ‘step 8: Create the folowi Erecteea c Py eet tone Posen) Poteet custonerRey preoies merService interface in com i Exception Handling using @RestControllerAdvice - Demo service pack Dy omer( racy customertd, SrecriscD) > getAllCustoners() customerRepository aad rececoy ect ees NEUE etsy ereenres optional .orElseThrow(() => yy Sree Peteceee Cte pare ace ay 0) PereteccnsgCiay) Pacer saareD) nailld(customer -get€mailId()) Bierce ceed) Cress erred c Saar reer ste oe Creer arenaee ey o SCR en) CseeCetet pe LE seec rep) custonerEntity. setName(custonerDTO. getName()) Peas eee 1s tomer Id cus tomerDTO. get Customer Id¢)) rar ML TCC e tron Entity2 a 0.0KB/s © & (OMe Mane) cxeo) eee er ed ‘Step 10: Create an aspect LoggingAspect class In com infy.utity package Petra Cortietia Asus pUrerrareearer at eaencsc ‘Step 11: Create the folowing InfyBankException class in com.infy exception package ‘ ese rss crit « Ce Carers Seen Pee arene preety pea eee nee Se ee ere Pec arene pres eae Carers re eee! oar e es ores Prasurercuse Suc! cen eastern aD 0.0KB/s © (OMe Mane) cxeo) eee er ed reate the following ExceptionControlerAdvice class in com infyutity package es r 7 Bevcase ge Ecos error = o Cpe ages eee eos ee a ee Sear crs Nee md oD) Peerrasiceit corey) Scie eT tS) rues ae orstaD) Ce ae eee ean eC ctr ce dD) Preece now) panerecamirer tte rome oO err Com} coats ere >> getAllCustoners() { y ee ee Se Creare ea) Scat ok) Se crcigd icra) fl eee) a ae Sea ere Sg om esas c Paneer ear ee precedes easiest] aCe cuss etsy file.level aS peareer cree tetes paneer paneote ‘Step 17; Deplay the application on the server by executing the class containing the main method, w have successfully implemented global exception handling. Now, you can test it using Postman client. Testing Web Service using Postman ‘Step 1 Launch Postman, ‘Step 2: Provide HTTP GET request - http:/localhost'8766/infybank/customers/4 that wil get the customer details based on the customerld (invalid customerid that does not exist in infybank) aD 0.0KB/s © ull & ray @ lex.infosysapps.com ee era ‘Step 17; Deplay the application on the server by executing the class containing the main method. We have successfully implemented global exception handling, Now, you can test it using Postman client, Testing Web Service using Postman ‘Step 1 Launch Postman, ‘Step 2: Provide HTTP GET request - http:/localhost'8766/infybank/customers/4 that wil get the ‘customer details based on the customerld (invalid customerid that does not exist in infybank) ‘Step 3: Provide HTTP GET request - http:/localhost'8766/infybank/customers/a that wil get the ‘customer details based on the customerld (A characteris passed instead of an integer) fom sesemapesnand — EEE -- ty te tee OY na \We observe that Exception is thrown with code 500. This Exception is of type Exception, ‘We can conclude that Global Exception handling is working for exceptions of both InfyBankException and Exception types, You can download this demo fram here. Discussion Forum, There arent any conversations yet Start a new thread *.

You might also like