Spring Boot REST Tutorial | Karthikeya T | Skillshare

Spring Boot REST Tutorial

Karthikeya T, For Your Learning Needs

Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
54 Lessons (4h 46m)
    • 1. A note Before starting the class!

    • 2. 0101 Traditional MVC Architecture

    • 3. 0102 Problems With Traditional MVC Applications

    • 4. 0103 RMI

    • 5. 0104 Webservices With SOAP

    • 6. 0105 RESTful WebServices

    • 7. 0301Traditional MVC vs REST API

    • 8. 0302 Installing Postman To Test Our API

    • 9. 0304 API We Will Be Building

    • 10. 0305 Create A Spring Boot Project For Our API

    • 11. 0306 Get Products API

    • 12. 0307 Get Specific Product

    • 13. 0308 Add Resource With Post

    • 14. 0309 Update With Json And Put

    • 15. 0310 Delete Resource With Delete

    • 16. 0401ContentNegotiationIntroduction

    • 17. 0402HTTPHeaderContentNegotiation

    • 18. 0403RequestParamForContentNegotiation

    • 19. 0404PathExtensionContentNegotiation

    • 20. 0405ContentType

    • 21. 0406ProducesAttributeAndPDFResponse

    • 22. 0407AcceptEncodingForCompressionAlogrithm

    • 23. 0502CacheMaxAge

    • 24. 0503ETAGTheory

    • 25. 0504EtagExample

    • 26. 0505No Store,Public,Private

    • 27. 0601PatchAndSendingMap

    • 28. 0602IdempotencyAndSafeMethods

    • 29. 0603FileUploadAndDownload

    • 30. 0701ErrorHandling

    • 31. 0702Validation,CustomValidations

    • 32. 0801RESTTemplateIntro

    • 33. 0802JsonJacksonToRetrieveSpecificInfo

    • 34. 0803POSTUsingRESTTemplate

    • 35. 0804PUTUsingRESTTemplate

    • 36. 0805DELETEUsingRestTeamplate

    • 37. 0806RestTemplateErrorHandling

    • 38. 0807HandlingTimeOut

    • 39. 0901HATEOASIntroduction

    • 40. 0902HATEOASImplementation

    • 41. 0903HATEOASImplementation

    • 42. 1001SpringReactiveProgramingTheory

    • 43. 1002ImplementingReactiveProgrammingInSpring

    • 44. 1003BackPressure

    • 45. 1004RespondingInReactiveWay

    • 46. 1005LiveStream

    • 47. 1006FluxVsMono

    • 48. 1007ParallelStreams

    • 49. 1008WebClient

    • 50. 1009SpringReactWithMongoDB

    • 51. 1010SpringReactMongoDBWorkingExammple

    • 52. 1011LiveStreamWithMongoDB

    • 53. 1012TestingReactiveApplications

    • 54. 1013DrawbacksOfReactiveProgramming


About This Class

Spring boot REST, is  a tutorial that covers all the necessary concepts related to Spring Boot REST API (or) RESTful web services. At it's core, we Spring REST allows us to expose an API to make remote calls from another Application, like Angular, React, Mobile App, etc.

Knowledge no REST API is an absolute must for IT professionals and Spring REST is by far, the post popular framework to create REST API.

This course will start from fundamentals and then we explore a host of concepts that are listed below..

Webservice Fundamentals

Creating a CRUD REST API

Content Negotiation

HTTP Cache

Error Handling

REST Template


Reactive REST

OAuth & JWT


1. A note Before starting the class!: full stack developer sort in great demand and are paid very high. So it's not enough that you'll on one technology but rather full stack off technologies. We have all the courses on sculpture that would help you become a full staff Java developer so that you will gain skills to develop, end, to end applications from scratch all by yourself and be eligible for top profile jobs or to work on freelance projects. So was it this link? Its corporate dot com slash skill share. It has all the links to our courses, and they're all organized in a proper sequence. You can start from Java programming, and here's a link to that course. Once you complete this course, you can get into advance Java. And here's the course link for the same. Like was, you keep going and complete the entire stack off technologies. The courses were also include creating into and applications from scratch. And if you're struck anywhere, you can always post your questions. Even if you're inexperienced. Dollop er I would highly recommend you to start from scratch because many people who followed this approach and gone through all these courses from scratch have seen very good results. Many individuals have clear interviews. Some of them also cleared certification exams and some of them also got into good jobs with better income and all. So I would highly recommend that you followed this approach. Start from Java programming all the way to all the advanced courses. Hope it makes sense. 2. 0101 Traditional MVC Architecture: before we dive went understanding Web services. It might be a good idea to understand traditional monolithic embassy applications. If you all don't know about them, that's great. Otherwise, it is a simple scenario. Imagine that I have a company and we provide weather forecasting services. Now, whenever somebody visits our website off many features, they're going to see a button that say's show current temperature. When the user clicks on this button, there be shown with the current temperature, depending on these this location well behind the scenes. This is how it works. As soon as there's a flex a button. Yesterday, Perricos would be sent from the Broza to the server, the underlying containable. Then forward that request to irrelevant controller controllable delegate that call to model . This is where we would have the business logic interacting with the database etcetera. And in our case, we're going to figure out the current temperature in model section and then after that, from within the model, we're going to send back the response, basically an object that would constitute the data back to the controller controllable, then handled that data to some view technology, depending on the view technologies that you use. For example, if you're using JSP, the JSP would consume that data and just be file would become what it into equal. And so that file, which will have bunch of printed in statements and then ultimately that so that would be executed. And the response would be sent back with the HTML back to the client. And so user will see the response. And in this case, we're assuming that our application is reciting in a single silver. 3. 0102 Problems With Traditional MVC Applications: there are certain challenges with traditional monolithic applications. The stock about a few of them. Imagine that there is another company who are providing fried booking services so the customers can book flights etcetera. What they found out is that they also needed some other information, depending on which they would schedule flights. At the same time, they don't want to spend a lot of money hiring people to do all of that service for them. Instead, what they want to do is to use ourselves by paying a certain amount so they will approach us and we talk about a deal. And finally, we agree with the contract to use our service from that point on. What they will do is they will send yesterday Pericles from their application from the business logic to our service to extract the weather information. But our application is designed in such way we won't be sending the data, but we'll send data along with their Stammel or the presentation logic. This is clearly a problem. The flight booking service is expecting our service to send data, but we're not only sending data but also the presentation logic. This is bad for two good reasons. Number one. The fried booking service does not have knowledge on how to understand HTML. So they have to introduce some additional modules or write additional code to chop off all the stimulus tax and extract the data from it. And another problem is, even if they're able to do so, presentation logic will not remain same. It will keep changing. So when we make changes in our esteem, l cord, it's also going to break their court, and so their application will not function as well. So this is one problem. Another problem is, if you think about a website like Amazon, you can't expect Amazon to be hosted on a single server. I mean, what if there are not enough resources to handle the traffic awarded the silver runs off this space are What if there is a bug in the app that's going to cause the end? That application to crash and no one would be able to access the website, so instead, their application is split up into multiple competent and each component would be reciting in an independent instance off server, and each instance would handle a particular task, especially with Microsoft's architecture and when you spit out the application in this manner, they often need to communicate each other in order to perform a business task. But unfortunately, the way we're deploying our applications, they won't be able to talk to each other because we're not sending the data were communicating with data with presentation, and that's not feasible at all. So this is clearly a problem. Another problem arises when you talk about single page applications. If you don't have what single page application here is the simplest definition off the same . A single page application is an application that does not need a page reload when the user is interacting with the application on the website. Here are some of the examples off single paid applications A stock about Gmail, for instance. The moment you log into Gmail, you're going to see all the emails subjects, and when you click on one of the subjects, all the content would come up. But the page reload does not happen as soon as you click the subject. Similarly, with the Google Dogs, when you're navigating through the entire Google Docks application, it does not cause pace to be loaded. Only that particular section which you wanted to access will be populated. Twitter is also a single page application. You can click on multiple links that are available and Twitter and use all its features without causing pace to be lorded. Same is the case with Instagram. The moment you click on image, it does not cause players to be reloaded. Same as guest with Netflix there many such examples, including Facebook. Facebook is also partially single bit application and basically it's not about Page not getting reloaded. The idea is that it will improve the performance off the application and gives the batteries or experience Single payer applications are possible because off the way it works , we never use the visits. The website a get request will be sent to the server so that would then respond back with all the esteem. Lt is his jowls prep, etcetera. And from that point on, for all these interactions with the website, the silver would only send back the data without the presentation logic Because so where has all the injected the javascript, which is a client court, essentially like angler reactor BJ s, which is handling the presentation part but taking the data anyway, that's a topical future. But I hope you understood how single page application is working, but with our traditional monolithic application. So where is going to just respond back with SD Emma making single page applications harder to implement? So this is clearly yet another problem. We will take a look at how we can bring solutions to these problems with, of course Web services. 4. 0103 RMI: one of the solutions to our problems is remote matter in location or simply are my Basically. The idea is that you would no longer send yesterday per request and then receive STM allows the response You're going to definitely call the matter inside the more layer. In other words, you're going to call the business matter directly that is reciting in another jbm and get back the data as the response This cold water with that method returns going back to a flight booking service. Example, The flight booking service will would now be able to call to get temperature method along with para meters. In this case, it's going to send the location to the remote matter reciting in another jbm which is our weather forecasts overs. And then there. Moz of was going to respond back with the data or whatever the value that the method returns, which will then be used inside the flight booking service. This is possible with Autumn mine using an out of my tour. We're going to create so called a stub and the skeleton stop is going to recite on the client side, which in this case, ISS flight booking service and the skeleton is going to recite on the server side. The weather forecasts overs from within the client application. You would use the stub object and you would be able to call the remote method. Internally. Stop will take care off, establishing the connection with the silver and then send those para meters to the remote machine. Their skeleton on the other end is going to receive those perimeters called Espace with JV method or the remote mattered and water with the matter Britain's The skeleton is going to send back the data or the object back to the stub and stubbled and forward it back to the client application. In simple terms, the client application of the flight booking service would interact with the stub as if it is interacting with the remote object. Well, Ottoman makes it possible to extend data between services, but it has its own drawbacks. For instance, since we're using arm my, it will only work with Java, so only the two applications are deployed on JB and Machine and their board Del appears in Java. They both can communicate. If, for example, you would like to interact with the PHP application, then it's not possible. So this is a significant Is that want age when you're talking about distributed applications like Amazon, where all the services may be residing in various geographical locations on various different platforms and might be written in various different programming languages, the only toe becoming getting with each other not to perform a business task, but without a my. Their application is only restricted to use only java and use JV and platform, so that's definitely a drawback. Another drawback is off course. You won't be able to interact with technologies like angular reactor view because they're all essentially JavaScript libraries reciting in the client, and you cannot just talk to them using out of my along with all these. There are certain other these advantages without a my I mean, it's not efficient, and the court doesn't look so user friendly to dollar purse. And for that reason, army is not even an option of the days. They're better. All the natives, which will talk about in a while 5. 0104 Webservices With SOAP: Okay, let's talk about Web services with soap protocol. We've seen that too. Services, which may be written on two different languages or technologies and maybe running on two different platforms cannot actually talk to each other because they just cannot call every more Java method on your application is written using, say, PHP or Darknet Technologies. So the underlying problem is we don't have a common language that these two entities can understand. If we can introduce a language that these two entities can understand an exchange data between them that would solve our problem. So the language off choice is XML markup language. XML is just bunch off tax somewhat like HTML, and we can define our own standards and at a very high level. This is how it's going to work, going back to our example on fried booking service, where it tries to access the weather forecast service to maybe extract the current temperature, depending on the location, assuming that the flight booking service. So the client is written using BH pure .net Technologies, and it tries to access a remote matter of Java, which is reciting on a different host our remote machine. This is how it's going to work you as a dollop er off PHP. You're going to use a PHP library in order to send the request so you would send the battle meters or the method name etcetera. And this underlying library will take care of converting that request into Equal Int XML file, which will then be transmitted over the Internet to the remote machine on the remote side. You would have a library written using Java, which will take care off, passing all the XML data and making call to the Java method. And whatever the value that the Java mattered, returns would again be robbed inside XML tags and would be transmitted over the Internet back to the client, which will again be received by the library and would be translated back to technology specific implementation. So, ultimately, your Babel toe make a call. The remote method, which was written using different technology than to that off the client and you would be able to receive the data as a response back to the client. Now, in this case, the weather Forecast Service is called a Web service because it is essentially a service available over the gap and somebody can access it over the Internet like the fried booking services trying to access it. But we still have a lot of problems here. I mean, you can't just send any random XML and expect the remote mission to understand it. You have to follow certain standards are you have toe follow certain standard tags in order texting data, and all these entities who want to be part of the Web services would stick to that standard . And that standard is nothing but soap are simple object access protocol, which are just bunch off rules that needs to be followed by all these entities in order to exchange data. In simple terms, it's a messaging protocol, a standard as we off exchanging data using example between these entities or services. In addition to all this, the plane also needs to know how rats is the Web service. What are the matter? Perimeters that are expected? What is the return value that it can expect? Etcetera. We have to use wisdom or Web service description language in order to define all those stuff. So here is that our format office soap mess age is the same format which you need to follow . For both request and response, you have to have the route tag, which is envelope. It's mandatory to start your maximal with this tag. And when I say you have to start, you don't really have to do that as a developer. This will all be taken care by the underlying library. You don't get to create the request maximal in this format, unless you're testing seem tohave the envelope as root tag. It would have typically bunch off child tax the first off, which is an optional header tag, wherein you could include some authentication information. This is optional and you need to have a mandatory body tag. This is where you were include all the information required to call the remote procedure or to send back the response. You know, flight booking service. If you want to send the request from the flight booking service to the remote method, the body would include the information to call the more procedure, including the perimeters that you want to send. So maybe you would want to call get current temperature and you would pass string as a perimeter. Then you can do so in this case. What we're looking at is the response received back from the web service back to the client . So here we're trying toe send the name of the location and the current temperature that it is trying to return. But still, this is not the complete soap architecture. It is way more complex than this. And this was just a very high level view how far it's going to work in case if you're curious how it exactly works in case offspring ws our spring Web services. Here are the sequins off steps in to take care in order to create a Web service and expose it over the Internet, you would force create so called on xsd file and it looks something like this, and this would define the information about the perimeters. Expected the expected return value, etcetera. So you have this get temperature request, for instance, and you're expecting to receive location as a perimeter to the remote mattered, which is off type string and similarly went to send back the response, which is the temperature in the form off string. And using this XML document, we're going to use the tool called Jack's B, which will be a maven plug in our greater plugging, depending on the project management tool, your using who used this plug in in order to create doing objects using this XSD file. This will be done with that plug in. And then we'll create an end point, which is essentially a place where he would receive the request and process it kind off like a controller. And it would start off, respond back with some written value, and inside here would use all those domain objects. And then, finally, spring Ws will create so called a versatile file that I talked about isn't the sexes do file and would make it available over the Internet on the other end? Whoever wants to consume the service, like, in our case, tried booking service willing to consume the weather forecast service, we will again used to Jack's be plug in in order to create the domain classes, using the video file that was published over the Internet and then using those request and response domain classes who would send the request and receive the response? Well, this is at a very high level. Down the line will have some examples that will understand even better So in the end, we may have all these advantageous by creating Web services with soap protocol, the first of which is interoperability, meaning that regardless off the technology is in which your service is written, every service can actually talk to each other using soap protocol and extend data between them like this, another that will just talked, the second of which is Soap uses his tribute protocol, and hence there won't be any shoe. With the fire war going back to our PC example, for instance, or remote procedural call, you have to open a second report and oftentimes firearm actually block that traffic. So with soap since we're using is to depict protocol in order to transmit the data. There's going to be no problem with the firewall because Hester the report is always open and Fire world will not stop it. In other words, the message that I talked about would be wrapped with extra DP header and body inside the body would have this message. Soap also works with other protocols like FTP, SMTP or TCP, in order to communicate within the network and for this very reason. For all the advantages that I talked about soap is a better alternator compact toe RPC when it comes to single page applications or distributed systems. Well, that being said, there are a lot of disadvantages when you're trying to access up services with soap protocol, and we'll talk about them once after we cover rest architecture. 6. 0105 RESTful WebServices: Let's talk about restaurant Web services in order to understand what is the rest of Web service. So here's the definition defining what is the rest for Web service? A service which is built on the stock director is called Arrest Will Web service Now, Obviously, this may not make complete sense to you, because there are a lot of terminologies and principles that we should be a bit off in order to understand. What exactly is restaurant conjecture? By the way, restaurants for representational state transfer, and we'll understand it as well. Incoming SLIDES The first time that you need to know is something called a resource. Now there are a lot of definitions to define. What is the resource? Industrial architecture? But according to me, I want to put it very simple. You can think off resource as something that you can manipulate with a. You are. For example, a resource can be a document which contribute or the Internet with a You'll. Or it could also be a row in the database, which you can manipulate with your if you're not exposed to Web services. This might sound strange that you'll be able to manipulate a database record with a UAL. But that's what rest is meant for investable Web services, even a record in a database systems as a resource because you can manipulate it with a year earlier, an example off which can be seen in here assuming that you are having a school management application, for instance, and let's that you'd like to retrieve all the students available in the database for which you would use a You are that looks something like this. You'd say Whatever is the domain and then slash students. This riposte would land in a controller logic, which will have a your mapping that maps with this, your whole Patton, and it would get that call to business. Logical. Whatever. Ultimate ID will retrieve all the students in the form off the XML or Jason. The data would look something like this if errors in Jason and then would be sent back to the client. It is up to the client. Depending on the client, it could be a silver. It could be a JavaScript technology, etcetera. Whatever it is ultimate, it's going to consume that data and do whatever it wants to do. Another example is, let's say, you wanted to access a specific record off a student, bypassing the identifier. So in this case, we're trying to retrieve a student having the following i D. And this over would respond back, or the Web service would respond back with defaulting Jason Data. Likewise, inside Web services, you would be able to seek all the services offered by Web service. With you are, Let's talk about rest ful methods. Restroom Web services relies on extradicted methods, so you can pretty much use all the standard of stripping methods in order to manage plate with the resource. For example, he could use has to do to get method like we did earlier, in order to access or get a resource from this over are you could use the post method in order to create a resource on the server you can use. Put in order to update a resource on the silver or delete in order to delete a record in the silver or resource in the silver. For example, If elected the leader store into card, you pretty much send the same request, but using it delayed method instead off get mattered, and obviously, as you might have guessed. We can't use these methods from the browser because browser's would only support get in post methods would have some additional tools to do their job. For us, for example, we have a chrome plug in called Postman How we convey trauma to like coal. You know, some of the other elements in just for architecture that we should be aware off. We have request headers. This is where you would include authorization and authentication information because in most cases you don't want pep services to be accessible by everyone. That has to be some kind of authentication or authorization. Maybe I won't expose my Web service to only paid audience who have the credentials. So this is where you will include those authorization authentication details so that my service can provide services to you are declined. The request body is something very would include the data, how you would essentially include a representation off a resource in order to perform some operation, for example, you might have and data that looks something like this, and you're going to use the post matter off extra DP in order to send the request. So that way the student entry will be stored as a record in the database. Now this brings me to talk about what is rest. Rest stands for presentational state transfer. What that means is when you're trying to retrieve the student information, the record that is present in the database is represented in in the form of Jason or example, whichever declined requests. So that is essentially representation off a state off, a particular object reciting on the silver. And you're transferring it from this over to the client in a former that normal human can understand. And then you have response body, I mean magnified. To get request, you're going to get back with some response. Typical in the form off XML or Jason. All this information would be part of the Esther Dip. It responds body, and that's what this means. An investable architecture. We would use the extra devastated scored in order to show the status. For example, if you're able to retrieve a record from the server, then you're going to see 200. Okay, status off extra DP. Similarly, if you're able to update or put their record using post method, then you'll be able to see 201 created as a status. And if your authorization and authentication is invalid, then you may see the several code for one are not authorized. Now I'm pretty sure that if you're a beginner, pop up services, all this mess sound a little complicated. But actually it isn't. Once we take a look at an example in future, you'll definitely be able to connect the dots and understand what's happening. Well, rest is not any standard. Like, for example, if you're talking about soap, there is a particular form it off a message. In case off rest, you don't have toe follow any standards. But that being said, it's necessary that you need to follow these principles if you want your Web services. Toby Arrest for Web Service If you break this principles, you can. But it is you who will pay the price, so it's always better that you follow this principles. If you want to leverage the benefits off, rest will architecture, the first of which is something called stateless, which means silver or the Web service should not keep any client information because Arabs services publicly available over the Internet and many clients can send request to it if the server stores all the time and information to maintain the conversation state that's going to cause a lot of resource drain. So it's necessary industrial architecture. Every request that comes from the client should be treated as a brand new request, even if the previous request had come just a moment ago. And it's the responsibility of the client to provide all the necessary information in order to process the request. The second principle is so called cashing, which means the plane must be able to store the retrieved data are cash the retreat data? What that means is, let's ascent, I get requests and I got back with some response from the server. I should be able to store that information in the client machine so that if trying send the same request again, the request doesn't have to go all the way to the server. But instruction retrieved from within the client itself. And of course, salvo can configure. How much time should the response be cashed, etcetera? The third principle is called a layered system. What this simply means is your website. We should be able to split up into multiple modules and they can be deciding on multiple servers. But from decline Prospect toe, it has to send requests to only one entity and shouldn't be bothered about all the different entities. So essentially, Klein doesn't have to bother about how the Web services managed on the sour end. It just has to be able to send a request with a your. The fourth principle is so called uniform contract. This is actually a combination of multiple other principles, and the first of which is identification off resource, which we've already talked about. A resource must be identified with a you'll. That's what this means. And then we have resource manipulation through representation. When you're trying to start a record or update and existent record, you're essentially manipulating a resource with the representation you're going to send a Jason Data in order to manipulate a resource on the server side. That's what the Saiz next off, which is self descriptive mess age, and it's something that we're all that we talked about. It just simply means that the line has to provide all the required information in order for Silver to process the request. Next, we have hyper media as engine off applications state or simply Ha dios. Well, to put it simply, whenever client sends a request, the response from the server must have enough information to let the client take for their actions. We're going to take a look at a quick example off at the next slide and then you'll understand better. Next we have playing silver. We just simply means so over, not care about the presentation logic. So it doesn't care about how your data is present there, etcetera. And at the same time, client does not have to take care off. Storing the data is the responsibility off the Web service. So here is a quick example of hyper media as engine off application state, when we get into examples, will understand this even better. But here is what it is, roughly. So whenever you're trying to say, retrieve the account information off, a person has done that phone number, you're not only going to get how much is the balance left, but the soldier has also responded, but bunch off links using which the client can take action. For example, using this, your you can deposit some money are using this you convict drove some money or transfer of clothes. But then, if you don't have enough funds, are few balances in negative, then you shouldn't be prompted with other links apart from the deposit, because when your funds are negative, you should not be able to transfer money or withdraw money. And that's why those links should not be shown well. This is what is hot deals essentially. So when you have a restaurant Web service that follows all these principles, he can say that your architecture is arrestable, architectural and develop services. The rest will be up service. Now you might be wondering, what is the real difference between soap and rest? Web services? Will. You cannot really compare rest with soap because soap is a protocol. It's a messaging protocol, while rest is an architectural style. In fact, he can use so protocol inside the restaurant architecture as well. But again, maybe you would be limited with a maximal data. But what we can compare, though, is we can compare Estelle Web services with so based Web services. So here are some of the differences. The rest is an architectural style. Soap is a protocol so is based on XML and just would support multiple of the formats like Jason XML, Plain text, etcetera. In fact, the plant application can ask server. What kind of data is expecting and based on that themselves will respond. Back with the data at cribbage is an ex similar pain text. Similarly, rest exposes FBI with your mapping while soap Use annotations dressed Walks with Jiao Step technologies like Angular You, Jess, React, etcetera. Combat to Soap. One of the good reasons for that is the presentation of data in Jason Format, which is native to JavaScript. And since there is no overhead off, using XML in order to wrap the data rest requires very few resources. Combat, too, so best architectural and, moreover, rest responses can be cashed by the client, and soap will not support cashing Horrell. Rest is clearly a winner compact toe on my or soap and would allow us to have distributed applications and plan can be anyone who want to see the data from the Web service and our dimension. It is perfect option for single page applications and distributed applications 7. 0301Traditional MVC vs REST API: here is the architecture off traditional spring embassy application. Initially that line or the Broza would send the request to these over server will take a look at Developed a maximal file in order to deter mined the front controller or the dispatcher sold it. Now it is up to the dispatcher Sollett Predator mind relevant controller where it needs to get the call to. And for that it will take a look at the handler map ings that we can figure Handler mapping is nothing but a mapping between a your baton with this specific. So let or the controller the controllable then delegate the call to the model This is where you would have so vicious repositories. Our model objects the goal off moralists toe take the input, process it and then just one back to the controller with the date or the model object The controllable then handled the model object along with the name of the view back to the dispatcher Soviet, the dispatcher Solve it. We'll take a look at the view, dissolve or in order to deter mine The extension of the view. I mean in case of fair use and Js before in stance, the extension would be dark GSB, the dispatches, all that would happen, that extension to the View name and then forward argued that date are the model object to that view In order for it to render and guess off JSP, the JSP would be translated into equal and sold it, which will have went off printed on statements with HTML tags. And ultimately, the suburb would execute the soul it and respond back the HTML back to the client, which will be rendered on the browser in case of up services, though, we're going to get rid off all this view part because we're only interested in sending back the data since RAF sending back the HTML as response. Who in descend the data as part of the extra duty response? And not to mention that since the reason Spring boot majority off these are auto configured . When I say we have to configure handler mapping, we really don't have to because it's all taken care automatically. You don't don't have to configure the dispatches. All that our web dot xml file pretty much everything is taken care by spring boot auto configuration, and we can just focus on things that matter in our example application. The client. The client can be anything it could be mobile application or it could be a desktop application. A Web application. Are another application running on another server. They will fire a suitably request toe arrest FBI. So it is where our application would be running, and the job off for FBI is to respond back. But data in the form of Jason or example, it is up to the plaint what they do with that data. But since we don't have any off this client, at the moment we don't have any client applications like angler Jails or Android App. We're going to use a tool called Postman that will allow us to test our FBI and in this chapter will perform all the crowd operations so that we can understand how we can live Ridge. Yesterday we get posed, delayed and put methods in order to manipulate a resource or the data hope it makes sense. 8. 0302 Installing Postman To Test Our API: as I was mentioning before Web services is all about making use. Officially, the methods I get posed, delete, etcetera. Unfortunately, browse. It is not the best tool in order to test our application, because browser is only capable off sending get and post requests. If you want to be able to use other s stripping methods, you either have to have an application that is capable off sending such requests. Who are he should be installing a tool like postman, which will help us do that. Postmen is a great toe. It's free for personal use, and you can just download and install it just as you were installed. Any other software harder for using chrome you have a postman plug in, But in the reason past, they're claiming that their browser plug in is duplicated, and they were recommending us to download that application. You can download it real quick and install it were able to start application with the stool 9. 0304 API We Will Be Building: Let's take a look at the A P I that we're trying to build as women that are application is about e commerce application. One of the modules off e commerce application is to be able to manage product details, So we're going to expose a product a B I and somebody can actually manipulate with the resources by using following your batons along with that stupid methods. If somebody sends a request to product isn't get, they must be ableto see all the list off products. If somebody sends, I get request with unidentified air as a part variable, then they must be able to see details off a specific product with that specific I D. And if we send a post request to the same mural along with records perimeters, then we should be able to create a product. And in kids, if we wanted to update an existing product, we would use the put method to do the same. And in our FBI contacts, Objects on has the input, not a top date, a resource, and finally we will perform the delete operation using the yesterday Padilla. It mattered, so we will be able to delete a specific product with a specific I D and the idea would be passed as a part of edible. I hope it makes sense. 10. 0305 Create A Spring Boot Project For Our API: Alright, it's time to create our first rest. AP I using spring boot. I hope you're excited. I'm assuming that you have installed Eclipse and Spring Toe sort already. So with that in mind, I'm going to click on the file menu, click on other Search for Spring and I'm going to click Spring Starter Project. We've talked about all of these already. So in my case, these are the values that had entered. I'm going to change the artifact name, too. Spring Greste FBI. The only model that would be needing his spring starter web because your home your mouse over there, you can see that it will help us build rest Philip services. However, if you're building so perhaps services, then you'd be needing this model, and we could actually include a database like a stream but a database. But I want to keep things simple for now, and we're not going to use any data. Best for the time being. Someone hit finish. It's going to take a while for spring to a suit to create the project and sort off important indoor eclipse. And Roman, you can see the progress in bottom right corner. All right, Once you have it ready, we're going to be needing few packages. Some would expand source Main Java and inside here, I'm going to create a package to keep all our controllers. And in this case, we're just going to have one controller. And whatever the traffic that we get from the dispatcher sold it, we will receive it in our controller. So that's going to be controller. We're also going to be needing another package to store our services. So this is where you would have your business logic. We're going to dependence. Inject these objects into our controller in order to manipulate with the data. So this is going to be a service layer and we're also going to be needing model. Although we're not going to interact with database, we're still going to create a model because this is the same object we're going to use. Has command object in order to map Dataquest's para Meters etcetera, you will see them. Why? What I mean and that's it. We have everything in place to get started creating or estate. Be I I didn't be supposed to include one more layer, which is a repository. But since we're not using database, I'm going to ignore it. For now, I hope it makes sense 11. 0306 Get Products API: the 1st 1 shelter that we're going to introduce his to expose an FBI to retrieve all the products available. It was created controller specific for product related requests. I'm going to call it as product controller in Camel case and we want to receive requests. That has slash product in there you are. Someone didn't. Did you say request mapping notation with the falling Patton. In addition to that, I'm also going to make this class arrest controller. This is similar to a controller annotation. The only difference is this time this controller is tuned to respond back with the data and make it part of destiny. P response. Now this is complete opposite to traditional embassy applications where the intent is to respond back with HTML, in which case the controllable respond back with moral and view objects. If you hope your most on the sanitation can see all the annotations that will make this sanitation. So we have controller as well as the response body. So whatever the data that we want to send would be part of the response body. The next thing I'm going to do his stint. Ageism mattered to retrieve all the products available. But before that we need to have a command object, someone to create a product class inside the model, something like a poor Joe. And guess if we had a database, this would be our model. So would have all those annotations to map this particular entity with the relational dead of a stable. But at the moment, we don't have a database, but still, we're going to use this as a command object in order to store the product related data. This is going to have three variables in my case when this product I d. And then we have a string which is going to be product name, went into just one more field, which is and in teacher, and that's going to present the product price. I'm also going to introduce couple off constructors, and for this I can make use off eclipse to do the job for us. I went into juice and know our constructor, and I want to make this private because we don't want to be able to create instances off this class. But since we're going to use this as a Poggio are or an object that holds the data off products. We do need a parametric constructor and to make it public. So if you want to be able to create an instance that's only possible for sending the para meters, you can't just create an empty instance. And of course, we're also going to add garrison centers. I look until shift up to give proper indentation for all cord just to make it look visually better. So no, we have the model object. Next thing is to introduce this always layer. This is where we would have our business logic before creating the classless create. The contract is an interface which set off Matt that someone to call it does product service. So in our case, I'm going to return a list off product, get a draw that's doesn't need any para meters Contra chef Toto, import all the missing classes and interfaces, and then I'm also going to create a class product service implementation, and that's going to implement product service. Let's holds at all the missing unimplemented methods, some just simply going to create a list off products and then return that list. I had a list off product products and Dart had new product. I didn't fire as the long it's called A Die for now is the first product, and its price is going to be saying Triple nine. Actually, I guess no, because it's more expensive. Let's make it one Triple nine. I would add a couple off more products. You were unique art and fire. We're doing all this because we don't have a database and this is going to be, say, a speaker. Cheers off, say, 5 99 And then we have a maybe a book just say $99 and written all the products inside the controller well before that. That's made this a service because we want us to be auto discoverable with Springs auto scanning. So the spring will country got this bean by itself. That's no dependence. Inject us product service inside our controller control shift hole auto writing. Now let's introduce the method, which is pretty much is going to have the same signatures. I'm just going to copy it over here, and this is just going to respond back with all the list off products available. We also want toe annotate. This mattered as get mapping because we wanted to receive all the get requests from the client, and of course, we want to return them. Couple of things to note here is that the records mapping annotation doesn't correspond to any specific history be mattered. So all the requests are all the euros that has this. That particular string in them would end up in this controller. And inside this country, we have methods specific to has to do the math. That's in this case we're trying to map with all the get requests. So if we send a get request with this particular string in the your Erica's would end up in this method. Also, this control annotation comes with response body, so you don't have to declare response body annotation in all the methods in this class. So that's another advantage off using the rest controller annotation. And I guess, with this, we have everything in place to test our application. Let's run our application. If you created the project, using spring to suit should be able to locate this file, just run it just as you would run any other Java program. I don't have any errors. Let's open the postman application if you're using a postman for the first time you may be feeling a little intimidated looking at the interface. It looks very complicated, but but trust me, it's very user friendly interface. Only thing is that it will take a while for you to get used to. So as we progress through this course, I'm going to talk about radio speeches that the stool has to offer and thereby you'll feel comfortable using this tour by yourself. So can you guess watching with the You are here. It's going to be local host 80 80. That's where ourselves is running in product. Let's send the request. But before that, do make sure that you choose get as a method and see it did work, he wrote. The list off products returned in Jason Format. 12. 0307 Get Specific Product: The next thing that we're going to do is to have the ability to fetch a specific record or specific product information. So first, let me introduce the intra first mattered for our product service. The method is going to take long ideas. A perimeter. This would correspond to the product I d and is going to respond back with that specific product if it is available. Let's go to the service implementation and provide the behavior. And here we have it. What we have here is we're trying to search a specific product in the list off product. Now, this is all core Java. I don't think I have to walk you through this code, but here we have a never because we're trying to access a list that is not scoped within the class. So let's move this list out off the matter and put it over here at class level. However, we still have a problem because the list one repopulated unless we first request all the list of product. So let's make this court a spot off the constructor. We want to create a constructor real quick and let's populate the list. Control shipped. Oh, control shipped F. And there you have it. And inside the controller, we already have this always dependence injected. I'm just going to introduce another mattered. But this time we have something called a path variable. Because from the client we should be able to send the identifier. Let me get this real quick and that's it. So if you want to fetch a specific product detail, then in addition toe having this particular, your mapping should also provide Dad into fire. Let's relaunch your application and see how it works, so I have the exact same request. But this time I went up and the identify ire. Let's say I want to fetch details off iPhone, so I would say one, and it has retrieved the information of that specific product. 13. 0308 Add Resource With Post: Let's take a look at how we can create a resource with post request. First, let's created matter in our intra fess and here it is. It's not going to written anything, but it's going to take in these perimeters which will help us create a product. And here is implementation for the same. All I'm trying to do is to add a new product. But taking in all those arguments an insider controller, I went into juice and method with post mapping. So all the yesterday people streak was would end up in here. This method is going to take in three para meters and these are essentially the request para meters that we would send from the client. This is as good as receiving the form. Enter data from declined and all we're trying to do here is to create a product. We're just calling one of the service methods nor to create a resource. In addition to that, we also want to send some status back to the client so that the user would be aware that the resource has been created. So for that I created a map with string as a key, an object as value. I'm trying to populate one off the map elements, which I'm sending back as a response. And all these map entries in this case is just one would be rendered as Jason response on the client machine. So let's take a look at how we can send post request from our client. So this time going to chose post and I'm going to go to body dab and click on form data. So this is essentially going to simulate submitting a form from the Broza. So we need to send this perimeters I d name and price with the exact same name I d. Name and price. That is going to be a unique value. How's therefore name is going to be, maybe washing machine or whatever price, some random number. Let's try sending the request. Okay. We seem to be having problem because we're trying to upend this para meter. Let's get rid off it and send the request once again. Oops. I completely forgot the fact that went to restart our application. Sorry about that. And let's go back and send the request once again. And this time it worked pretty well. So that's how you would send a post request. You know, next example will take a look at how we can send Jason as an input as part of the request. 14. 0309 Update With Json And Put: Let's take a look at how we can perform an update. Often existing resource who went into just a matter inside out interface and this is going to accept product has the matter argument that's also provide implementation. And all I'm trying to do here is I'm trying to find the product with the specific I D and find update its fields in this manner again, this is all core Java. Let's go to our controller. And this time we're going to introduce put mapping annotation because we're going to use the actually put method in order to perform abdication. And here's something new. We're trying to use the sanitation request body because this time I'm not interested in sending because para meters like we didn't gets off post. But instead, I would like to send Jason as part of the request body. So by specifying the sanitation the Jason body would be mapped, our would be binding to this object in here. So ultimately the Jason would become rooted into product which will use in our cord. And I'm also returning the same object which will be rendered back in the form of Jason off . Whatever the client requests Well, the tricky part is how do you send the Jason data from the client? Let's take a look. So I have to send Rick questions in this you'll. But this time it's going to be put history view method. But before that, let me make use off to get method to extract all the product information. I haven't started my application. And so you're seeing that editor. Let me quickly copy this control. See that said that I wanted to update this particular product iPhone. Maybe he wanted to change the name to something else, so I just cooperated. Let's go toe put method click on the wrong to enter the raw Jason. I'm just going to past in whatever I had copied. And I want to name this as maybe my phone or whatever the matter. One more mine and let's send the request. You seem to have problem and it stays content. I plain text not supported. Okay, The problem is, we're trying to send this as a plain text while on the other end is expecting Jason. So let's select the content type as Jason try to send it again, and this time it worked. The field has been updated. Let me do get request again and see if it has indeed updated. Sure enough, it did. 15. 0310 Delete Resource With Delete: Let's take a look at the delete operation as well. The lead operation is pretty straightforward, so we're going to have a method that's going to accept the I didn t fire, based on which we need to find the specific element and dilated. And here is implementation that does a job. I'm trying to remove an element from the list, and I'm making yourself the one of the matters that were written. Get product by I. D is going to return the product, which will get deleted ultimately inside the controller. The court is pretty straightforward. We're just going to accept one part variable bills down, that we're going to delete a specific resource and again in order to show some status. We're just populating this map and returning it. Let's test our application. So this time I'm going to use delete. Before that, let me get all the list of products available. Let's I want to delete product with I D one delete and going to send one as perimeter and item got deleted. Let's try to verify it, and sure enough, and got deleted 16. 0401ContentNegotiationIntroduction: Let's talk about content negotiation, industrial Web services. We already know that in case of rest, API I decline can be anything. It could be a JavaScript application. It could be a mobile application, or it can even be traditional embassy application. In case off traditional embassy application, the brother would send the request, and it would expect esteem allows the response from the server in order for it to render on the browser. But in other cases, the former can be different. For example, if you're talking about adjusted application, it would expect this over to respond back in Nader XML or in Jason format. So it's not specific what kind of format that the client needs. In this case, it may not be ideal to configure a specific format on the server side. Instead, we want to leave that option to the client to specify what kind of format it is expecting from the silver. And at the same time, server may not be capable off sending in any random format that ever existed. So there are certain limitations on the server side as well. If the train's request for a format that silver doesn't support so we would just simply respond back with an error. So this mechanism is called content negotiation. So how will this over know? What can a format that the client is requesting for? Well, there are three different mechanisms for that. The first off, which is so called part extension, would just simply means that the client would specify the format as part of the part extension, an example of which can be seen in here. In this case, the client is requesting list off products in the form it off PdF, and so we would be able to determine that by taking a look at this extension. If the server supports pdf format, then the server would respond back with PdF as a response. Similarly, the trying can request in Jason Format, in which case there would respond back in the format off Jason. Another approach is by using a Ural Param Eter, an example of which can be seen in here pretty much same as the previous one. Except we're not going through the Part Extension institute include a your Param Eter with the name format. This is customizable, by the way, and we'll take a look at it in our example. So in this case, client is requesting for the PDF format and here Plant is requesting for XML format. Yet another approach is to include a history dp axa Petr, obviously, Gandhi's browser. In order to include Scdp headers, you have to use the to like postman our JavaScript in order to do so. But essentially watching it to do is to include a property as part of this today, beheaders and the name of property is, except which does the server, what kind of format plant is willing to accept, and the value off it is going to be the format that the client is willing to consume. Once we take a look at an example, you'll understand this better. Let's talk about message. Can voters first of all, what is a message? A message in Web services, simply a request, our response, having information to process or retrieve the data? I mean, when you're sending as to directly from that line, that's called a message. It's called a request message, which will have enough information for the silver to process and respond back with something. And when silver response back with something as part of the yesterday. P response. It's called the response message, but how does this conversion happen? I mean, you've seen in our crowd example that we're able to include Jason Data as part of the request, and the solar is able to convert that Jason Data into a job a model object in order for it to process. How does that conversion happen? Well, that is with help off this converters. In case off Jason, we have a specific on motor for that. Similar. We have a converted, for example. Similarly, for all the other formats, marshaling would just simply mean the process of converting the Jason or XML or representation to Equal and Java object. And we've seen this example when they're trying to send the Jason data from the client and sort off abated at record on the server side and the opposite off it is called on marshalling, which assembled the process of converting job object back to the representation. I mean, when the controller is returning a moral object, somebody is trying to represent that object in the client requester format like Jason or XML. That mechanism is called on marshalling 17. 0402HTTPHeaderContentNegotiation: Okay, let's first explore Hester deeply. Head away off country negotiation. What I have here is our crowd FBI that were developed previously. The first thing that we need to do is to go to bomb the XML file and add this dependency by the fall. When you create a springboard project with starter Web dependency, it comes with Jason Support. But if you want to be able to represent your data or the resource in XML format, then you have to add this additional dependency. Other worst things may not work as expected. Once we had this dependency, do make sure the job did the project so that those libraries would be present in your class part. Let's run our application and see how we can configure yesterday beheaders and specify the except property. How it again go to postman, the missing the request and by default, it's going to respond back with Jason Data. But let's say that I wanted to have this next symbol format. I go to head a stab and out, specify the property, except you already have it populated. Just click it and you were specify the content type. In this case, that's application and if you notice they're a lot off options in here, you can choose one off them. But of course, your Rabia has to support it as well. In my case, I'm going to change this to XML. And now, if a fire, the request, everything is shown in XML format. So what has happened behind the scenes is when I send this request, spring is going to take a look at STP headers, especially this property in here. It can then figure out the expected media type that the client can, except in this case, it's application slash example cantons. We've added this library has part of from the XML file. We do have an XML can water that can convert our job, object into a bunch of facsimil tags and using that converter, whatever we're trying to respond back in here. I'll rather here would be converted and represented in XML format. And that's what we're seeing in here. And from this point on, for all the request, the content or the responsibility present, that in XML format 18. 0403RequestParamForContentNegotiation: Let's take a look at how we can make use off. Request perimeter for content Negotiation by default. This feature is disabled, so we have to enable it with our configuration. If you're not using spring boot and you're developing spring applications the traditional way, then you have to introduce quite a bit of configurations. Edgerrin Java Contra Gar in XML conflict. But with spring boot, things are going to be a lot easier. All you have to do is to add this properties inside application, not properties File. If you created the project isn't spring toe suit. You should be able to look at this file under resources folder. So with this property, we're trying to enable that feature. And with this property we can customize the name off that Param Eter. This is optional. If you don't specify this property, the default name would be format. But in this case, the perimeter name has to be media type. Let's take a look at how we can use it. Let's relaunch our application. Got a postman this time I'm going to include this as a perimeter. Currently, I have Hester DP headers as well, and I'm tryingto except XML as the format. But let's see what's going to happen if I use a perimeter and make it Jason. Well, it looks like if you use the perimeter, then this will have preference over yesterday. Beheaders. So if I change the stool X Emma response Woodberry presented an XML format regardless off what you configure in here. 19. 0404PathExtensionContentNegotiation: Let's talk about part extension, way off content, negotiation by default. That feature is disabled, and if you want to enable it, just have to have this property inside your application or properties file any to set this flag to True. From this point on, it should be able to do content negotiation with extensions. And this will have presidents or the other two methods that we had talked when I tried to test our application. After configuring this, I noticed that our application is not working as expected. When I checked with one off my associate, he conform me that this is an existing bug in spring framework, and the team is actively looking at fixing it. But ideally, it should be able to append an extension like dot Jason or example, or pdf or whatever. And accordingly, you should be able to see the response in specified format. You can give it a try. Maybe by the time you're watching this video, it may have got fixed, but do make sure that you got the latest washing off spring frame book 20. 0405ContentType: just as a silver is able to respond back with data. And where is different formats or media types meant Lankans and data invaders, different formats and several must be able to receive and process it. One of the cases where this might happen he's been client is trying to aid their update or creative resource. So let's tried updating existing resource going to go the Postman. And he wrote the list of products available under the spare in XML format who into copy one off these because I want up that this particular record change the method to put inside the body. I want to change this to something else, whatever and if I tried to send the request going to see another says the content type not supported the real cause off. This error is that so is notable to pick the right converter to convert the XML into Java objects. So plan has to specify the type off content it is trying to send by adding one additional header. Could the name content type and then you were specified, the type of content you're trying to send? Not this time it worked 21. 0406ProducesAttributeAndPDFResponse: I was mentioning before that we can have restrictions on the silver side as to what kind of media type that it is capable of handling at the moment. Or get mattress capable of responding back with either Jason or example. But let's say for some reason I want to restrict it toe respond back with only XML data or , said Jason, how do I apply that restriction on this method? Well, it's by using the property producers and your specify list off media types, but this method is capable of producing. The reason why you're seeing the Serra is because when you have more than two attributes, then you have to provide value for all that attributes that are present in the sanitation. So this is going to be value. So now this method is capable of producing a drove this media types. So this matter, essential is going to exhibit pretty much the same behavior as with our previous examples. So let's try to apply restrictions and say that this method is capable of generating only Jason media type that saved the file and run it. Let's go to Postman and if you send the request is going to work because Jason is supported this chain the except Header to XML and see what's going to happen. You're probably going to see another and it says could not find acceptable representation with four of success Reppas Staters. So that explains you can also have this attribute added at class level so that it will be applicable in all the methods reciting in this class. One of the cases where this might come in handy is when you want to call a specific method depending on the type of media type that it can handle. So let me desperately copy this. Obviously, signature has to change something else and let me change this to XML, for instance. So now we have couple off methods. If the client is requesting for Jason Data, this method would be triggered or if the client is expecting XML data then replaced would end up in here. That's really want our application. And this time we shouldn't have any problem responding backward Maximal data. In this case, however, the behavior off board this method is exactly the same, and this may not imply a real time scenario. So for this part was in order to demonstrate. I'm going to introduce him Method that's going to respond back with a pity of media type. I already have the cord copied just to save your time. And here it iss. In addition to this, I've also created a pdf file and have put it inside the resources folder under files. You can put any content inside the speedy if it doesn't matter. But what we're trying to do is when we try to send a get request requesting for a pdf media type, then this method will be triggered and ultimately isn't streams were trying to respond back , but pity of data. Now, I really hope that you don't expect me to walk you through all this cord. This is all core Java. All we're trying to do is using streams. We're trying to read that file and make it part of the response. Isn't this response into the class you'll see more examples off response entity in coming times. So here is a PDF file We're trying to pick from the class part, and then I'm trying to add a header which is basically the size or the content length off the pdf file will be able to see this header as part of the response Headers and I'm using this response and did the object to sort of create the response with headers as well as the status code that's real on your application. And this time XML would obviously fail. Let me change the headers, the acts of terror to Pdf and send the request again. Well, if you notice you don't see anything in here because Postman client is not capable of displaying the period of content. But you can say that it has worked because off the status scored toe wondered. OK, Along with that, you'll also see the header, which is a constant length off the PdF, so that explains. 22. 0407AcceptEncodingForCompressionAlogrithm: Let's talk about compression mechanisms real quick. In our case, our application is running in the same Horst and even the response his Justin few lines. However, in real time scenario, the summer might be reciting in different geographical location, and even the response can be in hundreds off lines, in which case it takes a vile for the response to be transmitted over the Internet to the client. And if there are millions off request to the server, it's going to cost a lot of bandwidth and delay in response. You know that that just this issue, we have compression mechanism in place. Let me show you what I mean. If you go to the network stab, you should be having same tool in chrome as ville, and I'm guessing that you're a better off it. To take a look at the response, you would notice a request header that says, except and according and specifies a couple off and courting mechanisms are including algorithms that the client is expecting server to use in order to compress the response. So, using this header, Silver is going to pick one of these algorithms in order to compress the response so that when the response reaches to the client plant is going to use the same old guard. Um, in order to decode the response and render back the media in this manner, it's all taken. Get automatically. You don't have to had any additional head us or anything of that sort. 24. 0502CacheMaxAge: Let's take a look at an example off cash mechanism in order to simulate a real time scenario. Imagine that we're trying to access a weather forecast. So with where? I'm trying to fetch the current temperature off my location so I would send the request, the question for this resource get temperature and then the sober would respond back with the falling data, the current temperature as well as the time at which I received this response from the server. We're going to need this information just so that will understand the concept better. Now, you're not any astronaut or something that you need to know. The very precise information. It's okay. Forget the data that is, like 30 seconds old. So what we're going to do on the suicide is when we respond back with this data, we can instruct the browser to keep this information in its cache memory for not more than 30 seconds. So let's take a look at the core and try to understand it. What I have here is the crowd example that were talked about in previous chapters. In addition to that, I just introduced this new method with the falling mapping get temperature. I'm using this class cash control in order to specify the cash static tooth in this cousin specifying the max age and setting it to 30 seconds. He considered any time off your choice. This could be 30 minutes or 30 years or whatever it is. But do make sure that it makes sense based on your scenario. And I'm trying to gender to random number between 10 to 60 isn't the Java's math class. This is to simulate the current temperature. And ultimately I'm just trying to create a bunch of esteem attacks with all these details integrated so that the user will see the response. I also included one hyperlink, which does nothing. And when somebody clicks on this, it would pretty much request for the same resource. And finally I'm using the response entered the object in order to set the status as well as we are specifying the cash control directors. So ultimately, this would be part off the response headers. I'm also start off sending the string as part of the response body which will be rendered on the browser. So with this, let me reload the page. Regard this current details No no matter how many times he would send the records, you would see the same response because all these details were actually fished from the local cache memory, not from the silver. However, if you wait for 30 seconds, you would get the fresh details, because by that time all these details would be expired from the local cache memory. So let's wait for 30 seconds and there you have it. If you go to the network stab, you would notice that there is a header response center that saves cash control and max. Age is set toe 30 seconds. This is what I was talking about. There might be certain scenarios where you don't want to store details in the cache memory , for example, so that you're trying to perform some transaction. Maybe you're trying to send funds to your friend or whatever once after you send funds to your friend in to see the econ balance reflecting immediately, right, you don't want to send say $100 you see in your record that nothing has changed. That would be very inefficient, and it's going to result in bad user experience. So there are cases where you don't want to store the details in cache memory, especially since two data and there are scenarios where it's OK to store like in this case . 25. 0503ETAGTheory: In some cases, it may not be ideal to let the silver decide as to how long should the resources be deciding UN declined machine, for example. That's declined, is requesting for list off products now on the solar side. We cannot have a fixed value. How many? Can't say we want this to be reciting there for 30 seconds or 30 minutes or whatever, how we're having a mechanism where client will try to fetch the resources from its cache memory, But before doing so, it will take constant from the server to check to see if there are any update on that resource. If there are any updates than several would respond back with the latest details or the data. Otherwise, I would just say Go ahead and fetch from your cache memory because they're no updates, and that's where e tag will come into picture. So the way it works is initially the first time somebody visits a website to take a look at a list of products. Let's say client would send the request so we will fetch all the list of products available from the database and before sending it to the client. So what would apply the hashing ill, guarded them on the response and create a string that looks something like this. This is essentially a string that's going to represent that resource. You can think of it as a unique value that represents that resource. You can explode about hashing mechanism if you wish, and the Southern would make this cord as part off the E tag response header along with this off course. So we will also send the list off. Product has part of the response body, but the next time client tries to access the same resource before fetching the products from the cache memory, it will send a request to the silver with the falling header. If non match, with its value being the same hash code that was received from the server solvable again tried to fetch the resources from the database applied the hashing ill guarded them to create a hash rally something like this, and it will see if they both match. If the boat do not match, then that means there are updates on the requested resource and so the sub over respond back with a list of products. As part of the response body. However, if these two hash code matches then so would just respond back with three or four response code without including anything in the body. So that way, trying to signal that whatever is the resources that it is requesting for the same as the resource that it is already having in its cache memory. So plant would just simply fetch all the data from the cache memory and would be rendered. The idea here is that, and there's no change in the request resource, so it doesn't have to send a huge chunk of data. Instrument can just respond back with the state of scored, which is pretty lightweight, and it's going to save a lot of bandwidth. This mechanism does come with a drawback, for example, for each and every request. So what still needs to fight equity in order to fetch the requested resources, which will, of course, cost some performance on the suicide, But still it would save bandwidth as well as the response time. The next thing that we're going to do is to take a look at an example of the same 26. 0504EtagExample: Okay, let's take a look at an example off E tag the first time. A request for the resource in this case I'm trying to fetch all the products available. I should be getting toe under focus status and the response header must be having the e tank with the hash off the response. Along with that, he would notice some of the head of it says Cash a control. Set it to know Kasia. Earlier, we had said this to Max Time, but this time we had said this to no cash, a meaning that we won't declined to come from with the server before it can fetch the resource from its cache memory. Let's go to our eclipse and see how this court is implemented. I know having to just a new method where, and I'm tryingto send list off products, available a spot off the response entity and have no said the cash control to know cachet. And that's what you're seeing in the response header. But the key thing to notice inside your conflict file, you have to introduce this shallow it I had a filter because this is the thing that will do the job off actually hashing the response internally, This is going to use all the filters to start off perform this operation. You need to have this being defined inside a contract file. Whether it is Java conflict are XML conflict. He must have this being defined. And once you do so, everything will be taken get automatically. And the second time you try to send the same request again. A custom for the same resource. This time you got three or four status from the server. And if you notice, client has also sent that exact hash with the key as if none match Exactly. The stuff that we talked about earlier, so so would compare this particular value with the hash value off the response and would save the both are same. In this case, the both are same and so so has responded back with three or four status. Otherwise, that would have just sent all the required resources. And that's how Anne Tank would work. You can perform the same operation in Postman climbed as well. Only that you have to manually send the request header. I mean, you just have to copy the e tag and when you send the second request from the client, you just have to include that e tank while us part of the if none match request header. Hope you understand what I mean. Also, I was mentioning before that this is still going to cost bit off performance on the solar side because no matter how many times you send the request for the same resource, so we'll still have to fight acquitted to the database in order to fish the resources and apply National Guard, um, to create hash value of that response, the better approach is to actually do something on your own. Because unfortunately, spring does not have such support. Our of box, you have to come up with something off your own. One of the approaches, which I had followed earlier when I was working in one of the projects, is that we maintain the hash map, and every time there is an abdication off a resource in the database, there's a hibernate trigger or uneven that kicks in, and we'll upgrade that map along with its corresponding hash value. It gets really complex, and there is no sure shot way or the best way to do it. It is up to the individual preferences. Have you come up with a solution that would solve the problem so that someone doesn't have to file quit or the database instant? It can just validate the hash value by checking a map or something of that sort. Hope that makes sense. 27. 0505No Store,Public,Private: I was mentioning before that we should not be storing literally all the resources in all the cash members that come away. In some cases, it may not be ideal to even store the resources and cache memory, while in some cases it might be okayed a store on the client machine, but not on any intermediate nodes. Well, the way you control that is about using these response headers. If you're setting the cash control to know store, then that means we're not going to store any off the response data in any off the cache memories. This may be true in case if we're performing any banking transactions where the information that is being exchanged, maybe too personal to store them in the cache memory. If you made the cash control toe public, then that means we can store that resource in all the cash memories, not only in decline Mission but can also be in any intermediate note like CD in a proxy server was etcetera. If you said the cash control toe private, then that means we only want to store them on the client machine and not on any intermediate notes. This may be applicable in case off e commerce websites where maybe you're adding certain products into your cart, and it may not be ideal to store all those product details in some common server and only store in the client's machine. So that's how you control how we're going to store the data. Hope it makes sense. 28. 0601PatchAndSendingMap: Let's talk about Patch or partial update in spring rest. FBI. We're also going to take a look at an example of the same, but first, let us try to understand the difference between patch and put. Often times people get confused between these two, and they don't know when to use what. So let us try to understand it with the real world example. See that you wanted to manufacture a product. The first obvious thing that you would do is you would order all the missionary required to manufacture the product from the supplier. Let's say that this is a mission that you are ordered, and you found out that one of the parts is not functioning well now. Would it be efficient if you ask this of player toe, replace the entire unit and bear the shipping cost again? Are would have been nice if you ask this a player to replace this plastic part, which is affected. Obviously the second option right? That's the basic difference between Patch and put so far in our previous examples when they're trying to perform the put operation, were performing up addition off the resource, but behind the scenes were actually replacing the entire record. But whereas with the patch, what we're going to do is that we'll update only a particular field, which requires subdivision. If you want to understand the difference in more technical fashion, as you know that you have Jason with a person bank details so you'd have the balance, you'd have his age name, gender company, etcetera. Now let's that you want to update the age off that person. If you use the put mattered, you'd have to send this entire Jason pay lord just to replace one particular field. But with Patch, you can only send the field where you need optation. You don't have to send the entire Jason or said wanted here. The obvious advantage here is you would be able to save the bandwidth because you don't have to send the entire Jason payload and you're sending only a specific field. Very require abdication. Let's take a look an example of the same. What we have here is our previous crowd example. So we have get mapping, post mapping, put mapping and delayed mapping to perform crowd operations. Now we have additional method, which is patch mapping to perform partial addition this method is going to accept couple of para meters. The first off would is about available that would be sending from the line, which is the identifier. This will help us identify a specific product in the database. The second battle meter is list off key value pairs, which is basically a map. The key would correspond to a particular field off the product, and the value is the value that you want to replace for that particular field. What we have here is core java. I'm trying to use the reflection FBI in order to replace of fields for the fished product. And, as you know that I don't have to walk you through this cold Java stuff. You can pause the video and take a look at the score. If you have any questions, you can ask me. Finally, what we're trying to do is we're trying to just simply update that particular product with the final product object that we create. Let's try to launch our application and see it working. I'm going to go to the Postman client, have cleaned up everything just so that you'll have a fresh and Roman to work on the first thing that I'm going to do is to retrieve list of products available to a local host 80 80 and and believe it's get products. When did you simply copy this and send? So he wrote the list off products. Let me fetch a specific product, which is going to be this All right. Now let's say that I want to perform partial a bit on this particular resource. Maybe you'd like to change the name to something else. Let me just copy it. This particular field Let me switch the method toe patch yesterday P method and inside body window choose raw. And here I'm going to send only the fields. But I need optician in the scarce. I'm going to call it as new iPhone. Let's fire, gets fired the request and see what's gonna happen. So it has returned unsupported media type. Let's go toe headers and change the content. Type to Jason and send the query again. And this time we got to wonder. OK, and if you try to retrieve the product once again, we should be seeing the name getting updated and sure it is. I'm going to make this court available for you to download so that you can experiment with it. Hope it makes sense 29. 0602IdempotencyAndSafeMethods: Let's try to understand safe and I damn bored and met. That's Nestor DP First, let's talk about what are safe methods. A method is considered safe if they do not have side effects are if they do not cause any state change on the solar side. Let me explain what I mean with an example. Consider the get matter. For instance, all this is going to do is to retrieve an existing resource. In this case, I'm trying to retreat a product with a particular island fire. This is not going to perform any update, our creation off resource. So this is just a read operation and is completely safe. I mean, no matter how many times you fired the same request, it's not going to cause any side effect or it's not going toe cause any state change on the server side. However often developers would like to log some information along with the times tramp as to when the request has come, that is considered safe because it does not have any negative consequences on the solar side. However, coming to posed, if you try to fire this request along with this Jason Data, this is going to result. In addition, off a new resource on the silver side, which means this will potentially change the state on the server side if you find the same request multiple times, this may result in creation off multiple resources. Our multiple products hence post method is considered not as a safe method. I'm pretty sure you must have experienced whenever you're trying to re submit the form on the browser for the second time. Rosabal Trey warning. Prompt asking if you would like to re submit the form Well, this is the reason for that Post is considered not so safe. And so browsers kind of giving your warning whenever you try to submit the form for the second time. If you want experiment with it, just try to fill any post form submitted and tried to reload the page. You would see that warning from the browser similarly put is also considered as not a safe operation because it's going to result in state change. Your essentially trying to update an existing resource. Same is the case with delete. The same is the case with Patch, so the only method that is safe is get. There's no talk about, I'd impotency off a method. Hired impotence is a little bit tricky. It states Multiple identical request should have the same effect as a single request. Let me explain with an example, Let's consider. Get for instance, no matter how many times you fired this query or the request, nothing is going to change on the server side. So obviously this is I'd impotent. But let's talk about Post. He fired the query for the first time. It's going to result. In addition, off a new resource. You going to find the same query or the request for the second time. That's going to result in addition off a new resource. And if you fired for the third time, a new resource will be added. A new resource will be added every time you send the post Request. Hence, post is not item, but in method. This talk about put Matt the first time you send this request. It's going to replace an existing resource. And from that point on, no matter how many times you send the same request, it's not going to change the state on the server. Everything would remain same only for the first time it might change. Hence put is I'd impotent. Same as with delete only for the first query. It's going to result in delicious off resource. But for all the subsequent query, you're going to see an error because the resources no longer present. No matter how many times you find the same query, it's going to get back with the same result. Let's talk about Patch Patch in this case, his ID imprint. But the Pats prescription does not say that it has to be. I'd impotent because coming toe patch. Unlike put where he would specify the entire resource that needs to be replaced in batch, you're just specify some instructions as to how to identify resource and what feels or what abduction is to be done. So it's not guaranteed that the patch will be. I'd impotent if you're using any tour party, FBI. And if you want to fight a patch request, you'd have to be careful that it doesn't necessarily have to be hide impotent. For example, you could have a patch request having instructions to increment the age of the employees by one, and if you want to send the same request multiple times, it's going to result in incriminating the value every time you send the request. In which case Patch is not I'd MPA tint. However, in all likelihood, in most cases, Patch is I'd impotent, but it's just not guaranteed nobody. There is no specification that states the patch has to be identified int I hope it makes sense. 30. 0603FileUploadAndDownload: the straight. Understand how we can introduce, upload and download features using springboard dressed FBI in the process. We're also going to explore so 10 crucial concepts in the state p i that maybe off helpful to you. So here is how our A P is going to look like will have an upload endpoint, which will help us applaud a single file. And then we have upload files, which will help us applaud multiple files. We also have an endpoint for download, and here are the steps that made to follow. First wanted to have a springboard project a very basic springboard project with spring Web started dependency will do just fine. In my case, I'm just going to use one off my previous projects where I created crowd application. And after that, we're going to introduce certain properties that will help us upload files and then off course will write the logic both controller and service logic to perform the upload and download our operation. So let's go to Eclipse and Roman and see how it's done. And he wrote the set off properties, which needs to go inside the application or properties file. The first off which is to enable so called multi part file uploads by neighbouring this Sprinkle helpers upload the file in multiple parts. Which means said that you uploaded at 10 MBI file. It would be split up into multiple parts, and each part will be flushed into the destination file system. But for that we do have to set the threshold, and that's what this property is meant for. File size threshold. So for every two K B, all the bodily date off, the uploaded file would be flushed into the destination file system. And here we're trying to set the maximum size off a single file with this property max file size and then with this property Max request size. We're trying to set maximum size off all the files combined while sending the request. Now let's take a look at the controller logic. For now, let us ignore the downward file functionality, and let's just focus on applauding violets. It is a logic that will help us upload a single file. This mother is going to accept one single Param Eter with the name file. This is basically the file that we went up from the client specifically from the Postman Klein, and it's going to be off type, multi part file. And in order to actually store this file are binary data into the destination directory. I had created a service with this Method store file, and all we're trying to do here is we're trying to just simply use one off the Java libraries and using one off its method copy to copy the stream off input onto the destination or the target location. And while it isn't stance off, this class is created inside the constructor. I'm also trying to populate this property, which says, File storage location and I have explicitly hardcore did the value where we want upload the files in real time projects. Your mont heart. Cordes maybe want to read it from the properties file itself, and we also have a check to save. The file contains any illegal characters or whatever. You can have as many validations as you wish. But that's not our primary focus here. And in case, if you have any exceptions, you may want to handle that exception in some good way by creating a custom exception. In my case, in order to explain things better, I just kept things simple for now. And finally we were just returning back with that exact file name. And after that, we're just trying to populate upload file response object. This is just for response. This is the response that the user or the client will see. Once we take a look at the example of the same, you'll understand this better. So let's go the postman and try toe upload a file and see the functionality working. But before that, let's run out application. So here is a postman client again. I cleaned up everything just so that everything looks clean. And in here I'm just going to say a local local host call in 80 80 slash product upload and that's it. Inside the body, I'm going to simulate submitting a farm with a file upload sensor off. Next, I'm going to choose a file. And when did you lose the fires specifically for this purpose? I've actually created a folder with these two files, which we're going to experiment with. And once I upload the file, this is the destination folder. Mary. Want to sell what? Upload the files to someone to choose one of these files? I went to give the name. It has to be exact same name. Whatever the request. Bottom we had configured in the end point. We seem to be having an editor and that say it's failed to convert type, string and required type long. Okay, this is going to be a post request, not a get request. All right, let's go back to eclipse and see what's going wrong. So it's product slash It's upload file, not upload me. Copy this. It's just a type wetter. No, it worked with it. Wonder. OK, and if you go to the destination directory, you would indeed find that file applauded. But if you notice the response, we have some details here. This is a response object that I was talking about. So here I'm just trying to populate that response object upload fire response, which is simply a Poggio that has all the details that we've just seen in the response. And here I'm just trying toe calculate the download. Your I went to take a look at the download file function out in a while, and ultimately this you are I would show up in the result, so I can just simply click this and download the file. But before that, let's try toe experiment with multi file upload, and for that we're going to make use off this endpoint. And inside this method, I'm just trying to use job way it streams in order to call this method for each and every file that got uploaded to this time we're going to accept and a day off files. So going to say, upload files and with me, apply multiple files and send the request. And this time you see a couple of files getting uploaded and since filed one was already uploaded. It got replaced because if you remember inside ourselves logic, that's what we had set to replace the existing file. If it was all that existing, I hope it makes sense. No other straight explored the download functionality. This matter is going to accept one part variable, so we're going to use a template variable. So this right here is what we're going to read as part of the path variable. And once we have the file name, I'm trying to load that file as a resource. Let's take a look at what's going on in here inside this matter. We just have some logic that will help us read the file as a resource which is providing the final name. And then we're trying to create a resource object out off it so that we can work on it, and we're just having some validation here to see if it really exists. Others were trying to throw an exception in my case. I just commented the thought, but you may want to handle this exception in some meaningful way by creating custom exceptions or whatever. Continuing on this logic, we're trying to determine the content type of the file is the Pdf is a text file, or is it image or whatever? We're trying to do it remind that so that we can respond back in the same format. And ultimately, again, we're just trying to use the response object to send back the details along with the resource as part of the response body. Let's go back to Postman and just click this link consent. Not sure why has it taken so much time with me? Cancel this try to recent Oops, my bad. We have a debug point right here. Let's get it off this. Continue with our execution, and we got 200. Okay, That means file is available for download. And here is the text Inside that fire. You can also try the same, but in age or any other file formats. I'm going to make this court available for you to download so that you can take a look at it, make some changes and experiment with it. I hope it makes sense. 31. 0701ErrorHandling: Let's talk about exception handling in spring rest a P I. First of all, why should you handle exceptions? Well, here are some of the reasons why you should handle exceptions gracefully. The number one reason is you don't want to show the other message on the you I to your user because and use that doesn't care about the error. If you show every specific messages on the you, I to user may get annoyed and so bad user experience. Instead, what you'd like to show them is an error page. It's a meaningful message that the user can understand. Number two reason is, maybe you would like to send a customary message. Our response especially. This is true if you're talking to another Web application from your application, in which case you don't want to receive standard http Error response Institute like their message to be represented in some meaningful way, maybe in Jason Format or next Emily, depending on your needs. Yet another reason is you may want to log the exception in case often exception so that at later point off time, developers can trace the error while trying to debunk the issue so typical inside your controller will have all these mapping methods you could introduce strike at blocks in all these methods and handle exceptions. But that's going to introduce unnecessary corded and Nancy. Instead, it's better to have all that exception handling mechanism in one place and that it's possible with the sanitation exception handler. He would specify the annotation just about the method. Sick nature. And you would list on all the list of exceptions for which you want to have a handing logic inside the mattered. He can do whatever you want. Miskell. Inside Here you may have logic Teoh respond back with an ever view. It's a message that the user can understand are you may want to send the response entity, which is what we're trying to do in this case with the custom matter object. We'll take a look at an example so that you'll understand better, and this method can actually take inability off para meters. You can also ask for request object response object so that context, etcetera and spring will take care off, passing them as perimeters. That's what eclipse and see how it's done. So here is the exception handling cord, and in this case. No matter what type of exception we get, this cold right here will be triggered. And in this case, I'm trying to respond back with the response entity populating a custom header object. This is simply a poor Joe with a couple of fields. Status and message status will deter mined the extra devastate er's message. What is that? Her message. I'm trying to populate the same here bypassing arguments to this constructor. And I'm just simply trying to respond back with response entity, which will take in all these perimeters the response body headers and status called, which is exactly what I'm trying to populate in here. You can get a little creative and do water we want in here. Maybe you'd like toe respond back with model and view in case offspring MBC and respond back with a ever view to show some meaningful message to the user. You can also target multiple exceptions by adding them inside a calibrates separated by a comma character. Maybe I would like to add no point or exception as well, by the way, this doesn't make sense because we already have the parent class declared in here. So regardless off there is another point. Exceptional. Not this will be triggered anyway. But ideally would like to have two unique exceptions. Maybe, for example, you can change the exception to illegal access, exception whatever, depending on your needs and this will work just fine. Let's run, not application and see how it looks inside the postman Inclined, Amusing post actually be mattered nor to send the request. And I've intentionally messed up with the format off the Jason data that I'm trying to send . This is just to make sure that will have an exception. And so handling logic would be triggered. And sure enough, water, The poor Joe object Porta A robbery that were just created or send back as part of the response body. We have status as well as a message. Whatever we had populated in here, this method right here is applicable. Only written this controller, if you want this handling logic to be present across all the controllers, you can create another class. I mean, get it off this and just add the sanitation controller advice and spring will take care off . Making this exception handler part off all the controllers. This matter is nothing different from the one we had here previously. That's run out application and you won't see any difference, which means it walked. Hope it makes sense. 32. 0702Validation,CustomValidations: Let's talk about how we handle validation in spring rest. A typical test AP I may be receiving a lot off request from declined application, but not all requests could be in the right format. For example, every quiz could be lacking the required request para meters or part variables or deform it off. The Jason inside Erica's body may not be in the right format, in which case we don't want to delegate that call to the service layer on the business logic. Instead, we want to have an additional layer a validation layer, which will check to see if the request is in the right format. Only then we will forward the request to the business logic. One of the advantages with this is that we don't have to care much about the validation logic inside the business layer, and we can focus on performing the actual business task. We would leave that responsibility to the validation layer so that whatever the liquids that come to the service layer were sure that we can process it. Spring actually does this job for us to some extent. For instance, let's that you have the following controller method, which takes in one part variable. Let's say that the part variable that you entered is not in the right format. The method is expecting long type, but we're sending a string so spring will throw an exception. And Silva will respond back with foreign. Did bad request error, complaining that the string cannot become watered or typecasting too long? Like was If you were to send the Chris perimeters that are not compatible, then so would complain with the same because spring is modern after identify such others. However, in some cases you have to do things manually. For instance, let's that you wanted to edit an existing product. You want to make sure that the product name is not blank are is not empty. Spring certainly cannot decide on your behalf as to whether the sting should be empty or not. It is you, as a programmer, have to have price such restrictions, and that's what I'm trying to do. In this case, I'm using standard job invalidation FBI and introduced these annotations. So if the client application sends a request where the product name is not mentioned or is empty, declined application would be seeing the response with this message and here's example. For the same, the product name is empty, and so the several respond back with foreign Did Bad Request era, saying that it is invalid. Let's take a look at this with the running application as well as will explore how to create custom allegations. So here I am inside hair clips. So I'm going to be using extra TV put method in order to update an existing product. And here's the product for JAL, along with validations, which will just stopped. I already have this application running. I'll just go to Post meant Lined and send the request. I'm going to choose the put method, and let's say that I want object the product with I d one. Let me make sure that this is empty so that we'll see if we're going to get an error. Content type is going to be Jason. Let's fire the request. And sure enough, we've seen the message along with few other details. But however, things might get little complex at times because with these annotations, you're just restricted to use only the validations provided by the job. Rex Library. If you'd like to take a look at the and our list, Hiro Day. So you can check for now, not empty min Max, etcetera. Now, let's say that I wanted to put a restriction that whatever the product price that will be populated should be written the range between 1 $2000. How do I buy the restriction? I cannot use one of these methods. I have to create my own allegation. I'm going to use the standard. Java interferes an addition to create my custom annotation. And here is the name off the annotation that I would like to use. And whatever you specify, whatever the methods that you specify are the bunch off attributes that will be part of the habitation. Let me show you what I mean. So here is how our custom annotation is going to look like, and these are the method names that correspond to these methods. In addition to that, we also have a matter that says message with the default message. Well, this is there a message that will show in case of the criteria is not met. If you'd like to override this message, he can certainly make use off this matter of name and add it as another attribute with your custom message. So once you have this matter, Dick laid. You just have to add a couple off additional methods. These methods have nothing to do with what we're doing now, but you just have to add them. Talking about groups and payload is a little bit off topic and actually will never get to use one on these. So just have them in there and forget about it. Let's talk about these and additions Target. You would specify the list off target where you think that we can use the sanitation. I want this, an addition to be used at method level at free level and that I met the perimeter level. Maybe I can get it on this. It's individual choice. The retention specifies that When do you want the deflection FBI to use the sanitation or to populate the sanitation? It is during the run time. As part of the constant annotation. It would specify the class name, and this is a class where we'll have the logic to see if the value falls in between the min and max values that we configuring here. So you just have to create another class that implements constant while the data that comes with a couple of gender perimeters. The first off, which is the annotation glass. But we've just created, and the second argument is the target type putting stance. We're trying to target indigent here, so it's the exact type which you have to specify. This introverts comes with a couple off methods initialized as well as his valid with initialized method will try to initialize all these fields, and spring will take care off, providing all the values that we enter as part of this attribute, and you will have them with this object. So I'm just trying to initialize these very boats, and then we have is valid method. This is where you would write your own logic to see if the entered value, whatever the value is entered by the user, false within this range, and based on that it will return a Boolean value, so that's pretty much it. Let's run our application. Let's make this 1000. Can't expect I phone to be priced within that range off 1 to 10. Let's relaunch our application. Go to Postman, and this time let me mess up with the price. It's already messed up. It's send the request. Okay, We have seen this ad or a name is mandatory field. Have me populate some name. I phoned Z the future Russian off iPhone, and sure enough were able to see this message which was populated in here. So that's how you create custom validations. 33. 0801RESTTemplateIntro: Okay, let's talk about rest template. We already know that we can send requests from the browser or from a client application like postman out any JavaScript application. But there might be instances where to Web services needs to talk to each other and exchange data to perform a business task. So how does to Web services come and get each other? There is no user interface for you to enter the U Earl and then send the request. We have to communicate programmatically. Some of the instances were to Web services would talk to each other is see that you're having a food delivery application. You may want to make Web service calls to another Web service, maybe a weather forecast service, because you want to deliver the food depending on the weather conditions. Or you may want to notify the user regarding the weather conditions and hence the delay in the delivery off the food. Another example is, when you're having micro services, how do these micro services talk to each other? Maybe if you're having any commerce application like Amazon human have multiple micro services, one for managing users, other for managing products, other for delivery, etcetera, and often times all these micro services needs to talk to each other in order to perform a business task. So how do they communicate? Well, one of the answers is rest template. So in order to demonstrate this with an example, here are the steps that we're going to follow. We're going to have a Web service running, and it's going to expose Cry Baby I. And for this purpose, we're just going to use our existing crowd FBI. And we'll try to make a Web service call from another application called Web Service to which is step number two. So we'll have a Web service to make a Web service called the Web service one using rest template. So let's take a look at how it's done. So here is our existing crowd FBI. How this application is doing is to expose few endpoints to perform crowd operations, but one that we're going to use is simply this one to retrieve all the list of products available. So let's first run this application. Let us go toe postman in order to save your time. I already have everything ready. Let me fire the requests and make sure that were able to extract the products. I'm ascended again. Let's see. Not sure why it is not working. All right. The problem is, we just started the other application. Let me just open this particle of file and run it. So the Tomcats over has started. Let's run this application. Sorry about that. So we have our Tom gets over running in Port 80 80. Now, let's try to fire the clearly and see if it works. So here are the list off products. What we're going to do next is to introduce another Web service that would make a call to this end point in order to retrieve all the list of products available by using off course Rest template. You can just simply create a springboard project with spring Web dependency. But one thing that you had to make sure is, since we're going to run these two applications in the same host, you do have to make sure to start off chain the port off the Tomcat silver to something else. By default, it would default to 80 80 on which were already running an application. So for this application, spring app, I'm going to launch it in this sport otherwise would have a conflict. So once you add this property and start your application would have our application running in the sport. I also added a controller. Basically, I just cooperated from outright application and made some changes in it. And it just has one single method with test as a mapping, and here we're going to use the rest template. But before you do, so do make sure that you configure that being, if you're using springboard wash in, that is less than wondered. Three. You don't have to do this, but if you're using one about four or a bow, then you have to configure this bean and spring doesn't do it automatically. So once you have it taken, dependence, inject and use that object. And all I'm trying to do is calling this method. Get for entity your power, the your basically the exact same your Candace copy it and have it in here, which is what I've done. And the second argument in here you would specify the type of the written value in this case. I'm trying to keep things simple and make it as a string, and we're going to respond back with the same type as part of the response entity. Now let's launch this application. So it is this file and make sure that the Tom gets over it started in 80 81. We know have to applications running on the same host. Let's go back to postman in another time. I'm just going to make it a Stabia call with the get method to our new web service. And sure enough, the result is, as expected, I've already experimented this before, by the way, in this case, I'm trying to respond back as a string. But you could actually create a poor Joe. For example, if you go to the actual controller off the lip service, what we're trying to written is off by product. You could create the same Poggio inside your project are another Web application and use it in here just as you're using in here. And it should be fine as well. We're going to explore more such options in coming time. But for now, I hope you got the sense off how to Web services can actually talk to each other. And anyway, this is very crucial for you to understand before moving on to understand Micro services hope it makes sense 34. 0802JsonJacksonToRetrieveSpecificInfo: In our previous example, we had a couple off up services Web service one end up service to were able to make a Web service call from Web service to to Web service one in order to retrieve list off products . And we're trying to display them as it is. However, in most cases we don't want to use or were not going to be needing the entire list off products. Maybe you'd like to retrieve specifications Formacion only depending on your needs. In fact, most often that would be the case. So what we're going to try to do now is in strong retrieving all the list of products from Web service. One. We're only interested in retrieving the product name with product I. D. One. The answer to it is Jackson Library. Let's take a look at the cord. So here we have the controller, and all I'm trying to do here is we have the your this your will help us retrieve all the list of products. But what I'm interested in is retreating only the first product details, and then I want to get more specific and retrieve the product name with identified one until as part of the you'll. I'm trying to get a specific product with the island fire Inside the Web service one, we have a controller method that would help us retrieve a specific product based on the product. I d. You are a template. So this response would essentially will now have the first product and then we're going to create an object off Mapple. What the seller wants to do is we can actually read the end of response in the form off a tree which we can then travels through and retreat specific information. And here is instruction for the same using the map or object. I'm trying to read the response as a tree and in this case, I'm only interested in retrieving the body. Were not interested in head road will have things like state of scored etcetera. If you wish, you can actually retrieve the header information. There's a method for the same. And here it is, but for normal interested in returning the body. So once you get hold off the root node, we can use the Jackson Library methods in order to retrieve specifications Formation in this case, as that mentioned before, were only interested in retreating the product name, and then we're just simply trying toe display it in the form off a text. Ultimately, if you send a query to this method, you would see the result. However, more stuffing things may not be so simple. In our case, we have this set off products, but Jason can actually get little complex. For example, you could have Jason, which will have an aerialist off products. So we have products and then and add a list off products. And you can also have nested objects, for example, a spot off each product. You could have seller information in this manner. In our case, if you go to the product for Joe, it's pretty simple. All it has is three feels, and so you're able to see the same in here. However, you could have another object, something like Cellar that would, in turn will have multiple fields, so its object inside another object. And so the Jason Dress bonds that we get will also be nested. So if you have a response that looks something like this, he can still use Jackson Library to get specific information. Jackson Library has all the methods you need to help you retrieve specific information. It would be very impractical off me to demonstrate you all those methods available, I believe, and just go three, turn off these members description and then get a sense off some understanding on what each one of this matter does. So we have one to find a specific element using apart. I mean, let's say that I would like to retrieve the city off the seller so you could have a bath that say's product slash city something of that sort. And obviously this is not the perfect example. You can experiment with all these methods and to simply play with it. And we don't a purse. Typically read the Jason in the form off a string and store it as part of the string object . And then we'll try to experiment with the Jackson Library before we actually get into the production code. I hope it makes sense 35. 0803POSTUsingRESTTemplate: Let's talk about how we can send Post Request using less template in order to create a resource. You know, kids were going to be adding a new product. So we're going tohave Web service, one which will expose the crowd, the FBI. And of course, we're only interested in the creation part, though, And then we'll have Web service to running, which will send the post request to Web service. One. Using rest template. So first of all, let us try to understand the boss mattered in Web service one along with a quick demo so that will understand the sequence off steps involved in order to send the Post request to Web service one. We went to pretty much use the same sequence off steps in order to send the Post requests from Web service to the Web service. One programmatically he's in rest template. So here is the post matter. Inside the Web service one. Just ignore ology just off the medicine here and focus on this matter. This matter would receive all the post request that are mapped to this. Your and this method is going to accept three Request para meters, which will help us populate on the fields off a product. I'm using those Request para meters in order to create a product. And then finally I'm populating a map with the status which will be responded back toe the line to let that line No, that the product was added. Let's run this application and see how it functions. This is going to run in board a d a. D. Let me go to the postman. Let me will send to get request to see on the list off products available. Let me now try to introduce a new product. Let me open a new tab and send the ball strict rest. Let me try to simulate the farm submission with Chris para Meters So it's going to accept the following values i D, which will uniquely identify a product. And then we have name and then finally Price. When did you the identified as four name? Maybe washing machine price is going to be whatever. Let me send the request. The product is added. Let's make sure that it indeed got added. Sure enough, it did. Now let's go to a web service to and try to follow the exact same steps So here is the controller mattered inside web service to we have the request. You all This is where the records would be sent to And I'm using a builder class You are a confidence builder in order to construct. Are you are I? You could actually heart got all those because para meters as part of this year world But it's not a good practice. The better approach is to use a builder glass like this and construct the your on the fly. But we will be getting all this battle meters from Well, we're reading it from this object. So for this method, though, from the client application, which is both, man, we're going to send a Jason Data which will be on marshaled into product object. And then I'm just trying to read its fields like silk and create all those reports perimeters. So, for this purpose, as you might have guessed, I had to create a Poggio called product. Have corporate this poor Joe from the web service One application. Well, you don't have to copy the exact same Bordeaux as long as you have a Beau Jo that is capable off holding all the data that is being received to dis mattered. You're good to go in real time projects. We would typically referred to the documentation of develop service and try to understand what are the expected para meters and what is the written value, etcetera. And based on that, we would create a Beau Jo. In fact, there are a lot of tools available which will help you create a Bordeaux from the sample Jason Response, and vice versa. He could use one such tools, but in our case, arson at is pretty simple, and we don't have so many fields that we have to worry about it. So I just copied the existing Poor Joe from Web service 12 Web service to. Additionally, if you if your request is having any headers, you could use this yesterday beheaders class in order to do had the list off headers. In our case, we don't have anything at the moment, but if you wish, you can send headers as well. But here is the method post for object, which will ultimately send the request, and this belongs to the class rest temperate, which we had previously dependence injected. This going to accept fue para meters, the first of which the U. R. I, which we're trying to build in here. The second perimeter is so called scdp entity. In our case, we don't have any request, body or headers. And so I didn't include We just said this to empty. That means head acquis, which does not have any body or headers. But if you have a the body or headers, you could populate the request as to the identity, just as we did in here, and then send that request. And finally, the third Param Eter is the type of value or the written value that is expected from the Web service. In our case, it's going to be a map with the results, and ultimately I'm just trying to respond back with the same status. Alternatively, can also use this extreme matter of rest template in order to send the request so you would have the your I as the last. The Hester DP method that you would like to use to send the request has to do the entity if you have any, as we last the map, let's go do here and try to send the request Web service to is running in boat 80 81. So make sure you switch the board. I'm going to copy one off these in order to create a new product. Because if you remember, that's what we're trying to get from this method. That method is expecting us to send the body, which will be on Marshall on the server side. Let me change them at the type to boast. Let me introduce a new identify air and change the product. Something else maybe I'd like to name this has. I'm not sure if I bought it. Still, under production, strain the price to maybe $99. It send the request. Hopefully, this will work. If it doesn't, we'll find out why it didn't. So The problem is we didn't start the application. This is going to run in Port 80 81 and let's try to send the request again. Okay, we have another that say's content type not supported. Let's add one header. That's safe content type, which will let us specify the type of the content that we're trying to send us part of the body. In this case it's Jason, so I'm going to make this as J Son product added, And if you go to a website, respond and send the request, it worked pretty well. So that's about how you can send poor street quest from a bab service using rest template. I hope it makes sense. 36. 0804PUTUsingRESTTemplate: Let's take a look at how we can send the put request, use and rest template in order to update and existing resource. You know, case we're going to update an existing product. So our rep Luis one will expose the crowd. Baby I and from Web service to will be sending the put request using rest template to Web servers Want, in order to update a resource Post will try to understand the put Matt that in Webster was one maybe with a quick demo. And then we'll see how we can write cord to send a put request from Web service to use and rest template. So it is the controller off pep service one. And here is the put mattered. This is going to accept the product object, which is an Marshall washing off the Jason data that will be sending from the client internally. We're just trying to update the regard are the resource and then responding back with the same object. Let's see the functionality off it. So he wrote the list of products available. I'm going to send a put request with this Jason Data. Let me change the name to maybe I for next and also increase the price to maybe whatever. Let me copy the request as well. And let's send it okay, We have to specify the content. Die, Petters. Since we're sending the Jason data and it worked, let's go to a web service to and take a look at the put matter. What they're here is a method which I had introduced its contacts of the same barrel meter , the product object. And here is the cost you are where would be sending the request to. And this time since we have body off the Dick West, we have created this Hajdib entity populating the body with the product object. And then finally I'm using the exchange method and specified all the battle meters to send a put request and get back with some response the resource, your lee and then the method that I want to use to send the request that request itself, which may have body and headers. In our case, we just need the body. The written type is expected out off the response. And finally, we're just responding back with the same object wrapped inside the response entity that's run this application in a different boat off course. Ford 80 81. And from here, I'm actually going to send the put request. Let me try to update. You know, the available products. Maybe I'd like to change this, to wash into or whatever. It doesn't matter. And it got updated. Hope it makes sense. 37. 0805DELETEUsingRestTeamplate: Let's take a look at how we can delete a resource using rest template. So here inside Web service one. We have a delete method, which will help us delete a product from the list off available products. And this matter is going to accept one part variable, which will be bottled the ur itself. And inside here we're trying to delete a specific product by a identifier. And then we're trying to populate the map with the status, which will send as a response as well, from inside Web service to we have a delete product method, which is also going to accept the part variable. And I'm just trying to con cabinet the product idea, along with the Ural that will be using to send the request. Finally, I'm using the exchange matter off rest, template and spurs federal. This perimeters, along with the deal it method in order to send the request and delayed the product. And since this method is responding back with the map, I'm trying to get the map as the response here and this morning back with the same. So here are the list of products available. Now let's try toe delayed this specific product from the list from Web service to which is running in Port 80 81. I already have everything set up, have chosen the dilate method along with the your and it seemed to have worked. Product was deleted and sure enough, it did. So depending on your requirements. Huge. Understand what develop services, accepting what kind of para meters, where is it written value, etcetera and based on that, he can use the methods available inside the rest template in order to send the request and come and get with other more. Jill's hope it makes sense. 38. 0806RestTemplateErrorHandling: Let's talk about error handling in dressed in black. Let's say that your application is about delivering food so we have a food delivery service which might want a doctor, one of the Web service, say, a weather forecast service. Because depending on the weather conditions are application needs to notify to the user regarding the delay of delivery off food. So obviously, we're going to be using rest template to make a Web service called to the weather Forecast service. However, we may not always get deposited. Response from the server are the weather forecasts Elvis. In other words, we may not always get wounded. Okay, status scored. As part of the response, we may end up getting other status courts, depending on the type off error. For instance, plane may have requested for a resource which is not present on the silver are it could be the case that silver went down for some reason or it went off this space. Whatever is the reason, depending on the ever its corresponding Hester deepest Rita scored would be sent back as part of the response from the silver, in which case we need to handle those other scenarios gracefully on the client side. Inside our application logic, here are some of the typical state of scores that we might come across within our date of their life when working with Web services. But there are many more status chords like this, depending on the other. For example, we have poor ended has to deepest era scored. This could happen for Verity off reasons, one of which could be the format at which declined. Since the request may not be in the right format, let me quickly demonstrate you what I mean. I already have our crowd application running and currently the showing list off products available. We also have a put method nor a top data record. So let me just make use off that mattered. So I'm going to make this part of the body and send the request. But before that that Mr the Comden typed to Jason. Now let me just mess with the format So this is not acceptable format. This is not standard Jason format. If I send the request if you notice you have 400 bad request, So not having right format while turning the request is we're not the reasons why you might get 400 bad request status. Similarly, we have four or three forbidden. That means Plant is not authorized to invoke a particular operation. This is true, especially if security is enabled on the other end, and it requires authentication and authorization. And then we have 404 not found status. I think this is pretty popular one. I'm pretty sure you might have come across with this. Friends stands. Let me just go to Google. It's google dot com slash whatever, obviously doesn't exist. Hence we're getting poorer for not for Netter were trying to request for the resource, which is not present on the silver. So likewise we have many such status is you can go to the Wikipedia page has to be bested US codes, and you can explore all the official list off State of Scolds off yesterday. Be so we have basically find sets off status cords. If you have a status code that starts with one, then that means it's informational response. All the state of scores there start with two would correspond to a such a status. Similarly, we have state of scores that start with four to represent it is different types of feathers which you have just seen from decline side. I mean, if you come across with the status scored that started four, then that means something is messed up from the client side. Whatever the examples that were just seen is the mystic from declined side me as a client at requester for the resource which is not present. So it is my fault, not on the server side. While all the serious courts that start with five has something to do with this over side, maybe sober might have went out off this space or result of service, etcetera. So here are all the list off status cords, so we have 500 status scored. This can come from already off reasons. If the server is not able to determine mind theater, then it would just respond back with this gender extractors. Court 500 which means something is wrong from the silver side. So how do we handle these errors on the client side? How do we deal with this? Well, one straightforward approach is off course to rob the court around, Try, catch, block it pretty much will work. But if you want to get more fine grain control on how you handle the status courts. Then we have a special interface specifically tuned to walk with rest template. Let's take a look. So here I am Inside Eclipse. I just created a random class and we want this class Toby Auto scannable. And so I made this a competent and this class has to implement the interface response Error Handler. As the name suggests, it's going to let us right Methods toe handle the errors that are part of the response. This interface comes with three methods to our standard method signatures, and so we have to provide implementation and hit all day. The first matter is about deter mining if the response has another so inside this matter willing to introduce a logic that will help us determine mind if the response has ever you have complete control on the response that is sent back from the silver, and you can customize your logic to determine if it has an answer. So the court that I had introduced is to see the status cord. If it is not Esther, devastate us. Okay, this is an Inam constant and OK would mean 200. Okay, State is called. Likewise, we have many different status cords which we can use said the status is not okay, that I'm returning the value True which will tell this matter here handle error that we have another which we need to handle. If this method returns false, then this method will not be triggered at all. The other would be handled. Additionally, if you would like to deal with only specific status cords, I mean let's that you want to deal with only for a 34 billion response. Then you can just simply have a check to see the status code and based on that, he will set the flag and so this method would be triggered accordingly. Inside this method, you can have the handling logic. I mean, whatever you would otherwise do inside the catch block, you can pretty much have the same stuff in here as well. But how do we make this all work? We need to somehow bag this handler with the rest template. And that's what is being done in this method. So for this example specifically have introduced this method which would map to the get request and inside here. The first thing that I'm trying to do, we won't be needing these exceptions since I corporate dismay at that. All those exceptions came along with that. But we won't be needing them, but he does a key instruction that will sort off, said the other handler. For this rest template, which was dependence injected. And then this you are right here will help us generate the status quo for choice. So let me just quickly walk it through this website and see what they have to offer, said this website. Right here is a service for generating different hash Olympic cords and is useful for testing. Have your scripts deal with bearing responses, and the way you use it is, it just have happened. This data scored in this manner and this application would respond back with the exact same status cord so that we can desktop application. For instance. I'm trying to experiment with four or four error and so I appended this in here and the application would respond back with that court. I'm using the exchange A B I in order to send the request. That's when our application and see how things will go well. We could actually have another application running end and change the logic in there to start off. Create this errors, but it's going to be a lot off mess. So I'm just using an existing application. It's got a postman and try to send the get request if you go back to eclipse. So this method has been invoked and we're also trying to display some details which are being displayed as part of the output. And we even handled the other. So that's how you would handle errors and gets off rest template. Hope it makes sense. 39. 0807HandlingTimeOut: Let's talk about time out and this template. Imagine that you have an e commerce application. Let's call it. He comes service, which might want to talk to other Web services that are available on the Internet. Maybe your service want to talkto shipping and tracking service in order to track the shipping off the product. For example, maybe customer has requested toe check the status of shipping by entering the cord. You would send the cord to this shipping and tracking service and then get back. Some data, which will be shown to the user, similarly, might want to use other services like, for example, an email service in order to send out the transaction. Details received are shipping status etcetera. Likewise, you would typically get to work with other Web services that are available on the Internet . In such a scenario, would use arrest template in order to programmatically call. I'm not the Web servers and get back with some response and do something with it. And typically, the way it works is for each and every client request. There is a new threat which will be created, and this trade will not be available for other requests until this request gets processed completely, for example, it so that the client has requested to check the status off shipping of the product. Then there's a new threat which will be created, and the call would be delegated to the shipping and tracking service. But what if something is wrong on the server side and it is taking too long to get back the response? Well, insert scenario Thread was still wait for the response, which means this thread is not available to so any other requests. It will keep waiting forever. The real problem is you cannot get to create unlimited threats due to resource limitations and enhance the performance. You would have a triple with limited set off threats which will be re used to solve the incoming requests. The limit off threads can be configured, but it would typically be 200 or so. Now what if there are 200 threads inside the threat poor and there are 200 requests requesting for this service, Then all those threats would be occupied, and all those threats would be waiting forever, which means all the other requests which will hit the server will not have any threats toe handle them, and ultimately it would impact the end user. They'll have bad experiences, etcetera. Same is the case. In case off micro services, you may have multiple micro services like product micro service, echoing micro service and a bunch off other micro services, which will talk to each other using rest template. And you cannot risk having a micro service wait for the response from another micro service forever. It might degrade the performance off the oral application it may even result in and that application going down to the lack of resources. So surely this has to be addressed in some way or the other. So what's the solution? Well, the solution is configure time out. So whenever we delegate, the call is in the rest template from one Web service. We'll also set a time out. If we do not receive the response within that time period, then we're just trying to deal with the other instead of waiting forever and causing in that application to get impacted. So let's take a look at how we can country the time out in case of rest template. This is how we would configured the bean and return the rest template object. But this time we're going to send the perimeter to the constructor of rest template like so it is an instance off Hester deeply Components Client, Extra Deputy Quest Factory. It's a pretty long name, but that's how it is. You're instance She ate this class and then set a couple of properties. One is Toe said. The connection time out and the other is to set the re time out. Great time. What is applicable when you're reading the input stream connection. Time out is what is relevant for us now. And you would just pass this object as an argument to the constructor of rest template. And when spring creates instance off rest template, we now have the time outset from inside the controller logic. We're going to somehow simulate the behavior where the Web service is going to take. We're longer than expected. I'm going to use this website, it says to Lippestad dot years. This will allow me to gender it all these to depict codes, and I can also configure the sleep time. In this case, if I send to get too close to this, your old then I would get back 200. Okay. After waiting for 10 seconds, this is to simulate that this over is taking longer than expected. So essentially, this is equal into we sending the request to shipping service and it is taken 10 seconds to respond. But we're not willing to wait for that long. And if you remember, we said the time out to five seconds, so we'll wait for five seconds after sending the request. If we get the response, that's well and good. Otherwise, we would just handle the editor by using the other handler. Let's go back to eclipse and credit on our program and see it working. So he does a bean. And here is the controller logic. But before it on this application, I just would like to show you what is already configured inside the rest template. If you go to the constructor off rest Template one off its constructor takes in the instance off client unsuitability Chris factory, which is an interface if you check all its implementations. One off the implementation is simple. Client s to depict Chris factory, which is the default one used by rest template. And if you notice the connection time out as well as a free time out is configured to minus one, which means we'll have to wait forever. You can actually use one of the methods available last part off this class in order to configure these time outs. But we're going to be using this implementation right here. In order to do that. Well, you could use any off these implementations, but this is the one which is popularly used. Let me run out application. Let me go to Postman and send the get requests to our Web service, which will internally send the get requests to another Web service. So because it has been sent, it took longer than expected. And so we gotten better saying every time out. And we got fined internals over ever, which is a general carer if something is wrong on the solar side and the time actually took 6.65 6.67 seconds while the computer price second, it's because because this time is calculated right when we send the request from this client, whereas whatever we had configure is how much time it should take from this over before we see the response. Now let me just change the court just a little bit and so that the silver is going to take just four seconds. Media, launch the application and now let's fire the equity or the request. And this time it's stoned it. Okay, which is expected. So whenever you're using this template to make sure that you add this extra peas off code, which is a lifesaver, hope it makes sense. 40. 0901HATEOASIntroduction: in this chapter, we're going to talk about hot Eos or some people pronounce it as hate aureus as if they're hitting operating system whichever way you pronounce it here. Is that provision off the same? It's hyper media's engine off application state. I'm pretty sure that this does not make any sense to you at this point. Months after I walk you through a real time scenario where hot ears can be useful and the problem that it is trying to solve, you will have a better picture off what disease and you will know when to use it and how to use it. So let's try to understand hot deals with the real time scenario. Imagine that you visited an e commerce website, something like Amazon here be shown with some products on the home page. He would click on one of those products, and then you'd be taken to a product specific page with some product specific actions like had to cut by. Now are reviews. If you would like to check the reviews off the product, if you really contributes, you'd be taken to yet another view with all the list off reviews that corresponds to that particular product behind the scenes the way it works is the moment you visit the website. Declined. Application would make a rest API call using this new or a baton, which would return list of products from the server and would be rendered on the U I. And once you choose one of the products, Este protocol would be made to the server with the product i D, which will fetch product specific information. And then if you click on reviews, the plant will make yet another rest. API. I call and retrieve review specific to that particular product. We have a couple of problems in here. The first problem is your heart courting the You are a patents in this manner, which means if there is any change on the silver side and there is change in this Patton, then that's going to break the client application. This is a problem because this is going to while it one of the principals off rest FBI were client and server needs to evolve independently. If you hard court, you are in this manner then obviously changing that you are a baton on the solar side is not going to let the client application evolve and is going to break the application, which is clearly a problem. Another problem is not every time you want to render all these buttons. For example, what if the product when daughter off stock then you don't want to highlight or enabled by now and add to cart button? Just want to let the user see the reviews. Or maybe you don't want to allow the operation off by now are at to cut. If the user hasn't logged in, you want alot these operations to be present only to the logged in user. In other words, all these actions should be rendered depending on certain conditions. It's a difficult watch you would do is you would send the request from the client to the server to check to see if this action can be performed. If not, the new deserve Bleidt. If yes, you would enable it. You do that for pretty much all the actions that corresponds to a specific product, which of course, means that you're going to be sending a lot off request to the server, which means there's going to be vested off bandwidth and performance. And although it's not very good user experience, So to address these problems, we have ha dios, which means Plant is not going to put any efforts to deter mine. The you are a patents. Instead, we would leave it up to the server to provide the client all the required actions that it can take. For example, if user clicks on product number one and if the user is eligible to perform, all these actions sober would provide with all those details in the response itself. Pissed on that client will render and let the user take those actions, for example, of product went out of stock, Summer is not going to provide links to I had to cut as well as by no, but would just provide only for reviews. If the product is in stock and if they use the logs in, then so is going to respond back with all the you are batons, using which we can perform all his actions. It's understand it by taking a look at another example there, but you'll have a better picture on this concept. Imagine that you logged into your banking application and you're fetching your account details with the following acorn number and assume that you have $100 in your back on balance. So here are some of the possible actions that you can take. You can deposit, you can withdraw, you can transfer the funds or you can close the account. However, if your application has zero balance, then withdrawing and transferring doesn't make sense, and you can only perform a the deposit or closure off account. If you don't have ha dios, then Plane has to verify but sending request as to what actions can you use a perform and moreover, client has to hard code Urals toe fire. These requests. So with Ha Dios, so is just not going to respond back with thrill when details are require information but is also going to provide What are all the possible actions that the client can take depending on the constraint off the application. For example, if the balances 100 silver is going to respond back with the following links is in which client can initiate requests and if balance is zero, then so is not going to respond with any operations that it cannot perform and is going to respond back with only deposit and closure so on the clean side, instead of hard coding these euros the client is going to rely on this skin here which is called relation, which explains how the lingual is to the object that you requested. For essentially what this means is client is not going to heart court this your instruments going to fetch that you are depending on this relation so that in future of silver introduces any changes in this You are a Patton. It's not going to impact declined application because it is relying on the relation. But of course there is some level of dependency and you shouldn't mess with relation. Name in here. At the same time, claim does not need to send the request to the server to verify if a particular action can be performed or not. For example, in this case so far did not send the withdrawal option so client can check to see if the drop shin is present. If it is not present, which is what in this case, then plane would just disable that operation Our action for that particular user. Another example which we can think off, is right here. I'm trying to retreat product information off his specific product and the silver is going to respond back with the following links. So we have a bunch off relations as well as the U. R. I self would mean the current object which you have just requested, which is this product itself. And here is the you are for the same. If you want to delete this product, then we're going to use this your eye if you want update this you are. If you want to check the reviews, then it is this. Your supply and application can actually sort of travels through all these relations, and depending on that, it can decide as to how we want to render or enable or disable certain features. For example, we don't want delete and a bit operation to be present for a normal user. This is applicable only for admin users. If it is admin user who just logs in thin silver is going to respond back with all these actions. One thing to note here is that a lot of people say that Ha Dios is to replace documentation . But that's not the case put in the stands. If you observe the link for delete as well. Ass retrieving the product Information are bought Same. So we will not specify the actually people hub, for example. If you want to delete this product, then you have to use this You are I with history p delete. If you want to perform update, then you have to use Hester TV put So essentially all that client should require to get started is an initial your And once the client gets the initial, you are all future applications. State transitions will be driven by the client selecting from the conditional links provided by the server Hence the name ha Dios are hyper media as the engine off application state and is essential part off uniform interface principal off rest FBI. So I hope with this you have 30% off understanding off. What is ha dios? We will own the remaining 70% when we take a look at an example 41. 0902HATEOASImplementation: Let's take a look at how we can implement Ha Dios in dressed FBI. We may be having a poor Joe that looks something like this. This is very simple and straightforward. We just have a constructor that would populate all the fields and we have bunch of garrison centers that correspond to these fields. If Civil War to respond back with this resource, then this is how it would be represented in Jason format without all the links that were talked about. If you want the neighborhood Theo's and include all those links to help the client application, I've get through all the list off actions that it can take. We have to include heartiest library in the class part, and we have Springwood started dependency for the same. So you have to include the stag as part off the bomb that XML and Christopher, using maven and for whichever resource you want add links to you have to extend that poor Joe with this class called resource support. This class has matters to help us add those additional links and in order to add those links in dynamic manner, we're going to be using controlling build a class We're going to take a look at an example in the next slide and then you'll have a better picture on the same. So what are the text that you're seeing in it? The blue or red is the additional court, I added, in order to introduce adios feature. The first and foremost thing is that I've extended the class with resource support, which comes with this method ad which will help me add a link Object. Now, when you're designing the application, you have to sit and discuss what are all the possible outcomes and water all relevant for your needs. In my case, I know the fact that whenever I'm responding back with a product, here are the list off actions that I would expect the client to perform, like the late update taking a look at reviews, etcetera. You can also apply conditions if you wish. For example, maybe I would like to disable delete if it is customer who logs in. So maybe I would have a conditional check to check the authentication, and based on that, I would either at this link are not at this link. Whatever the test that is highlighted in dread, is bad practice because what we're trying to do is we're trying to add the link object by hardcore in the U. R I. There isn't why this is a problem is because at later point off time, our mapping annotation can change and the link would no longer work. Instead, we want to use the class controller linked builder, which has bunch of static method like linked to methadone, etcetera, to help us dynamically populate the links. For example, this instruction right here would allow us to press the value off the mapping annotation that corresponds to the delete product method, off part controller class and with relation to lead. Let me explain this in more detail fashion so as you that we have the controller with the falling because mapping and inside this controller, we may be having a delete method with the following mapping. So using linked to mattered would help us call the matter off this controller, whatever the controller. But she's specifying here and by doing so, Spring is actually going to take care of dynamically pulling out the request mapping information from here and would respond back with the same. This is equal in tow. We hardcore in the link in this manner and ultimate Jason result for both off. These is going to look something like this. So it's always better to use this approach so that in future, if you change us to something else, it's not going to impact anything so likewise have popular all the links. And whenever this resource is requested, I'm in the product. Spring is actually going to take care off, wrapping departed content with all these link objects which will be used by the plaint in order to perform various actions. So ultimately, the Jason responds this time, after we added all that code would look something like this, which is what I'm expecting. So I hope that you have some better understanding off. Adios. The next thing that we're going to do is to take a look at a working example and thereby you'll have complete picture on what is ha dios, How to use it, etcetera 42. 0903HATEOASImplementation: So let's take a look at the running application that uses studios, um, equals walk you through the end result. With this year, I'm going to fetch all the list off products available, and the AP is going to respond back with all the list off products in Jason format. And if you notice each and every product have those links that correspond to that product. And in the end, we have a link that corresponds to this response. Would yourself so if I click this link and send the request that would yield the same result What you're seeing in here. So let's click on one off this products I would like to populate protect with i d one. Let me send the request and for the sake of this demonstration of actually added a couple off reviews for this product and hit all day and even give you objects, have some links that I feel are relevant. What is a product toe, which this rebuke, a response to and the other is self, which, if you click and send request, would yield the same result. So let's take a look at the code. First, let's try to explore what's happening with this? You are I. So here we have the get products method, which will ultimately respond back with all the list of products. Along with that, we're also trying to populate the link. Hence is we're not just responding back with products. We have to rob the response with this additional link or links. For that reason, I have to use one of the classes available as part of the Hadiya's library, which is resources. And what this does is exactly what it describes a general helper toe easily create a rapper for collection of entities. In this case, we have products which are collection of entities, and we want to wrap with some additional links, and that's what we're trying to respond back with. And here is the link that you just saw. And again, I'm using the Link Builder class to dynamically populate the You are a essentially, I'm trying to call the exact same method so this mapping would be populated as part of the response. And once after I click one off these products, you would get a response that looks like this, and this is something we had already explored. We pretty much have the same chord that we talked about earlier. We extended the class and that included all these links. This line here is a bad practice, and we're doing good here. So every time our a P is going to respond back with this object, that object would be wrapped with all this additional links. And finally, let's also take a look at the review spot, which is this So for this purpose of actually created another Beau Jo, they're correspond to product reviews and difficult. This would be an entity, since we're not using any database or anything of that sort. We don't have any foreign key mapping, etcetera. So I had to add everything explicitly. Let me go to the controller. And here is the method to fetch all the list of reviews. And if you take a look at the implementation, have manually populated the reviews in this manner, not catching it from a database. Ultimately, I'm using the same approach that I had used in gets off, get products in order to do send back list off reviews that goes born to the specified product. I hope it makes sense 43. 1001SpringReactiveProgramingTheory: this talk about reactive programming in the context off spring framework. Let's start with the real time example. Hasn't that you own a restaurant? And when the only restaurant it would obviously hire a bunch off servants to solve your customers, right? So I assume that all these white doors that you're seeing in here are servants. And the black box that you're seeing in here is a servant room where all the servants would be reciting unless of that your restaurant has, one policy would say is dedicated servant. What that means is each and every servant would be dedicated toe only one particular customer. Let me try to explain it with an example, say that one customer enters the restaurant so one of the servants would be located to that particular customer. The servant will take the order, and he will place that order in the kitchen. Servant will wait until the dishes being prepared by the chefs. And was the dishes prepared? He will go back to the customer, and so the dish what's even worse is the servant will keep waiting, handle the customer, eats the dish or finishes eating, and only after customer leaves the restaurant. Well, this oven go back toe servant room in order to make himself available to serve other customers. That's what this dedicated servant policy Saiz. You clearly see some inefficiencies here because let's say that there 10 servants and they're 10 customers went off the restaurant. How this 10 servants are occupied with all those 10 customers. If there is 11 customer who enters the restaurant, there's nobody to solve him. So that's one problem now. Obviously, this may not be true in Deal time restaurant, but just for the sake of this example, let us assume so. Another problem is, let's say, one customer places an order for 200 pizzas, and so seventh will go to the kitchen, place his order for 200 pieces, and chefs will prepare all those 200 piece US. The servant would carry all those 20 pieces back to the restaurant, only to notice that they're not enough tables to accommodate all those pieces. What so ever should have done is he should have notified getting staff to produce only 10 pieces at a time until all the stone the pieces are sold. But currently, that's not happening again. All this won't happen in real time restaurants, that is, as Jim. So for the sake of this example, we have yet another problem. Let's say somehow customers started loving your piece us and a lot off orders Save 1000 piece us and your current kitchen infrastructure is not capable off preparing so many pieces at a time. And so what you have decided is he wanted to skill your kitchen. You're create another kitchen like this in order to prepare more peace us to cope with the demand. But you cannot do so because of the fact that they're not enough servants to serve the customers anyway. So essentially, you have all these three problems with inefficient and blocking, meaning that servants would be blocked while customer is eating as well as while the dish is being prepared. You cannot scale the kitchen. You do not have control on harmony. Peace us at a time. Do you need according to what the restaurant can accommodate. This is exact same problem we have with current applications. Just replace this restaurant with application that runs on a server and replace the servant room with a thread pool and all the servants in here are individual threads, and all these customers in here are the requests that are hitting the silver and the kitchen in here is some kind off a data source. It could be another Web service, or it could be some form for data source. So this is how it's going to look like. And just as we had dedicated seven policy in a restaurant example, the model that we're following in our application is called Thread for request model. The way it works is as soon as a request hits the silver. Our application a thread would be picked up from the Threat pool in order to solve that request. Let's that you requested for some data, maybe a bunch off products available in the database. The request would be delegated to next layer, which is the data source. It could be another service order data store. Whatever it is, the thread will not be available to process other requests until the data is retrieved back and the response is sold back to the client. The inefficiency here is that let's say there are 200 threats, which would typically be the case in a threat pool and their 200 records that would hit the silver. And let's say that all those requests would take a while to process and all those threats are occupied. Toe handle those requests, which means if there is 20 want request that enters the silver of the application, then there are no threats available to process it. At the same time, threats are not really doing anything. They're just waiting for the data to be retrieved and processed. That's clearly an inefficient approach. And just as you're not able to scale kitchens in our restaurant example, he cannot skill. Other applications are other Web service because of the fact that they're not enough threads to solve the requests. This is especially true in Gets Off Micro Services, where you want to multiply the instances off one particular service where there's too much off Lord using docker continue ization or Cuban it is, but you're not able to do so again for the very reason and problem Number three is, let's say that you have too many data sources, and if all that data comes in one go, your application may not be able to handle it, just as with our restaurant example, if the customer places an order for 200 pieces at that time, there aren't enough tables to accommodate all the speeds, as and in the same day are. Several may not be having enough resources to process all the data so clearly. These are all problems, so we have synchro nous and blocking operations. Synchronous meeting thread will wait under the data, gets retrieved and gets processed. You cannot scale the application are individual micro services. And there is no concept off back pressure, which is a technical term for application, not having the capabilities to restrict amount of data that it can consume from the downstream layers. So what's the solution? Reactor programming. These are the major problems that reactor programming addresses. Let's talk about them So the really active programming walks is will completely get rid off thread for request. Moral. But what we're going to have, though, is thread per processor court. If your service having 16 core Cebu, then there will be 16 threats that are dedicated to each core. So now whenever there is a request, jbm will pick one of the threads from one of the core in orderto handle that request But this time our application is going to tell the data store that I'm not going to wait until the data gets retrieved. Once the data is available for me to consume, do let me know, do notify me and our picket only for have enough resources to handle it and mostly because gets delegated to next layer thread will go back to where it belongs the prosecutor or in order for it to so other incoming requests and all the application says that it has other things to handle, and it cannot wait for the data to be retrieved. It will actually keep an eye to see if the data is available for it to consume. I mean, just as you're walking on computer will still keep an eye on your cat or dog, right in a similar fashion. It is smart enough to do that, and once the data is available, the data store will notify the application regarding the same. It says, I have data available to serve you, but you like me to send it, and several respond back, but saying Yes, I might be needing it, and I think I have enough resources to process that data. It is when the data will be transmitted in the form off it data stream that our application can consume once the data is processed again. While the threat from the process corse one of the available threats from the prosecutors would be picked up in order to send back some form off the response to the client. But I mentioned that the application must be able to come way to the data store toe, let it know of the data availability, and only then will it process in which get the data store must be able to react to it. I mean, it has to say yes or no. At the same time, in the data store makes the data available. It needs to be able to notify the application regarding the same, and based on that, it has to react to it. It can be done like our current applications, and that intelligence is actually given by the reactor library. So you have to have this react to capabilities in each and every component in the entire stack in order to reap the benefits off, react to programming. But ultimately these two components come and get each other and understand each other using this reactor libraries with the Help off bunch off event. The concept off event will be more evident down the line once we explore examples, etcetera. But this mechanism is called and even blue because they're able to communicate each other and understand each other. That's possible because off all these events generated between these two parties, so ultimately, with reactive programming, we got it off. All this problems. The threats are no longer blocking and are a synchronous. And we can even scare the individual micro services and gets if it wanted to, because we don't have any restrictions or bad years in terms. Self. How maney request we can handle so scalability is not a problem, and even there is a back pressure, and we'll talk about back pressure with examples in coming time. But yes, application does have control on how much data it wants to receive from the data source, depending on what it's capable off crossing. And when I say that we have to use react to libraries in all this component, then all these libraries must follow one common specification that's reactive specifications created by a bunch of companies like Netflix people, it'll etcetera. The reactor specifications will have the following basic interfaces called publisher subscriber, subscription and processor. And here are the corresponding methods. It's better that you write down all this in a piece off paper. This may be helpful down the line and bear with me for next one or two minutes because I'm just going to explain how it all works and my bring in some complexity in your mind. So initially, the publisher, the publisher is nothing but the data store. Because they're going to publish some data, the interface will have subscribe. This isn't mattered, which should be used by the subscriber, which is from our application. We're going to call this method subscribe and send the subscriber object. By doing so, the publisher will call the on subscribe matter off subscriber and give him the subscription object, which the subscriber can use in order to request the data. One of the matters that is available as part of subscription is request. If you notice this request method takes in one para meter. Well, this is where the magic off back pressure happens. The subscriber, which is going to be out application can restrict how much data it needs. That's already requested for a result set off bunch of products available in the data store unless it there are 100 products available. But right now, our applications only capable off crossing only 10 products at a time, In which case we can call this method request and send the perimeter 10 so that we get back only 10 products from the stream off data. And the subscriber can also use the cancel method in order to cancel subscription this into a kind of works like our magazine subscription. If you can manage to correlate it, the bunch of other matters which will be called by the publisher are right here. We have on next event, which will be called for each and every data element in the stream. And we have oh, never mattered. In case if we have another was streaming the data from the data store. Maybe database server went down. Are the web service from there were requesting the data crashed? Are there some earthquake in that location which I wish will not happen. But if that happens, then we'll have some gonna Panatta. So are never method off subscriber would be called by the publisher. And here you may have some handing logic, and you will write down some logic to deal with what you want to do in case off another. The on complete even would be triggered once the publisher delivers word subscriber has requested for. And then we have processor interface, which extends both publishing subscriber so basically would use the processor to be able to have control on both publisher and subscriber operations again. This will be more evident once we take a look at an example, but I hope you got some sense off how it all works. I'm very sure that this all looks very complex. Unfortunately, a lot of the complexity would be taken care by the project called Project Reactor. It's a reactor library for spring framework, which follows these specifications. And flocks and mono are the publisher classes that are part of the project reactor, which we can use in our code in order to read the benefits off react to programming. So next thing they're going to do is to take a look at some of the really cool flux and more examples to bring in all those reactor capabilities as well as will talk about some of the drawbacks off, react to programming when to use it and when not to use it, etcetera. Hope it makes sense. 44. 1002ImplementingReactiveProgrammingInSpring: Let's take a look at how we can implement reactor programming in spring framework. In fact, we're going to take a look at the simplest possible example off reactor programming in our spring project. Here are the steps that we're going to follow pasta Paul. We're going to be needing the reactor library. And for that help, including one off the Maven started dependencies for spring boot inside our bomb. The XML file, if you use maybe in and then will be creating a consumer or a subscriber. And then we'll have the flux, which will be the producer to produce stream of data which will be consumed by the consumer or the subscriber. So let's go day clips and right off us react toe example. So what I have here is the simple controller with the falling mapping, and we have to get map method so that when you send to get records with this year, old mapping will be able to execute whatever recites in this method. But before that, let's take a look at the dependency that I've just added. I just have to add the following spring boot started dependency. It's springboard started, wept, flocks, dependency which will do the trick. So this will bring in all the reactor capabilities inside our project. Now, since I'm not going to be using any database I'm not, including any react to data sources are repositories. I just want to keep things simple. And since we don't have a database, we have to have some means to stream the data. Fortunately, the producer class flux has a method called just, which will allow us to specify a bunch off elements which will be streamed. So here I'm going to say Apple, whatever Doesn't matter. It's called it banana. And let's call this maybe orange, and this could be maybe eyes one or whatever. Let's look under a shift or to import the flux class that belongs to the reactor core library. And it is a publisher. So so far, with this instruction, no data will be streamed because there is nobody to consume it. And if you could recollect what we've dogged earlier, the producer interface has the method called subscribe. In this case, Flux is our producer, which implements the producer interface so we could just use thesis subscribe method. There are many variants off this mattered, but the one that I'm going to be demonstrating is right here. The one that takes in Consumer has the Para Meter. I really we would be using a method that takes in the subscriber object. But let's try to use the consumer first for simplicity and in here we're going to specify our consumer. So for this purpose I'm actually going to create and a realist, let's call it as products a new era list and off string. I'll look under a shift Oh, to import all the required classes. And no, I'm actually going to send him at the difference had let's dig deep and try to understand what's inside this matter If you open, the implementation is going to take in the consumer, which in this case have sent them at the difference. So all the data that will be streamed by this producer, there's going to be an on next event and inside the our next event were calling the method . Add are very list. If this sounds confusing this hold on for a moment. I have a better example, but ultimately instrument we creating the new subscriber. The flux is going to do that for us with this method difference used as the consumer of the data that gets streamed. Let's try to We could actually run this application, but I'd like to log everything What's happening? Someone to be using one of the methods available as part of the flux class and dis method. It's just going to return the flux object, but will also help us look at the in for messages as to what's happening. I mean, we can observe all the sequence off events that are triggered. So with the launch, your application and then we'll explore further. Well, I did. I could just write the J unit for this, but I think this example would be more realistic. So let me send the request. So that's 200. Okay, you're not going to be seeing anything here. But if you go back Jack lips and to the control, he would notice some log messages. So first of all, the producer has called the unsubscribe mattered off the subscriber by sending the subscription object, and the subscriber is going to use this subscription object to call its request method, and by default, the perimeter that it passes is unbounded. That means we're requesting. For all the data that is available in the stream, this is there. The back pressure will come into picture. If you could specify some number in here along value, then you would only be retrieving that much off data. For example, if you have a results that off say 100 products but your space for 10 in here you just going to get 10 elements from the result set that gets streamed. And as I mentioned before reaching every element, the publisher will call the our next event off the subscriber. And since we have four elements in the stream, there are four on next events preaching every on next. We're trying to call the ad matter off federalist by passing these elements. So essentially all these elements would be added in the list that were created. And finally the producer will call the UN complete. Even That means it says, I've delivered all the data I have and I have nothing else to share. Well, I mentioned that internally, this subscribed method is actually going to create a subscriber for us. If you go deep. So you have this method that's going to ultimately create the subscriber and is going to call publisher DOT subscribe to subscribe that subscriber. But what I'm going to do next is instead off we letting the flux create the subscriber. We can do that as well. And this is an interface. You have to implement all the UN implement that methods. And inside our next event, I'm just going to populate the realist with the object that receiving here. Of course, this needs to be typecast, erred and on subscribe. We got the subscription object, which we're going to use to call its request mattered, and you can specify some value in here. But for now, I'm going to be setting this to long dot max value. That means we want everything that is being streamed, and now that's run our application. But let's also flogged them a sage. So for that, I'm going to be using the default logger that comes with spring boot. Um, so longer logger factory dot get longer. I'm want to specify this glass name. Well, let's follow some best practices and make it prior weight Static final contar Schiphol to import the logger, and that's just use this longer to print. Watch inside the list n four and I'm just simply going toe print the list in the form off a string. Hold it, Let's run our application. But send the request and let's go back and make sure there are elements in the list that means all the elements were consumed. So here's a quick example off the reactor programming walks, and we've also practically understood the sequence of events that have dogged in theory. I hope it makes sense. 45. 1003BackPressure: Let's try to understand the concept of back pressure. But before that, let us try to understand the difference between pull and push model. An example off pull model could be Javits streams. If you're a bit off java, it streams. What we're trying to do here is we're trying to create a stream off even numbers without first instruction in here and with our second instruction were trying to pull the data from the stream. That means the producer is not pushing the data, rather the consumers pulling the data from the stream. In this case, we're trying to pull five elements from the stream. So this is an example off pulled model. Whereas when it comes to reactor programming, it's more off a push model than a pull model. Some people call it as pull push hybrid model. But whichever way you think the way it works is the subscriber will request what the data just the amount of data that it is capable of processing and the data source are the producer will have a huge chunk of greater Toby streamed. But depending on how much data is being requested, the producer will push only that much off data that the subscriber is capable of handling The data, which is available to be streamed but is not yet requested by the subscriber, would be stored inside this buffer. And maybe that studies. And it's called back pressure mechanism because all this data yet to be requested by the subscriber might actually build up some pressure. And hence that name. I'm not sure that's my best guess. The concept of back pressure is very crucial, especially in case off micro services, because all these micro services would actually coming to get each other with rest. API I called etcetera and each notice both consumer as well as a producer, toe another node. If there is no concept of back pressure than all the data would be streamed in one go, which the Microsoft's may not be able to handle it, and that might cause lack off resources, and hence the service may go down. And as a side effect, all the other micro services which are reliant on the affected micro service can also be impacted. And hence the back pressure mechanism is very crucial. Where all the downstream note would notify the upstream notes as toe how much data they're capable off handling. What we're going to do next is to take a look at a simple example off back pressure when will try to pull a limited set of data depending on our needs. Let's go wreck clips. So here is our previous example and currently we're trying to request for all the data that is available in the stream. But now we're going to enhance it to request only two elements from the stream. So I can make this to know what this is going to do is the subscriber is just requesting for two elements from the stream. But what we won't accomplish now is not just request to elements, but we want to request to elements at a time. So the unsubscribe matter would be called only ones. When the subscriber subscribes to the producer. However, the our next event would be triggered a rich in every element. So we can have a logic in here that will check to see if we had all the reprocessed the requested data. If so, then total request new set of data and in order to request noose around data, we need tohave the subscription object because that's what who used to request for new data . So we're going to make this available globally in this class. So let me just create a variable private subscription. Let me just populated and inside the on next, even we're going to request the next set of data from the stream, which in this case is too now, obviously, this doesn't make sense. Have to have a check to see if and for this We need to have a account and would incriminate the count for each and every our next event. And then we'll check the safe count equals two. That means we had all the re process, the data which we had received, and let me also reset the counter back 20 And there you have it. In order to understand this behavior in better fashion, let me also log what's happening. I'm not support the log message in here. Annan for log to see populated products. I'm just simply going to print whatever is available. A spot on the list. Let's run out application and see what's happening. I mean, go to postmen and send the request real quick. And if you take a look at the console the first time subscribers subscribed to the producer producer called the On Subscribe. Even with the subscription object his language, we requested for a couple of elements and hence their corresponding on next events off those two elements for each and every our next call, we're implementing the counter, and since there are two elements in here, the condition is met. The count will become, too. And so we requested for additional set off data and something is repeated once again, and the third time were trying to reckless for new data. We don't have any data to be streamed by the producer, and so the producer will call the incomplete method off subscriber. And finally, we're just trying to print what's there in the end, our list with this log message right here. So that's are you limit the amount of data that you want to consume. I'm pretty sure that this is not the most realistic example off back pressure. We have many more exacting an interesting examples coming. Stay tuned 46. 1004RespondingInReactiveWay: Let's take a look at how we can send response and react away. But before that, let us try to understand how it works in non react away or in traditional way. Imagine that the client had requested for all the products that ever existed. So we would have to fetch all the parts from a data store and would have to wait until all those products are accumulated on the server, and it would then translate all the spirits and equal and Jason format to send it back to the client. Now there are two problems in here, since so what is dealing with so many records, and it would have to translate those objects into equal and Jason files. It's definitely going to drain the resources it may run out of RAM, and the worst part off this is it might actually impact other crucial operations that needs to take place on the server. So this is clearly a problem to be addressed. So this is have you write core in traditional way. You would fetch all the parts on the repository and only after. If it's all the products, even if it means one million products, you would wait for all the products to be fished. Only then you will send the response, so this is clearly inefficient. However, if you deal with this and react away, that line would ask for list off products. But this time you're actually going to stream the data back to that line, and the Silverado application will not wait until all the records off. Fresh application would just subscribe to the stream from the publisher, which is the data store, and it's utilizes each item and send it back to the plant in smaller chunks. And since this is not blocking operation, we're just going to eat less the threats that are not being utilized and is surely an efficient way to send huge chunks off later. And this is how the court would look like the only primary differences that, instead of responding back with standard at a list, were just responding back with the publish interface. So this could be flux or more no. Whatever is a publisher, and on top of that, we have an instruction. The stream. All the list of products from the data store are to ask the data store to provide a list of products. So we have flux dot generate method and this matter would just help us generate unlimited number of objects. In this case, I'm just trying to generate an unlimited number off product objects. And then we have the take method to take just as much as we need. In this case, I'm just asking for 10 products from the stream and then returning that flux object back to the client. Let's go to eclipse and see how it works. So here I have the exact same chord. Let me just launch the application. And since this is just to get mapping, you could send the request from the browser as well. But I'm just going to be using both man and there you have it. Although with this example, you won't be able to see much off a difference between traditional way and react away. But in real time applications, where the data is huge, this would really mean making a huge difference. Enough course. In order for this to work, I've actually created a poor Joe which is going to be our product object with the one battle mattress constructor that just takes in the name and you know, kiss All the broke names are same. This is just a symbol. It We have a huge chunk of products in the data store. This is not a real time scenario, of course. 47. 1005LiveStream: with reactor program. It's even possible to stream the data live so that all interested parties can listen to that stream without being aware of the start of the stream or the end of the stream. For example, he could have a Web service that streams live temperature are the life score so that all the clients who want to listen to that stream can join or subscribe and listen to the current ongoing stream without bothering about the start of the stream or the end of the stream. Now the plane can be a browser, a client application and Andrew Rap. Whichever it is, they can listen to the ongoing stream. Has a wish. Amazingly, don't have to do a lot off work to start live streaming. All you have to do is to add one attribute, the one that you see in red Color. You had said, the media type toe text, even stream value. And that's all. And now whatever the data that we're sending from here would be livestreamed and in this case, though, who just streaming 10 products. But the example that I'm going to walk it through in eclipse is going to stream continues data in an unbounded manner, and we're also going to see how we can apply back pressure. So let's go to eclipse. So this time, instead of returning products, what I'm trying to do is I'm trying to gender to random number between 0 to 50 in order to simulate live temperature, and the rest of the court is pretty much the same as with the previous example. Off course, the written type is going to be not a product object would rather a string. And finally we have this attribute added. This is a tribute that does the magic that's from out application. And this time let me go to Broza. So we are having data streaming live, and it is and it is unbounded and will never end until we stop off course. And of course, temperature want proctor it so frequently. But this is just an example. Also, if you notice the data is being streamed once everyone second, so you go back to eclipse. We're a playing back pressure. With this method, call delay elements with a delay off one second. Imagine what would happen in real time applications. If this restriction is not there, then all the data would be streamed as a huge chunk and might goes over to go out off memory 48. 1006FluxVsMono: Let's try to understand the difference between flocks and more. No. If you want to return a result set, which will have multiple elements, then you would use flux. If you just have one element to be returned or if you have only one result, then you would use model. Let's go there clips and try to understand the same. So in here flux would make more sense because we're trying to return list off products. But let's say I wonder it on the count, for instance, in this case, I'm just returning one result. Someone would make more sense. You might be wondering. Flux is going to return more than one element anyway, So why can't you just use flux? Well, the answer is the client might be expecting with one element. If you're using flux as Origen type, then there is a possibility off returning more than one element. Using one would ensure that will have only one result of Britain. That's right, not application. Let's send the request and regard the response 49. 1007ParallelStreams: Let's talk about parallel streams. I think this can be better demonstrated with an example, but but the idea is that instruct crossing all the stream elements under one single thread . We're going to be split in the stream into multiple Palo streams. And then we're going to have multiple threats handling each one of these streams and all this stretch would be running Palaly. Basically, we're trying to read the benefits off Java multi threading again. You understand this better with an example, Let's go to eclipse. So here we are, inside the eclipse, and what I'm trying to do here is I'm trying to generate values 1 to 4 in the form of a stream. I'm using the subscribe method, passing the matter difference, which is right here and in order to similar it. Something is being processed and is taking a while. I'm waiting for five seconds. Along with that, I'm also printing processing water. Delmon that gets passed. I've been on this application and see how it's going to look like P notice. A message would be displayed every five seconds. That means all these elements are being processed under single thread. No parallel processing came into picture, so it almost took us 20 seconds to complete, because for each and every element, it took us five seconds to process. Now what I'm going to do next is to spread the stream into multiple parallel streams, and then we'll have multiple threads handling all those streams. For that, I have to add his additional statements. The key matter that will help us accomplish this task is right here. Run on and then we're going to use one of the classes available as part of the reactor core schedulers. And here we get to choose the more at which we want to handle the stream. We have been as different options, battling in order to create multiple threats to handle the barrel streams. Single would mean that would create another thread, and the same dread would be handled to process all the elements from the streams. And then you have idiots are the Mort's. But the one that we're interested in right now is this want to run the streams battle early , but in harmony threats is what you would specify with this method call. So this time we went to have four threats that would handle each one of these elements. And since all these were running Palaly, we're going to be seeing some efficient usage off resources and would be very evident once we send the request. You would notice that all these elements are being processed simultaneously and regard the result in just 5 to 6 seconds. But now let's say that our silver resources are not so significant that they're able to handle so much off. Lord, guess what? We have to apply back pressure and so will be able to. Reggie is the frequency at which the data is being streamed from the producer flux. So with this instruction, we're asking the producer to produce on the one element with the gap off one second or 1000 milliseconds. That's long your application again. And this time will process the elements once in every second. And all these elements are processed paddle only. I hope it makes sense 50. 1008WebClient: Let's talk about how you can make to Web services are to micro services, for that matter, communicate each other in react away. So think about the following scenario wherein the client would be crystal list off products and a Web service will received the request. And let's say that this Web service needs to send requests to yet another Web service in order to retrieve the list off product. Obviously in traditional embassy applications will be using the rest template to perform that operation. But rest Ember is again blocking. That means once that it questions sent from this Web service, the thread will keep waiting. So that's going to pose a problem. That would be the case, even if this particular Web services reactive in nature. So if you want to get things done in react away and utilize the resources in much better fashion, then you have to replace the rest template with Web client, which is no, I'm blocking so the trade will not be waiting and is available to process other requests. So let's take a look at an example of the same. So for this purpose, we're going to be needing a couple off Web services. What I've done is I've just created a clone. How far existing project I literally did control C and Contrave. And here is what I got one additional chain that I need to make, though designed to add this property inside the application Dark Properties file. Since we're going to have this to services running under same host, we don't want any port conflicts and want them to be running on two different ports. So we have a Web service, one which will be running in 80 80 and the other one in 80 81. So he wrote the controllers off both these services. So here what I'm trying to do, it's just simply written, went off product objects by using the gender, it matter off flogs and generating an unlimited number off product objects. But then I'm applying the limit off only 10 and from hip service to I'm going to be using the Web client, which is a reactive abortion off rest template, and I'm using this method create and passing the u R I. But I would like to send a request to, and I'm a pending the your I that I would like to happened on top off existing. You're right. And I'm using this method retrieve in order to actually send the request and then retrieve the result. And then we have this mattered body to flux, which means I want to convert the response body to flux object. And here I'm providing the Poggio. Ultimately, we get the flux object, which would consider the list of products. And we're responding back with the same to the client, which in our case, is going to be the postman plaint. So let's run these two applications. This is going to run on Port 80 80 and the other one would be in port 80 81. So we're going to be sending request toe this method right here to this web service, which is running in port 80 81. And this is going to make a call to another Web service. With this you are I. And we got all the list off products, obviously the data and here doesn't make sense. I just want to simulate like, retrieving products, the lot off methods available, last part off the wept, lined, just as with the rest template, and you can actually play with it. I mean, if you'd like to, let's say filled road the results and you can use the filter method and send alarmed expression. You can even go ahead and retrieve particular fields from each product. And if you want to apply back pressure, can again use the deal elements method and given number the time you'd like to wait. You can even go ahead and subscribe and do some processing, passing the method reference. So there a lot of possible cases and depending on your needs, you have to come up with 11 solution and in fact, it will get even complex like you would be able to even come by multiple streams. Or maybe just let me demonstrate that I'm just going to make a clone off this stream, Let me call it, but plus two and them we're going to have the flux tree product looks. Three. I'm going to use one of its Matt that called Gone Got with multiple sources and let me just born back with the same. So I'm trying to come by multiple streams seemed to be having another. You tend the statement and relaunch our application hopes. That's too okay So this time, essentially, we should be getting 20 products, and sure enough, it work. So ultimately, this is the reactor part off the entire application. Rest off the layers would pretty much remain the same as with traditional embassy application. But make sure whatever the libraries are competence that you're going to introduce into your project are reactive in nature. If you'd like to follow the reactor way of dealing with things, we're going to talk about some of the drawbacks off. React to programming, especially in the context offspring framework, and we'll also try to understand when to use it and when not to use it. 51. 1009SpringReactWithMongoDB: okay, so far, I'm assuming that you have a fair bit off understanding on how reactor program and walks in case our spring framework. And so with that in mind, let's take a look at how we can create a complete reactor application from scratch using spring boot and with Mongo DB as a data source, we're going to be creating an application that performs basic crowd operations. And for this purpose, I'm not expecting you to have any knowledge or longer DB. So even if you haven't had an exposure to using mongo DB, he should be able to follow this tutorial at a high level. This is how our application is going to function. The client would send the request to the controller. The controller will have all those end points to perform crabbed operations and the controllable intern delegate the call to the service layer and then the service level, make a call to the repository which will doctor the database to perform that idea off operations. But the key thing to note here is we're going to be using react to libraries in the entire stack. And so what are the responses that we get from this competent are going to be a the flux Hormonal objects, depending on whether we requested for results set or one specific result. So for this purpose, we're going to be needing every actor library in place that is specific to the data store that we're using. Since I'm using mongo DB, we're going to be needing the Mongo DB reactor libraries offered by Spring Data Project, and we're going to use them in order to bringing all those reactor capabilities. So here are the steps that we're going to follow possible we're going to be creating a springboard project isn't Sprinkle suit with all those react to libraries, which includes react the Web as well. Last react a Mongo db dependence is. And in our example, we're not going to be using any external mongo db. And so I'm going to be using an embedded longer db. So we have to add a special dependency for that unfortunately embedded Mangane but doesn't come by default with all those react to dependencies as part of Step number three went to be creating a repository and with spring data, things are going to be very smooth because all we have to do is to declare an interface that extent a specific react to Mongo DB interface and that will do the job for us that's going to include all the crowd operations would be needing a non application and finally as part off step number four. We're going to create a controller, which will have all those end points to perform crowd operations. So we have get mapping, post mapping, put mapping and delete mapping methods to do that job for us. And, of course, we're also going to be needing at Poggio, which is product which will be used across all these components in order to sort of hold the data. And that corresponds to a document in manga DB are in rd BMS Stones that would correspond to an entity will understand what I mean once we take a look at a working example. So here are the dependence is that we're going to be needing we need the spring would start a Web flux to bring in all those react to libraries and capabilities. And then, since we're using mongo DB, we're going to be needing springboard starter date among really be react to library in order to come to get and react away. And finally, we're also going to be including the embedded mongo db with the dependency that you're seeing at the bottom. Here is the depository or the interface that will create. And as I mentioned before, this is all you need to do and this will suffice to perform crowd operations just have to create a random interface with add direct repository annotation that will make this a repository component and this must extend. They react. Oh, manga repository which accepts couple of gender para meters. In our case, it's going to be product and string, which is kind of like a unique ID and fire, and inside our controller will be having all those end points. And here's the cord that would help us retrieve all the products from the data source. So I'm actually making a call to define doll method off the depositary we had created well , ideally, would have a service layer and you would make a call to the service layer. But since our application is spread, your simple I want to reduce the complexity and I see there is no need off introducing a service layer, and we can just talk to the depositor layer. But ofcourse, India time projects would have a service layer that in General Doctor, the depository are the data tear. So I'm trying to retrieve all the products available in the data source. Are manga deep in our case? And I'm returning a flux object because it's going to be results set. If you're using a nonreactive mongo DB library, then that would not have been returning the flux object. And so that would introduce all the blocking operations. And here is our read mattered and for you To understand this, you must have some knowledge on Lambda Expressions and Stream. FBI introduced us part of job eight. But here is what we're trying to do. Initial. We're trying to retrieve a product with a given I D, which will be sent as part of the path variable. So that would be part of the U. R. Itself. And using that identify where we're trying to find that particular product from the data source and using the map mattered. I'm trying to transform that object by wrapping it with a response ended the object, and here, whatever the value that gets returned by calling this map that find my i d would be passed as a para meter and would be wrapped with the response into the object. And here I'm trying to set the status as okay. That means when the client is response, the extra demonstrators would be to under okay with the response body as this object. In case if we don't find that particular product, then we want to populate some default information. In this case, I'm trying to set the response entity to not found which would correspond to, for or for not for better off yesterday be the create method that corresponds to the post mapping. We would send a Jason Daito as input, which we're trying to read with the sanitation because body. And then I'm trying to save the object by using one of the methods available as part off the depository which would written a more No object would just got saved. And since the same matter is going to return only one instance or one object we're using Mortal Nora Flux. And here is the code to perform update operation. So we have put mapping and we're going to be sending the identifier off the product to which we want to perform the update. Along with that as part of the request body were also sending the product Jason, which will become water and equal and product object. And in here we're trying toe retrieve a product with that particular I d. And inside this method, what are the court that you're seeing in dread? We're trying to set the product name to whatever the name that has been received as part of the request body. So whatever the product that is retrieved, we're trying to update its name and then saving it back again to go back to post mapping method. Whatever we're trying to do in here is exactly what we're trying to do in here. But before doing that, we're not only retrieving the product but also updating its name. And then finally, business on what happens in here. We're again wrapping the result as part of the response entity. If everything goes well and good, that means product has been found and is updated then we're sending the status as extra DP Okay, otherwise would populate the default response with extra devastate us. As for four not found, the deal. It operation is somewhat similar. We're trying to retrieve a product and, if it is found, were trying to delete that particular product from the data store. And then we're responding back with some response entity, depending on whether the product has been found or not. We can also live, stream the data by adding this attribute, produces and said it to media type, text, even stream value. And here I'm trying to retrieve all the products that ever existed. And then I'm also applying some back pressure to deliver the spot. It's once every second, so that's how it works at a high level. But let's take a look at a working example so that you'll have a better picture and you'll have a better experience, but how it all works. 52. 1010SpringReactMongoDBWorkingExammple: So let's take a look at a working example off complete reactor application that use this mongo DB. But before that, let me walk you through the project. First things first, you have to create a springboard project. And in my case, I use spring tool suit in order to do that job. So just populate all the fields in here and click next hit. It controls all the starter dependence is that you have been eating. How do you search for react to that would show me all the reactor libraries and if you notice currently react to support is available for all these databases all it is no excluded a basis, which includes mongo db Red is Cassandra, etcetera. And we also have a support for an SQL database, which is, by the way, experimental. It's not recommended that you use this in actual projects, but the one that we're gonna be needing, though, is mongo DB as well as we need React a Web. I have already done this and so have this project with all of those dependent is added. So we have bet plucks dependency as well as the reactor mongo DB. And in addition, to that since I'm going to be using an embedded mongo db, I also have to include the following dependency. So once I have all these dependence is in place. The next thing that I want to do is to configure the falling perimeter as part of the application or properties. And this points to the you are a off mongo DB with a specific port. So are embedded. Mongo DB is going to be running in this particular port with whatever the database name that you'd like to give next. Let's talk about the depository. So I just created an interface with some random name. But this must extend the reactor mongo repository that belongs to Spring Data Project. And like I mentioned before, this is going to bring us all the basic functionalities that will help us perform crowd operations. If you want to go beyond what it all the offers, then you have to introduce some additional equity methods are give those greedy annotations and give your custom greedy, etcetera. But at the moment, we're not going to be needing all that, and we're not going to be having service layer so we don't have a service interface or its implementation. We're going to call this repository statically from the controller logic. So here is our controller, with all the methods that were talked previously, and in order to use the depository, I'm dependence injecting it. And here is a product, Bo Jo. And since I'm using mongo DB, which is a no SQL database, I have toe annotate it with a document. If you are aware off SQL data basis or relational data basis, this would correspond to an entity, and the collection in North Co database would correspond to a table, but still, the stuff would remain pretty standard. I have a couple of fields idea as well as the product name. We also have some validation to set the limit off characters for the spirit name, and this will be activated whenever we have valid. Annotation added. I already have this application running, so let's take a look at how it functions. Let me go to a client. Let me first try to create some products so that we can experiment with them. We're going to be sending Jason data so this Jason Data must map with the poor Joe. And here it's going to be local host happen 80 80 slash products if you go back to the controller. So that's exact mapping we have in here. That's products and made to send Jason as part of the request body, which will be saved. And a more no object would be ripped on back, which will see on the client side. Let me just send the request between the idea to something else can it to change my dad one header to say that the content type is Jason and product has been added. When we had a couple of more products real quick, No, let me retrieve all the products available. So this is going to bring all the list of products that were just populated. Now let me just update this product with I d one. I'm going to specify ideas, part of the part credible, and the body would have the Jason. I would like to name it as whatever. It doesn't matter. Of course, we need to change the method to something else. So that's put method for ablation, and it has been updated. Let me check if it indeed God updated and sure days, we can also delete a particular product. So that may send delete Scdp request. And we got 200. Okay, Response. Which means product has been deleted. Let's take a look at all the final list of products available and we have only two hope it makes sense. 53. 1011LiveStreamWithMongoDB: It's also quickly talk about the solar side events and stream the data live. So we have this method that will do that job. So I'm trying to retrieve all the products with the delay off one second. And, of course, in order for that to work, you have to had this attribute. Let's go to browser and trying to see how it functions. So everyone second, you see the data getting populated. But one thing to note here is that by default, this is not an infinite stream. That means you won't see data getting populated as and when the new data gets added into the database in order for that to work. If you want us to be an infinite stream, that means someone will push the data continuously as and when the data is available to the client. Then you have to use so called a available cars ER, which is a concept off mongo DB. And in order for Dr Work, you have to create so called a capped collection and you won't be able to create a capped collection with an embedded mongo database. You have to have an extra manga database where you're able to access its console and run some commands. So for that reason, I can or demonstrated that feature at the moment. But I'm just trying to say that it is possible that to see the data re alive as and when the data is created on the database sent, I hope it makes sense. 54. 1012TestingReactiveApplications: Let's talk about how we contest are right, Jane. It's for react to spring based applications that use spring were plucks. The first thing that you need to do he started this dependency reactor test. This is what will bring in all those additional libraries required for you to test. React to component. If you created your project Isn't spring toe suit are by using spring initialize er and added any off the reactor libraries like springboard started web flocks or react to mongo db Then this would be added automatically. Once you have that in place, you can write your test cases. So let me just walk you through the test class, which I've just created. So this class goes inside the standard a source it test directory. One thing that you would notice is the sanitation bet flux test. This is actually combination off multiple other annotations. But ultimately, this is just going to configure some beans that would help us test our reactive approx component. One other beings that it configures his weapon s client, which is a variant off, wept, lined that will help us and ESRI be requests. And it comes with a lot off additional methods to help us send the request. Check the response and see if the responses as expected, etcetera. We're going to take a look at an example of this in a while. The first test in here is the simplest possible test case. And this has nothing to do with our court in our project. This is just to get some understanding on how we can use that library in order to test the spring back flocks. So what I'm trying to do here is I'm trying to create a stream off elements in the scare stream off string elements by using the just matter of flux. And I'm using this class that is part of the reactor test library in order to subscribe to this publisher by calling this method create which takes in the publishers a perimeter and I'm using one off its method. Expect next ConEd which, as the name suggests, I'm expecting the count to be three. And then finally I'm trying to see if the stream is complete. Hard to save. The publisher published everything. What it has to publish. No. Since I've already tested this, this desk, it's would pass. But if you want to change this number to something else, the test case would fail. Let me save the file and quickly run it for you. We're going to see an assertion ever. That's a is expected countess for, But it's three. And in fact, if you're new to react to streams, then this is the best way to experiment with it is to write a quick Janet Dsk's and play with the stream. So we do have an assertion. Error expected. Count is four, but is three. Let me undo that. You can also create an exception and see if exception has indeed occurred. You just have to use another method for that. The other two test cases, though, would correspond to couple off controller methods we have in here. I'm trying to test both post as well as get product methods in gets off post. We're sending correct as a perimeter from the client and preventing Lord Jason as part of the request body, which will become water and equal and product. And then we're trying to call the same matter of this repository in order to save the object. So we're trying to simulate the same behavior from inside out desk is as well. I could see that the product object and I'm using the standard market or library in order to tell what should be returned if this method off repository has been called, but before that, I have to have a mark object off repository and I've done that with the sanitation. McBean and I can now use this mark repository and specify what should happen in a particular method is called. So if we call the same matter off repository with this object, then we want to return a moral off product, which is the same object. If you go to the same mattered. That's what it would written. It's going to return a Mona object and in the next line I'm trying to use the wept, lined the desk line to be specific and sending a post request. With this following you are a pattern with this instruction. Basically, we're trying toe similar it sending Jason as part of the request body. So we said the content type to Jason, but it would be the just in the presentation off this product and finally with the call to this method, I'm trying to send the request and then I'm checking, deceive the status corresponds to to except successful any extra devastate. Er's have stopped to would correspond to a success message. And so this death scares would pass. I've old around the desk is and it's working can actually see it all here, the next test cases to retrieve a specific product. So again we have product object created and that I'm trying to use the depository mark object in order to set a specific response for a particular called him at the and again, I'm using WEP lined in order to send and get request. But this following you are a pattern. We're sending path variable as one and just off the stuff. It's pretty straightforward. So this method is going to respond back with the product that we want to retrieve, which will be represented in the form of Jason and from the response body. I'm trying to see if we indeed have the right object which got retrieved. So that's how you dust your reactor applications over. It makes sense 55. 1013DrawbacksOfReactiveProgramming: Let's talk about some of the drawbacks off reactive programming specifically in the context offspring framework and Web flocks, and try to understand when to use the 10 men not to use it. First of all, the interweb stack needs to be known. Blocking. I mean coming to micro sources. If at least one services not reactive in nature than it might actually impact all the downstream nodes are the downstream services that rely on that particular service. Or if you don't have a react today, the best driver, then you're not reaping the benefits off reactor programming. So that's one drawback. And secondly, reactive programming might be an overkill if scalability is not an issue for you. I mean, if your applications not deployed on cloud in Roman and not using docker continual ization , etcetera, then you may not be needing the react to approach. It might be an overkill. And compared to traditional embassy libraries, the libraries that support react to programming are pretty limited, which may also limit the scope off your project and typically react to programming requires a steep learning call, and it takes a while for teams to get used to the reactor style of programming. Well, this shouldn't be a drawback if it is me who is teaching, though. And finally, you need to use another library in order to write unit tests well on top off your existing Janet libraries here to have some additional libraries in place in order to write Janet's for your reactor programming. So these are some of the drawbacks based on these factors you can consider, but they want to go with reactor approach. Our traditional approach hope it makes sense.