Building REST APIs with Spring Boot

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
how do you communicate with other people if they do not understand the language you speak or say with animals whose language or gestures you do not know about this is a diverse world it is but we know this communication is possible the question is how efficient it is now let's talk about our code how about the diverse distributed systems that you build and as developers how do you make them talk with each other on the internet efficiently restful web services is one of the answers to this problem hi everyone thanks for joining in i'm your host mala gupta and in to today's session you'll see how to build rest apis in java with spring this is a live coded session so you get to see all the talking in action and by the end of the session you'll know how to create a basic crud rest api in springboard you'll also learn about some of the best practices to create your apis now let me add our speaker to the stream hi and welcome dan it's a pleasure to have you present with us today well thank you so much for having me mama so happy to be here great and dan has been building applications for the web for almost two decades now and i wanted to say this his superpower is problem solving so here he is helping us to build uh the crowd applications that we talked about uh and before i let dan take the stage here are a few housekeeping details um everyone who's watching the session please use the youtube chat to post your questions yuri from jetprains i and dan would answer your questions also during the session and also towards the end of the session the session is being recorded and it will be hosted on our youtube channel so if you haven't already subscribed to our channel now is the time to do that and if you like today's session which i'm sure you would do because dan is live coding please like the video so dan let me add your screen to the stream and good luck all right thank you thanks again mala for having me i appreciate it i'm excited today today we're going to be talking about building rest apis in spring boot my name is dan vega i'm a spring developer advocate with vmware today i just want to get some things out of the way there's going to be just a few slides to kind of set the stage and what we're going to talk about i want to be very upfront and say today is really a beginner focused presentation on building rest apis with spring boot now even though that it's kind of beginner focused i always like to see if you can come away with one or two kind of nuggets out of a presentation then it's well worth sitting through so go ahead and throw this on in the background if you're working and see if you can pick up a couple things like i said we're going to do a lot of coding i just have a few slides to go through to kind of set the stage for what we're going to cover today so really we'll just get into a quick introduction of who i am in case you don't know at a high level i want to talk about apis and rest in general i don't want to get too bogged down in the weeds of what we're what we're doing as far as you know rest goes i'm very much at least my style of teaching is kind of moved to this is let's talk about the mechanics of how we're going to build these things today we'll get into the weeds of like more rest principles later on but let's learn the mechanics first instead of spending 30 minutes on slides and learning principles of rest so this will be a good time to just kind of give that a high level overview and then we'll get into a lot of coding today when we leave here today i'll give you some resources some kind of next steps a little bit of a deeper dive into some of the topics that we talked about today and then some of the things that you can learn after you kind of learn this there is a github repo for this you'll see the link there github.com dan vega building rest apis in spring boot that contains all the code that we're going to cover today so a little bit about me i'm a husband and a father there's my beautiful wife jen my two daughters isabella and juliana we live right outside of cleveland ohio i've been a software developer for over 20 years and in that span held a variety of titles from web developer to senior engineer to a curriculum developer to principal architect and now spring developer advocate and this is really kind of a culmination of all of those things and really a dream job for me i've been a huge fan of spring and the ecosystem for a long time now and this is what i get to do every day now is talk to you guys talk to customers and help them find solutions to problems using uh the different projects in the spring incu system so really excited about this there's gonna be a lot more presentations coming up so if you want to please go ahead and follow me you can follow me over on danvega.dev i'm a blogger a youtuber course creator and as i mentioned before i live outside of cleveland and i am a cleveland sports fan which is why i tell people i'm usually miserable so let's talk about apis so at a high level we if you don't know api stands for application programming interface and in the world that we live in today at the heart of all the applications we're building is data and and what's really important about that data is being able to share that data out right so we are there you know microservices are a big term big buzz these days you know the last position i was at i worked for a top you know fortune 50 company and they were moving a lot of things to microservices and there are so many microservices across the the enterprise and they need to talk to each other some way you know there are a couple ways to do this you can use a synchronous api in the form of say rest if you need to make a call to another service and get some data back you can use asynchronous if you start getting into event driven architecture and you want to just throw something out there and and wait for you know communication back uh using something like kafka or rabbitmq so there are different ways to talk to these different microservices one of those ways is obviously through say a rest api and it's becoming even more and more important with all the different devices that we're using so it's no longer just the phone in our hand right our tvs can have computers in them now uh microwaves bathtubs i mean it's crazy the things that are getting chips in them these days so all these different devices need to talk to something to get data down or push data up right and this is done through through apis so that's an api what is a rest api so it's important to understand that a rest is more of a guideline than a protocol rest uses the http protocol and then define some constraints on top of it it's also important to know that rest is not this definitive thing you don't need to like there are some principles we'll we'll kind of talk through some of them as we're building this out there are some principles but these aren't like hard rules like you must do this or you are not rest i mean some people will tell you that but at the end of the day you try to strive towards rest once you get past some of the beginning kind of crud features after you're done filtering and paging then you start to blur some lines and to be honest it's okay um you're just trying to strive towards you know striving towards some of these principles right so there are six principles of rest you'll see them in work today but i'm going to leave you a resource to go ahead and learn more about them after today's presentation there are also building blocks of rest things that you need to understand like http methods status codes urls etc so we'll cover some of those and again like i said that's all i really had as far as slides go i want to get into some demo here and build something out so let me just make sure we are here again this is the repo if you want to go ahead and follow along don't need to code along today you know i suggest just kind of watching this you can come back to this code later and again if you have questions go ahead and throw them up and we'll try to get to them throughout this demo so to create a new springboot project we all know you should know that you go to start.spring.io and i want to show you this great little feature here you see this little blue star this little blue star means i favorited it use it use that in your browser because you're going to visit start.spring.io a lot so why not go ahead and bookmark it so here we are on the spring initializer and what we're going to do is we're going to provide some metadata about the project that we're going to create so i'm going to go ahead and choose maven and java and then the current version i'm going to just put some data in here so dev.brandvega call this uh streams schedule and then we need to pick uh if you look down here gar and then we need to pick a version of java so this is a good time to mention that at the end of this year sprint framework 6 and spring boot 3 are coming out and one of the big changes in that is going to be at a baseline of java 17. now this may seem a little crazy but the world that we live in now with java is changing so frequently now this makes sense and i mean java 18 is going to come out next month it's just crazy it's a great time to be a java developer with all this change happening and additions and performance schemes to the language so we're going to select java 17 here and then we need our dependencies so i kind of uh liken this to throwing a dinner party so if i was going to throw a dinner party i might prepare some type of menu i'm going to say we're going to make some pizza we're going to have some wine some cheeses so if i'm going to grow this dinner party with those things when i go to the grocery store i'm going to write down all the ingredients that i need so whatever i need to kind of make that dinner happen i'm going to put on a piece of paper i'll probably group them together by the layout of the store i go to a lot so i know that i'm not like inefficiently walking around right but i have an idea of what i need to get when i go to the grocery store same thing with my application i kind of know what i'm going to build today so i know what things i need to add to this application now if you forget something at grocery store you can always go back to the grocery store same thing with here if you forget something you can always add it later right so what we're going to build today is just a simple api that allows me so over on my live stream a lot lately i've been building out a way for me to build a schedule of all the live streams so that i could throw this on my website anybody who wants to come check that out and see when i'm live coding next you can go ahead and view that there so we'll kind of build an application around that idea so when we add defense dependencies we need to figure out what we're going to be building so in this case our first one is we can choose between spring web and spring reactive web so spring web is traditional spring nbc uses tomcat with the default as the default embedded container if you wanted to if you were getting into any type of like blocking i o talking to databases talking to other apis reactive web is a great solution for that because it moves away from the traditional thread per request model so you can look at that but today we're just going to stick with web because what we're doing is um pretty simple now one other thing we're going to need is as we are accepting data from people so if we want to create a new resource or update a new resource we're going to ask for input from someone and what we need to do often is we need to be able to validate that data and it used to be that the validation dependencies were right there embedded in the web or the web mvc dependencies that is no longer the case so if you're going to do validation you need to make sure you search for validation and here we're going to go bean validation with hibernate validator some people get tricked up by this just because hibernate validator isn't there doesn't mean we're using hibernate so we're not we're not using spring data jpa or anything right now today we could move to that obviously and we should once we start to introduce that stuff we're just going to be using some in-memory representation of our data but that beam validation with hibernate validator is what we need to create this project so at this point you can click explore this is an awesome feature that i love being able to see kind of what this palm looks like what are we pulling in what is the structure of the project and it's important to note that we're not generating code like there is some code in here that we're going to start with but it's not generating like some entities or anything based on what you've selected this is really just bootstrapping your application and getting you up off the ground up and running as fast as possible so at this point you could generate this project and open it up in your favorite text editor or ide but at this point i want to show you another way to do that and that's with the fine folks at intellij i promise you they are not paying me to do this um i am a paying customer of intellij i have been for a long time just for my personal projects because i just think it's a fantastic ide so i am using the intellij ide the ultimate edition today if you're going to use this startup the the new spring project wizard that we're going to go through today you do need the ultimate edition but if you have the free community edition that's fine too you can just use start.spring.io like we just did and open it up right there in the community edition so um another thing i really love about intellij is that you know i was talking to a friend over the weekend who is new to cody he's learning how to code and he's a java developer who is working on android projects and one of the things he told me was he really loves the fact that like when he writes some code in intellij there's little hints on like how he could refactor his code so like hey when you write a for loop hey you could probably turn this into a stream and filter and map and reduce on that or hey this would be a good opportunity to use a lambda function so i've always told people that but it was really great hearing from someone else that like he really enjoys that fact of intellij so big fan of intellij we're going to use that today i'm going to go ahead and click on this new project and we're actually going to build out the same thing we just did on the web so i have a stream streams schedule we're going to use java we're going to say dev.dan vega and again we're going to pick java 17 we're going to use jar as josh would say make jar not war directory is empty that's okay so again we're going to come in here and pick our dependencies we're going to use spring web we're going to use validation and we're going to click finish so the first thing that i like to do when i create a new application is i want to just come in here and make sure that it runs i'm going to make sure that some nothing weird is going on and that my application is able to run so i'm going to go ahead and click start and there we go our application is running on 8080. great so let's go ahead and hide this and i'm just checking to make sure there are no questions um okay so the first thing we're going to look at is just the palm xml real quick um this is using maven so maven generates this maven has this uh maven build tool has this and if you're new to springboot one of the things you might look at this go wow there's really not a lot of dependencies declared and that's one of the great things about spring boot is that that's how it helps us get up and running so quick is these starters so um the starter spring boot starter web if you have ever tried to build a web application in spring without boot trying to figure out all the dependencies that it takes and custom you know configure an embedded tomcat container it's kind of a pain in the butt so if you click in here you can see that this starter actually includes other starters and includes other dependencies and so this is how spring boot one of the things the kind of magic of spring book and how it's able to get you up and running uh really quick so that's our application it's working i thought that we didn't have anything here sorry about that i must not have deleted our starting code but no big deal this is actually good because now we can keep all of our packages there and we'll build this out together so here in the model directory so the first thing that we're going to do is really start with the model of our application going back to kind of domain driven design we're all trying to to speak the same language when it comes to our applications we need to model our application based off of something that we all can kind of talk about together right and in this case again we're building a live stream schedule api so i want a place where i can create new live streams have properties on it like the title the description the start date the end date what we're going to do in that live stream and then be able to display that on a web page somewhere so i'm going to create this here in our application and then make it available through an api so that anybody can kind of pull that schedule down so the first thing i'm going to start with is a model and what i want to do is actually go through kind of a traditional way that we might have done this in the past and show you how we can kind of improve upon this so i'm going to name some things a little funny here this is going to be called a mutable live stream and if you know the difference between immutable and immutable then you'll kind of understand where i'm going with this but what i want to talk about is okay this is our live stream what are the different properties that are going to be within our live stream so i'm going to go ahead and create our mutable live stream whoops this is our props live stream props so these are the different properties that we would have in a you know in a model that represented a live stream we'd have an id a title a description a url a start date and an end date and if you start to see some of these hints that come up that is actually github copilot trying to code for me i leave it on because i like to tell people about it and actually does help me kind of shorthand some things as we're going um but if you see that pop up that's what's going on okay so now that we have a um all of the properties we would normally just create maybe a no our constructor we know there's an implicit one but i'm going to just create one anyway we might create getters and setters so i'm going to come in here and create getters and setters for each of the properties in our mutable live stream i may come down here and create a equals and hash code so we're just going to generate all of this code yep looks good let's go ahead and do that and finish and of course i probably need a two tostring so i'm going to generate that as well so so far so good so we have id title yep so far so good so now that we have this live stream i want to go ahead and write a test for this and actually i might have these tests in place already so that we don't have to worry about writing these out i do see okay that's why but here let's go ahead and just get rid of these for now um i do have a test here to test out our mutable live stream so we created you know this is how i would normally you know how i used to do it in an application i have a mutable live stream object i call it a stream and i create a new instance of it using the noir constructor and then i go through and i kind of set all the different properties on there right so i'm setting an id to just a random uuid and getting the string version of that on setting a title a description so one of the you know again we've moved on to java 17 we're starting to use some of the cool new features in in modern java one of those is multi-line strings having a bunch of text that had to be escaped into the next line that kind of juggling our code right now we can just kind of use this multi-line string and we have this big description here i'm setting the url i'm setting a start date and end date and i'm just saying hey make sure that it's not null and make sure that the title that we have here is what we think it is so if we were to go ahead and run this that passes but the problem with this object is is that somebody can come along later and say i want to set the title to something else so now if we run this again obviously this is not going to pass because we've changed that title so this is how we've kind of traditionally built out a model right using something that is mutable now what we could do uh what we what we have done is we can move to let's say an immutable live stream and so again we're going to have those same properties that we did before so live stream props the only difference here now is when we want to build an immutable object what we can do is we can go ahead and say i'm going to select all those and i'm going to say these are final these are final okay i don't want these to be changed after these are created but again intellij is helping us out and saying hey you probably want to add a constructor perimeter and you're going to add a constructor to go ahead and set all these fields so now once you set all these fields they cannot be changed so now instead of generating getters and setters we're just going to generate getters here right we don't need our setters because if we try to create a setter here intellij is going to tell us again hey you can't do that you know you've marked these as final once they've been set you shouldn't you shouldn't be changing them again we can come through and say let's generate an equals and hash code and we'll do that and we'll do that and boom boom boom boom and we'll finish and finally we'll go ahead and create a to string and we'll save that so now we have an immutable live stream so let's go back to our test and take a look at this so now we might have a rest test to create an immutable live stream now in this case we're creating an immutable live stream stream equals new immutable live stream and we're passing all the properties that we want to build to our constructor so i'm passing in a uuid a random id here's the title here's that description again i'm using that multi-line string the url the start date the end date we're checking that it's not null and it's and that the title is what it is and this should pass and again this now prevents us from creating this object and somehow changing it later now the reason i bring all that up is because uh you know that mutable that immutable live stream that we just created was great that was a good step forward it was still a lot of code and i know there's things like lombok out there to cut some of that down but you know there are there are things you got to configure within your ide to get lombok to work and quite frankly i just want to write like code that is concise and that is kind of following some of these best practices and so what we can do here in java 17 is use something called a record so let's just go ahead and call this live stream but we're going to choose record instead of class and in here we're just going to go ahead and pass in some props so all these arguments are the same ones that we used back in those other two model classes but now this is all i have to do i don't have to figure out how to write a make sure that all of the fields are private make sure that we have a constructor that accepts all of them make sure that we have getters uh equals and hash code tostring all that stuff that was kind of boilerplate before we don't have to do that now so now if we go back into our test let's go ahead and check this out create a record now this code looks very similar to the one that we did before when we start to work with record classes though there are some things that we can also do on it if you want to uh you can call the git class and there's a is record method on there so you could say hey if you're if you want to find out if a particular class is a record or not you can do so all of those arguments or those fields that we passed into that record constructor there those are components so you can actually say hey get me all those components and make sure those are equal so if i run this this should pass and this also gives us a chance to go down into this target directory here look at classes and look at model and look at live stream and look at the generated code from our record so you see this is pretty similar right we have some fields we have a constructor that we can go ahead and create all of these items from and then we just have getters the only difference you may notice is you may write code that looks like get id or get title or get description these getters are just the name of the field so when you have an instance of live stream and you want the id you'll just say stream.id stream.title and so on so that is a record one more thing i want to show you about a record if you don't know if you come in here there are different so you can work with constructors still when you create a constructor here in intellij it's going to ask you do you want a compact constructor or a canonical instructor and so if you do a canonical instructor you know that's that's everything the kitchen sink everything is there so that's basically what was generated but if you needed to do some type of validation in there you could if you don't want to deal with all those fields you can go ahead and create what's called a compact constructor and a compact constructor says okay we know you're going to get all that information but if i just want to work with say the id if the id is equal to no maybe we throw some type of illegitimate argument exception right so you can do some kind of validation there in your compact constructor so that is all i'm gonna do for the rec for the models just checking here any questions so far am i still here all right so um yes sorry hi then i was reading through the comments so there are a couple of questions but nothing that i should be asking you now so i would let you move on with your flow okay okay sounds good we're doing on time good all right so now that we've kind of modeled our application we have the the representation of a live stream we know the the immutable one and the mutable one we're just uh things that we're playing around with but this live stream record has all the properties of a live stream like an idea title description url start date end date these are the the things that we're going to be the properties that we're going to be working with so the next thing we need to do is we need to create a new live stream controller so let's go into this controller package create a java class and we're going to call it live stream controller so in controller class right now this is not a controller class no matter so the the convention is to add the word controller on to the end of the class it's not a requirement but you'll probably see this convention a lot as you start to look at other people's code or look at open source project right now just because this name has a control on it this isn't a controller class we need to tell spring that this is going to be a controller class and more specifically that it's going to be a rest controller class so we're going to add on this annotation and this annotation is really just comprised of two other annotations you'll see this in spring a lot that there are a lot of annotations that are just rep you know uh making it easy and they're shorthand for uh composed annotations so in this case it's a controller annotation and it is also annotated with at response body so if you go into response body it just says hey this method should return the value that's bound to the web response body in our case by default what we're using is json so we're going to return json so now that we've kind of told spring that hey this is going to be a rest controller there's something else we need to do we need to go ahead and add this request mapping annotation and we need to give it a path so this is one of the things we're going to talk about really when it comes to those six principles of rest and one of one of those things is kind of a uniform resource right and when we talk about resources we we want to talk about um being able to build our apis that focus on a resource and in our case the resource that we're working with is a live stream too many times more often than not i've gone into code bases and seen apis that kind of just have you know methods all over the place and they're they're said to be rest apis and they're not what we're when we're talking about rest apis we're working with a single resource now a single resource could be in charge of other resources but in this case we're working with a single resource called streams so now when you hit slash streams that's kind of indicating that any method that we hid in here is going to be dealing with our live stream and you'll see as we start to build this crud application out all of them kind of fit under streams and then the way that it's these each of these methods are differentiated is by the request method so now the request mapping can go on the individual map methods but i like to set a base one here on the class to say everything underneath here is going to fall under slash strings that'll make a little bit more sense in a second so the first thing the first method that we might build out is we might build out something that returns a list of live streams and we can call this find all and let's just return null for now we'll talk about this and so what we want this to do is we want to be able to access this on localhost 8080 so by default we run on port 8080. we can change that through configuration if we want but by default that's what we run on and we want to run it stream so how can we tell this method that we're working on right now that this is the url the path that i want to be able to access this method on so here again there is a request mapping annotation that we looked at before there are also specialized versions of this because if you use the request mapping you have to say what http method you're going to respond to there are specialized versions of this where we're saying hey this particular one is a git mapping so this is going to respond to a get request at this address now you'll notice that i haven't put any other path in here i haven't said find all or whatever we just want to respond to localhost 8080 streams so if we do that because we've already set that request mapping up here we can just have this as a get mapping and that will respond for the find all method now we need a we need a way to get some data in our application right so should we go ahead and add it here should we go ahead and say well i'm going to need a list of live streams and we'll call this streams and we'll initialize this to maybe in a new an arraylist and maybe in our constructor i would go ahead and say this dot streams oh no sorry streams dot add and we'll say a new live stream and then we can fill this out and add a new live stream this is one approach that we could take um but it's probably not the right approach so when we talk about a controller a controller class again this comes back to spring mvc so this is model view controller and model the mvc pattern you'll find across whatever language or framework you're working with there's probably some framework out there that that kind of works with the mvc pattern the cnn stands for controller now controllers are meant to be thin and dumb they aren't supposed to do a lot they are supposed to accept requests and return responses so right here we're kind of already violating that when we're saying let's manage some data in here or let's do some other business logic in here you don't want to do that in a controller so i'm going to get rid of that and what we need to do is we need to move this logic somewhere else and where i'm going to move that is into a repository so i'm going to call this the live stream well let's type it right live stream repository i often misspell things when i am live coding so i apologize um so we're going to just go ahead and throw some code in here because if we were to type all this out this would take another hour but what i want to do is just kind of walk through what this is doing so repository similar to a dao pattern is just a a way for us to kind of encapsulate some data access in this case we're not going to talk to a database that's just going to kind of you know complicate things a little bit we're just going to have an in-memory representation of our streams so i create a list of live streams called streams initialize it to an arraylist and here in the repo in the constructor for the repository i go ahead and add a new stream again similar one to before it will have a random uid a title a description a url a start date and an end date then i have some methods to access that because again you don't want to have data access methods in your controller that should be delegated somewhere else we're going to do that here in a repository so find all is just going to return all of those streams in the collection there's a way to find one by its id so it's going to search for an id and return that there's a way to create a new live stream which basically just takes in a live stream objects and adds it to our collection there's a way to update one and there's a way to delete one so this is really just our data access and this is all going to be contained within this within this class so now what i want to do is talk about how we might use that data class right that repository class so i might come in here to my controller and say hey i need a live stream repository we'll call this repository and maybe in my constructor i might go ahead and create an instance of this so repository is equal to new live stream repository so this is one way that we could do it but this isn't a very good way to do it so there are a couple problems here now if that live stream repository constructor ever changes anywhere in our application where we need to where we've created a new instance of it we may have to go update those also if we are trying to write tests for this this is going to be a problem because you know maybe this live stream repository class is actually talking to a database if we're writing something like a unit test that tests just our controller out we want to get rid of all of those external dependencies right well you don't want to be testing databases in a controller unit test so you know the can when the constructor has created a new instance of it there's no way to kind of you know you could do some crazy stuff but there's no way to say hey that live stream repository that you're using let's go ahead and mock that out so for those reasons and a couple others you know anytime you start to use the new keyword in your constructor here when you're newing up instances of classes within spring that's generally generally a smell for me that hey we there's probably a better way to do that and there is so this is really a kind of a good time to talk about dependency injection so dependency injection is really one of those core concepts that the spring framework was built in built on so dependency injection and inversion of control and what inversion of control means is that in studying instead of us being ones being the ones responsible for creating an instance of that live stream repository we're going to paste place that control on the framework we aren't going to handle it the framework will handle it for us and really dependency injection is going to solve a lot of problems for us so let's take a look at how we might refactor that here so what i'm going to do is i'm going to create a final live stream repository i'm actually going to call this repository and now intellij is going hmm maybe i can help you out here why don't you add this as a constructor parameter so here is a constructor parameter now we're missing one thing here so for spring to really understand uh where this live stream repository is we have to tell it where it can find it and right now this class is not something that spring is managing so the way that we do that in spring is we can mark it with an at component if we dive into the at component annotation you'll say hey this indicates that this class these classes are considered candidates for auto detection when using annotation based configuration and class path scanning so which we are by default out of the box so all this is done is now said to spring hey please manage this for me create an instance for me and when i ask for one go ahead and give me one and there's also again specialized annotation for things like repository so i'm gonna go ahead and mark this as a repository when i come back over here to to my controller now i have a final live stream repository we're calling it repository and we're accepting this as an argument into our controller so this is going to use constructor injection um we want to so one of the things you may see in some code is coming up here and having this auto wired annotation here on the actual dependency that you're trying to inject and this is something you want to avoid it becomes very hard to say test things and as josh long says every time you mark every time you use field injection a unit test dies so don't do that as in spring 4.3 and above you no longer need to mark a single constructor with the at auto wired annotation it just kind of understands that hey if you have that single constructor that accepts a particular argument then we're gonna assume that you want us to go ahead and insert that for us so i'm just checking some just checking my notes here and checking comments everything looks okay so now at this point now in our method where we want to go ahead and get a list of all the streams we can go ahead and say hey ask that repository and go ahead and find all because there's a method in there called find all that will return all of the streams that we've set up in that live stream repository okay so let's try and rerun this oops sorry don't want to run that i want to run this okay and this has started on 8080 so now if you've created this um you've created this api one way to test this is you could go back to the browser and let's try and do that so one way is we can come back to the browser go to localhost 8080 and then go to slash streams so remember that's how we set up that that request mapping here in the browser because it's a get we can see the information that we're getting back it's an array of objects and that object has an id title description url start date and date so that's one way of doing it another way that i really enjoy testing out my apis here in intellij is by using intellij's http client again they aren't paying me to say this i just happen to love this feature anything i can do to kind of stay within the ide it helps me out a lot so if you hit this drop down nexus git mapping you'll see it says hey generate a request for me in the http client and what it does is it generates this localhost 8080 and it even figured out that the path that we need is slash streams so i'm going to delete that because i have a bunch of them kind of set up in here for us ready to go again this is just a get request to 8080 streams and if we click play we will see that our generated request is is done and we get the same information but unlike the browser we can test all of our operations like being able to create and update and delete so this is a great resource which i'm going to utilize as we go throughout this okay so we have to go ahead and just create some more methods in our live stream controller so now the next thing we need to do is we need the ability to get just a single uh live stream so let's say we want to we want a method to return a live stream and we may call this find by id and this may take in a string id and let's return null for a second now we need to annotate this with a get mapping again but now it's going to take a little bit more information now it's going to take an id and this is going to be a placeholder for an id so just like this one this is going to respond on a get request but it's going to respond on a get request with the id so it'll have that long like uid on it right so this little curly brace id is basically a dynamic placeholder and the way that we pull that placeholder out of there is by using a path variable so the path variable just says hey this argument that i've created string id please go ahead and pull that out of the path for me so it'll assign whatever this is give it to an id and then we can use that and we can now pass this over to our repository we can find by id and we can pass in our id and now if we go back over to our generated requests where first thing we need to do is we need to run the find all because again these uuids are generated so let's go ahead and grab that then here in the http client we can say all right go ahead and find me just this single one so i can go ahead and run that and that one is not found probably because we need to rerun this we didn't actually have that find by id method in there when the server was running so i needed to restart that for that to take place so with that it's going to generate a new id let's go ahead and grab that and then we'll just go ahead and paste that here and there we go so now we just asked for one single live stream and that brought brought that back to us so you can imagine a scenario where you have a list of all the live streams and maybe i just had a few properties and then on a web page you click on one of those to get some more detail about it this is that instance where you'd say hey give me all the details about that live stream because i'm just going to display one of those on a page cool just looking no questions i'm gonna keep going feel free maul if you want to bug me about anything or if there's any questions coming up so then there are a couple of questions i'm not sure whether you would like to continue with your session or would you like to answer them now yeah you can go ahead and if they're relevant to things we've covered uh we can go ahead and talk about those uh so one of the questions was uh regarding the auto injection and the field injection you mentioned that the josh mentions that it's not a good idea to do so so uh so that's one question if you want to answer it yep yeah so again with this approach right with this approach right here we are using constructor injection this is exactly the same as seeing this it's just implicit and what that does is now the controller the the controller's constructor accepts an argument of a repository so now when we want to go ahead and write a test and we want to write a unit test against just the controller again if that repository was talking to a database we don't want to those are those are external dependencies that we don't care about when we're testing just the controller so what we can do is we can create a mock of that repository and pass that mock in as an argument to our constructor and now we have a way to just test our controller if you if you use something like field injection you know there there gets you have to like you have to find a way to kind of mock that repository out and pass it in and then you're getting into all kinds of reflection fun which is not fun anytime you have to use reflection um unless you're some type of framework developer uh you're you're not going down a good path so i'm sorry what was the other question uh the other questions are more about uh what do you think about this topic or the other topic and the comparison so i think i would ask them to you towards the end of the session and i'll let you get on with your session okay cool so again we're creating crud here we've created a way for us to get all of the live streams we've created a way for us to get a single live stream the next thing we need to do is for a way to create a new live stream so in this case this might bring a live stream back we may call this create it's going to accept a live stream called stream and again let's just return null for a second so we can talk through this so the first thing that we need to think about is um in a create method we're going to accept a live stream but the way that we need to accept this is you you know most of the time when we're using some type of api we're going to be passing this data in through something like json right so what i want to do what i want what i need a way of saying hey i want you to bind the request body whatever is coming in in that json to this live stream i need you to create a new instance of a live stream based on that request body and the way we do that is again by an annotation that's called request body and so now that you know underneath the hood we're using something called jackson it's not magic it's really a really great project though and it makes all this so we don't have to write this mapping uh to make this happen it's just gonna say hey if i have a json object that looks like this live stream there you go i've i can now create a live stream instance out of that so that's the first part is getting that data in now we need to do is we want to so let's go ahead and do this we want a post at localhost 8080 streams so again this is coming back to the resource i've seen a lot of this in the past in in apis where you might have something like stream slash create and you don't need that um the stream is the resource so we're gonna we're gonna the path that we're gonna use is just slash streams but again we're gonna differentiate between this one and this one by the http request method so instead of using a get mapping now we're going to use a post mapping okay so we're using a post mapping there and one of the things one other thing we may want to do is you know we talked about some of the building blocks of rest applications one of those is making sure that we're returning the right response codes so when you when you're talking to someone and you're going through maybe you are at a restaurant and you order something if if you're ordering something say through a drive-through line and you say you want that chicken sandwich from chick-fil-a there's someone on the other end of that taking that request right and they'll be able to tell you right away sorry we're out of those today or okay i got one of those it's this much money go ahead and pull up when you're when you're working with an api the response that comes back has some information about that response one of those is a status code a status code is like telling you this is the status of the request that you just sent me when you're creating a new resource in a rest api it's good practice to return a 201 status code which is stands for created so that the caller knows that indeed that that thing was created and so the way that we can do that is we can use this response status and we can go ahead and give it an http status that created and that will tell it now when we return that hey let's use the 201 status code so now we can just call our repository our repository has a way to create a new stream and we'll go ahead and create it we go back to our http client here we're going to send a post to localhost 8080 streams we are setting the content type we're saying hey what we're what we're sending you is application json and this is one of the things i really love about this tool is that okay we're just generating uh back in our java code we were generating a random uuid and we can do that in java code just fine but how would i do that in say you know some type of http client well intellij gives us a way to do that using this placeholder syntax here and a uuid so it's going to create a new uuid for us and then we're just passing in the title the description url start date and end date so i'm going to go ahead and click run up and again i ran into the same problem which is that method is not there so let's go ahead and run that and let's run this and you'll see that the response was 201 so now if i'm a client and i call that i know that something was created okay so we have our created see how we're doing on time all right i'm okay we're gonna go here so the next thing that we need is an update so i may update this this is going to look very similar to live stream screen this is going to look very similar to kind of the method above in the create but instead of a post mapping now we're going to have a put mapping so we may have a url that looks something like that and to do that we're going to use put mapping and again we are going to be at slash streams slash the id of the live stream that we're trying to update so again we'll use that little placeholder syntax and then we can go ahead and say go ahead and pull that out using the path variable the same as we did that above in the get method now from a repository standby standpoint we can update we can pass in our stream and we can pass in our id one more thing i'll add to this is i'll add another response status a good practice here is to be basically say that nothing is there is no content coming back so you may have been you may have been expecting something but in fact i'm not sending back the updated live stream i'm just going to send no content back and then finally the delete will look something like this we'll have a public void delete and we're going to take in a path variable so this is going to be an id and so to do that we're going to use another annotation called the delete mapping and again all these are just specialized versions of request mapping this is going to look similar as one above we're going to use a placeholder a dynamic one so we can pull out that id and there's our id and we're also going to say hey don't expect anything back finally the repository is going to delete whatever id we pass in let's go ahead and rerun this and then go back to our generated yeah let's do this so it's gonna we're gonna go through and kind of test all of these so first let's make sure we can get all of our streams all right we can there's one stream if i use this id and i pass it to my find one can i get just that one i can if i wanted to add a new one can i do that i can there's our 201 saying it was created what i'm going to do is take that one that we just created i'm going to use that id and we're going to pass it to a put and so that put is saying hey i want you to go ahead and update that again we're saying the content type is application json and all i want you to do is change the title from my new live stream to new title and so if we go ahead and test that out there's a 204 says basically says okay there's no content coming back but everything seems like it should be okay if we run that we see our two in there and our second one has our new title and then finally we want to take that second one we grab that id from there and we are going to delete that one so let's go ahead and send a delete request again we should get a 204 saying no content which we did if we go ahead and run our find all we see that we only have one in that array so that's kind of the crud of building out a controller now again this is kind of the first steps of it there might be things that you add to this like paging and sorting there might be ways to like filter on specific data or search through specific data but this is kind of where you start if you're building out kind of a crud api one thing i did want to mention is you might see some code that that looks something like this so we have um [Music] entity and then a live stream so you may see a signature that looks like this and if we look at response entity this is really just an extension of the http entity um and this allows you to kind of control the response that is going back in our case i like so so when i'm sending back a particular live stream i'm just sending back the data of the live stream but let's say that you needed to manipulate that response that is going back maybe you needed to add some headers or some specific your own specific header or something to do with like authorization or authentication if you need to manipulate the response that is going back then you can use this response entity type and so you'll see that in all in a lot of apis that you're that you're working with so i think that's it for the controller i know we're coming up against the time but i just wanted to mention one other thing so we talked about the ability to validate data that's coming in right so if you have a create method here and you want to say all right well i don't want just any data coming in from a live stream i don't want you to be able to create like an empty title or an empty description like i want to validate that one way that we can do that is by coming into our record and if you didn't know you can actually validate you can use spring bean validation so remember that dependency that we included earlier will work in records as well it's not just for kind of regular normal classes that you create you can use validation annotations here in in this as well so what we could say is that we want to control the title and we want to make sure that this is not going to be empty so again there are if you look in the javax validation constraints package there are a bunch of validations that you can use like email or i want to make sure that it has a max or a min this one that i'm using which is not empty past or present you can follow a particular pattern it could be a specific size so there's all these constraints i can put on there and now if i go ahead and were to pass in something into this controller i'm just going to go ahead and mark this with at valid and now when i go ahead and accept that data it's going to have to pass those constraints so one of those constraints is don't pass me an empty title so if you pass me an empty title it will go ahead and throw throw an error and won't let you create that new resource [Music] so i think that's you know i wanted to get more into validation but i know we're running up against it and then just one final thing i wanted to show you if you look in the repository so let's find that if you look in here if you look in tests where are we source tests yep controller now we went through and we were able to use the http client right there in intellij and test a lot of the things that we're doing so i typically do this i just want for my sanity i want to know that things are working as expected but there isn't an http client on your cicd system right there's there's a way to run tests and make sure that things work so on top of that you'll also want to write tests against these different methods these cred methods that you're that you're creating so in the code that you can pull from the repo here's an example test of how i'm testing out those different methods so if you want to take a look at that that will help you out as well all right so with that um i just wanted to leave you with some resources so kind of what is next we've kind of learned a lot of the basics what's next here's a link for a deeper dive into what is rest again there are six principles of rest we started to cover on some of them today even though we didn't name them by name but there are six things that you want to kind of think about when you're building rest apis things like they need to be stateless and you know there are six of these things that you want to conform to so take a look at that if you want to deeper dive into that there's a couple spring projects that are really great if you're starting to build out apis if you want to start documenting apis so if if you're working in an organization and this team needs to understand what your api does you want to document that and one way you can do that is with swagger or spring rest docs our friend mala here we talked about java 17 today um she has a really great video on learning some of these java 17 features with intellij idea so i'd advise you taking a look at that again we're moving towards java 17 in the spring world this year so it's good to start to get up on on all the features that you're going to be able to take advantage of when you move to say spring boot 3 and spring framework 6. and finally when you're working in an api there may be a scenario where you need to call another api and for that you'll use something like the rest template in a spring mvc project or a web client in a webflux project so i think that's all i got i wanted to cover a little more but i know we're out of time so again thank you and at this time i can go ahead and answer any questions you have thank you so much dan that was an amazing presentation and we have loads of questions i'm not sure whether you're going to be able to take all of them because yeah i have a few minutes so we're good okay okay um so uh so the first question that i want to start with is of course we were kind of i was expecting this question comparison about uh the rest and soap so how they both are different and did soap die so your opinions um so you're probably asking the wrong person because i haven't touched soap or rpc in probably five to seven years now um now with everything you know if you're just gonna build a new application i i don't know why you would reach for soap but we don't all live in this great world where we can use new tools all the time so at the enterprise world you may definitely be still dealing with soap for me this is just a much easier approach uh i don't i don't have a good answer of how they compare to each other but um i have nightmares about soap stills um yes just to i mean i guess i messed up with the sizing of my windows yes just give me a moment oh my god i can hear you but i cannot see you that's funny oh i'm here i think yes and i i just want to add uh to the answer that you just had so soup is doesn't work uh with a lot of languages it's it's not so fast so developers would have issues with the performance and they would not be able to use jason a lot so a lot of constraints so yes as dan said if you are planning to write your applications today please prefer rest over soap um the other question was about uh new features for the rest api build uh in the recent spring versions if you want to quickly answer that question um what what new features are are they talking about specifically so that's kind of an open question so developers are always excited to find out what's new with this uh language technology so if there are um i honestly can't think of any alpha top my head um i'm probably missing something but um i will have to get back to you on that one no no thanks we always have for these kind of questions uh you know again the i think the biggest new thing for me is you know again we're moving towards java 17 so just being able to take advantage of of all the new language features you know i'm really looking forward to to spring boot 3 and hopefully seeing a lot more companies get off of java 8 and java 11 and move towards java 17. so for me that's going to be the biggest you know thing that we kind of start to adopt this year yes make sense and a lot of attendees were kind of blown away with the plugins that you were using and of course uh you were using live templates you had the auto completion with github go pile up copilot and they were absolutely blown away we had so many questions about what version is dan using uh and how can i have that grey code auto completion in my ide well thanks thanks for the tee up uh again as i said at the beginning of this conversation i am a huge fan of lj i've been using it for you know a long long time now i'm on the latest version of intellij well maybe not the latest uh we are uh 2021.2.3 so i don't think that's the latest this was october of last year um but that's what i'm on but again it is all about if i don't have to leave the ide to do something i feel like i'm more productive right so the http client was a perfect example of that i've used tools in the past like postman or even the browser to kind of view the json data i don't need to do that anymore so the more that i can just stay in here and get away from the second i open a browser i don't know about you but my mind goes to let's see what's twitter let's see what's going on twitter now there's just all these distractions so if i stay within the code i feel like i'm more productive so that is one thing live templates are such a great thing especially for when you're giving demos there are a lot you know if we were to write out all the code that we that we went through today i feel like this would be like a two and a half hour presentation and nobody wants to watch me type out all that code so you can easily create live templates in um in intellij and you can break it down into different groups so for me this is under spring boot and this is under a specific template folder uh so you can keep those so if i give this presentation again i can kind of use that the other thing you can do with that is create a live template for what a crud controller looks like right even if you're not using the same like customer employee live stream you could create a live stream that says just create me some crud methods in a controller so that i know what they look like so anything that you're going to reuse over and over again temp lifetimes are great for and finally github copilot is just a wizard so i use it here in intellij and in visual studio code when i'm doing some javascript work and the more and more i use it the more scared i am of losing my job because it just like it is it without even giving it context it will start to try to figure out what i need to do if you give it context and you start if you if you annotate some of your methods with a comment saying like hey um this should take um two numbers and return the sum it's gonna write that method for you and as you saw as we got into some of that even just being able to go oh repository the name of this method is create you probably want to call the repository create method and it figured that out so it's really like an auto completion that is thinking for me which which is amazing so yeah take advantage of plugins look through you know the intellij plug-in community and find things that work for you you know be more productive that way just find one little thing every week use it learn it and then move on and find another one and the more of these you can get used to and the more keyboard shortcuts you can get used to the more productive you'll be absolutely and i would request you to add the name of the plugins that you were using probably in the next presentation that you give because there's so many questions regarding all of those yeah so that's actually pretty easy uh if you go to the github repo i will go ahead and update that later today with in the readme with the plugins that we're using um so after this video comes out the recording of this video i'll add that and read me as well but then i'll add those plugins so so that you guys have them that's that's great um so um then i would take just a couple of questions and if you think the answers are too long probably we can skip those uh okay so so the first one is uh could we discuss which uh dao abstraction now is better to choose repositories jdbc template or any other and what are the pros and cons in each yeah that that is a long question so it but again it depends what you're doing um you know there's so so especially in the spring world there there's this great spring data umbrella that has all these projects under the spring data umbra and you know we can choose different projects based on what we're trying to do what are the constraints on our project so that for me really goes on a case-by-case basis like what you're trying to do and i don't think i have one blanket answer for that i i get your point um so would you like to briefly talk about service versus repository i think that would yeah yeah so for for me you know a dao or a repository is something that's encapsulating data logic right so i in in i'm i'm responsible for doing something with data in our case it was just an in-memory representation of that data but the repository is the one that is going to be in charge of finding all the data finding a single one a service for me is business logic about our application so if i need to say send a notification about an order that was just placed that kind of goes into service service is really my business logic layer i like to encapsulate data stuff in say a repository or a dao then we have a lot of other questions but they are going in so many different directions someone wants to know the best resources to get started with spring someone wants to know about the rest data and there's so many questions and of different levels so um it's kind of difficult to ask all the questions because they're going in all the directions so what i do is i i was just going to say um let's find a way to answer them though but maybe not today um so if you want to you can reach out to me on twitter that is not the first time i've gotten the question how do i get started with spring so this is something i definitely want to address now that i kind of get to do this every day that is a question in a video or an article that i want to go ahead and address so i will try and get to that one but i would say the best thing to do is to reach out to me on twitter or send me an email i know i'm opening up some floodgates here but send me an email danvega gmail.com and send me an email with your question and what i can do is i've kind of been putting these questions together on just like a notion board but maybe we'll get like an ask me anything type of github repository for all these questions to go into but i'd love to answer these questions so if you if you have some more context and like hey this is the application i'm writing here is my question or just a general question on how to get started with spring i'd say the best place to find me is on twitter and what i'll do is i'll start putting these questions together and find ways to get them answered that sounds great thank you so much uh dan amazing session i i managed to learn a lot in the session and um so if if you have any yes one thing that i forgot to mention dan now works with the the spring as spring that advocates so he gets to work with a co-team uh who is working on spring so if you also have some feature requests you can uh best done about it no that's not the right one you you can paint it and request it yeah you could throw them my way and hey maybe that feature already exists and you just didn't know about it yes i was about to say that yes that makes a lot of sense so thanks everyone for attending for asking the questions and for being here saying hi and i really hope you enjoyed watching the session and learn as i did so thank you so much dan and thanks everyone thanks so much for having me appreciate it thanks everyone for coming by thanks everyone bye you
Info
Channel: IntelliJ IDEA by JetBrains
Views: 57,353
Rating: undefined out of 5
Keywords: webinar, intellij idea, rest api, spring boot, java, crud
Id: q_RLfOB7axQ
Channel Id: undefined
Length: 76min 44sec (4604 seconds)
Published: Wed Feb 16 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.