Full Stack Development with Java Spring Boot, React, and MongoDB – Full Course

Building a Front End with React: Creating Components and APIs

To build a front end using React, we need to create several components that will enable users to interact with our application. In this tutorial, we will create three main components: movie component, reviews component, and review form.

First, let's create the Movie Component. The movie component will enable users to view details about movies from other users as well as add new movies into the system. This entails making an HTTP POST request being made when a user clicks on a "Add New Movie" button. From our React component to the relevant remote API endpoint carrying the movie data entered by the user, the server-side Java code will then save the movie data appropriately in a MongoDB database.

Next, let's create the Reviews Component. The reviews component will enable users to view reviews from other users as well as add new reviews for movies into the system. This entails making an HTTP POST request being made when a user clicks on a "Add Review" button. From our React component to the relevant remote API endpoint carrying the review data entered by the user, the server-side Java code will then save the review data appropriately in a MongoDB database.

We need to create three main components: movie component, reviews component, and review form. The first step is to create a folder named review form. Let's create a file named reviewform.js within the review form folder. We'll include the code for the functionality we have just discussed. This includes creating a form component that contains a text area control where the user can enter text that denotes a movie review.

As a next step, let's create a folder named reviews. Let's include a file within thereviews folder named reviews.js. We'll include the appropriate import code at the top of thereviews.js file. Then we'll generate the appropriate boilerplate code for the reviews React component by typing in RFCE and then pressing the tab key.

We will use the useRef hook to reference the text area control within the review form. Let's use the useParams hook so that we can extract the movie ID parameter value from the relevant URL. This movie ID is actually the IMDB ID of the movie that we have retrieved through the API call that is made to retrieve the array of movie data from the server.

We want to call a method that is passed in as a prop to our component when it first loads. This method will be used to retrieve the appropriate data for the relevant movie that the user wishes to review. We can use the useEffect hook like this for this purpose. We will also use React Bootstrap components, such as the row and col components, to create an appropriate layout for the reviews component.

We want to display the poster for the relevant movie in the left part of the screen and the reviews in the right part of the screen. We can use the row and col components appropriately to achieve this. We'll include the review form element here like this.

Next, we need to create a method named addReview and create the relevant HTTP POST request functionality for adding a review to the MongoDB database which resides on a remote server. We will write code to update the state of the reviews array on the client side, optimistically meaning that we are not using data returned from the server.

We are updating the array directly from the data entered by the user on the client side. We also want to include code that clears the relevant textarea control once the user has successfully submitted a review. Once the user has submitted a review, we will update the state of the reviews array on the client through the use of the setReviews method that will be passed as a prop from the app component.

Now let's go to the app.js file and create a method that uses Axios to make a GET request for data pertaining to a single movie so an IMDB ID value will be passed into this method to the movie ID parameter. Using the movie ID value appropriately in the URL, we'll make a HTTP GET request to retrieve data for a single movie from the remote server.

Let's set the state for the movie variable and extract the reviews array from the movie data and track the state of the reviews array. We need to ensure that the appropriate props are being passed down to the reviews component. By doing this, we will be able to create reviews for the movies retrieved from the remote server ultimately from a MongoDB database that stores our movie data.

So we are adding review to our MongoDB database through an appropriate HTTP POST request to an appropriate endpoint.

"WEBVTTKind: captionsLanguage: enIn this course, you will learnhow to create a full stackapplication using MongoDB forthe database, Java and SpringBoot for the back end and reactfor the front end. Farhan HasinChaudry teaches the backend section of this course. AndGavin Lon teaches the front endsection of the course. Boththese instructors are veryexperienced and have createdmany popular courses. Theproject featured in this courseis a great example of thecreation of a separation ofconcerns between the client codeand the server code. Byimplementing a loosely coupledarchitecture. These two partsimplemented using differenttechnologies can evolve inparallel and independently fromone another. So let's startlearning from Farhan. Hello,everyone. Welcome to the Javawith MongoDB course on the freeCodeCamp YouTube channel.I am for Han has ensured threeone of the instructors in thiscourse and I will teach you allabout developing a back end APIusing Java EE Spring Boot, andMongoDB. The other half of thecourse will be taught byKatherine lOn. Hi, I'm GavinlOn. I'm a full stack developerand have over 20 yearsexperience working as a softwaredeveloper. In this course, I'mgoing to be playing the role ofa front end developer. And myresponsibility will be todemonstrate building a front endusing React js. The Spyapplication that we are going tocreate will use HTTP GETrequests to appropriatelyretrieve data from a remoteserver through communicatingwith the relevant API'sendpoints. And HTTP POSTrequests will also be made tothe relevant endpoints toappropriately save data on theserver side. Of course, our datawill be stored within a MongoDBdatabase on the relevant remoteserver. So without further ado,let's jump in and start workingon our API. In the beginning ofthe course, you will have todownload two new software's fromthe internet. The first onebeing Java Development Kit, orJDK. If you already have JDKinstalled on your system, youshould be good to go with that.But just in case you do not haveit installed, I'd suggest younavigate tooracle.com/java/technologies/downloadsThe link will be in description.Once you have landed on thedownload page for Java, you mayfind multiple versions of JDKavailable as of the recording ofthis course there. The latestversion is Java 19. And thelatest LTS version is Java 17.lts C stands for long termsupport and JDK 17 will receiveupdates until September 2020 ForJDK 19 On the other hand, willreceive updates only until March2023 and will be superseded byJDK 20. In many cases, when youare deploying a Java applicationon a production server, it'ssuggested that you use LTSrelease for better stability.And for this course I will stickto Java 17 Since that's thelatest LTS. Now depending onwhen you're watching thiscourse, there may be a new LTSrelease so feel free to downloadand install that. So I'veswitched to Java 17 And since Iam on Windows, I will go towindows and the 64 bitinstaller. As you can see, it'sonly 150 2.85 megabytes anddepending on your internetconnection, you it may take afew minutes to download.Once you have downloaded theinstaller, make sure you haveinstalled it on your system likeany other software you have donebefore. And since theinstruction is sostraightforward, I will notspend a lot of time showing youthe entire process.After you have finishedinstalling JDK on your computer,open up your terminal window andwrite Java C space double dashbarsha.And if you don't get any errorsfrom this command, this is apositive sign and as it saysJava C 17 point 0.5 whichindicates that I havesuccessfully installed sevenpoint 17 point 0.5 version ofthe JDK. Now Java C is the shortfor Java compiler which you mayor may not have already guessed.Apart from this command, you canalso use Java double dashversion to check the version ofyour Java Runtime Environmentand as you can see it says 17point 0.5 lts which means we aregood to go.Since you have successfullyinstalled the jdk on yourcomputer Next up you will need agood code editor or IDE. When itcomes to Java, there are plentyof options out there. You can gointo Eclipse or maybe configureVisual Studio code. But I wouldsuggest that you go withIntelliJ IDEA. Now the people atJetIan's are known for makingreally good IDE s and when itcomes to Java IntelliJ IDEA ispretty much the industrystandard.Although the ultimate versioncan cost you some money, thereis also a free version availableby the name of CommunityEdition. Or to download IntelliJIDEA, navigate tojetbrains.com/ideas/download.Again, the link could be indescription and look for theCommunity Edition. This is theflag download button here. Anddepending on your platform, ieWindows, Mac OS or Linux, youmay get a different format. Forexample, if you're on Mac OS,you will get a DMG image. And ifyou're on Linux, you will get atar file. So I'm on Windows andI want to download the exeinstaller and not the zip one.So I'll select exe, and then hitdownload. Now the IDE is a bitlarger than the JDK in size at649 megabytes. But again,depending on your internetconnection, it may take a fewminutes to download. Once youhave downloaded the software,please go ahead and install itlike any other software that youhave done before.Congratulations on you'regetting the JDK and IntelliJIDEA getting installed. Next up,you will need an account atMongoDB Atlas. Now you may ormay not already know thatMongoDB Atlas is a platform fromMongoDB themselves that allowsyou to spin up MongoDB serverson the cloud.So in order to use MongoDBAtlas, you will have to maybeget tomongodb.com/atlas/database.Again, the link will be indescription and use the Sign Inbutton.Once in the sign in page, youcan either use your Google orGitHub account to log in or youcan sign up with your otheremail addresses for a newaccount. Now, I already have anaccount on MongoDB Atlas. So Iwill just use those credentialsto log into my account offscreen. As you can see, I havesuccessfully logged into myaccount. And For first timeusers, you may have to set up anew organization of sore justjust put any name as theorganization name and you shouldbe good to go. Since we areusing these for just ourdevelopment purposes, it's okayto just use any data that youhave. So once you have set upyour organization, you cancreate new projects. So I willhit the New Project button here.And I have to give my project aname. Now since you are creatingan API that is related to movieI'll just call my movie API. Andhit NextI will just go ahead and createproject since I don't have anyother member to add.Extra now we are inside ourmovie API project. And we areready to create a new database.So you can use the builderDatabase button here to create anew MongoDB database on MongoDBAtlas. So just go ahead andclick this button.And there are three differentcategories there is server listthere is dedicated and there isshared. Now for developmentpurposes, our shared servershould be fine and it'scompletely free. But if you'reworking on an application thatthat has some user and have somereal life usage, you may go withdedicated Serverless issomething else and maybe we cantalk about it in a differentcourse some other day. So selectShare, and hit create.Okay, next up, they will ask youabout which provider you want touse, I always go with AWS. SinceAWS has a server on Mumbai,which is near Bangladesh and hasthe lowest ping for me, but ifyou like you can go with GoogleCloud or Azure. Now selectwhatever region is the nearestto you to make sure that you aregetting the lowest amount ofbeing possible. Next, you canchoose a dear.Again, for free usage, we usethe aim zero sandboxed here itwill give us 512 megabytes ofRAM which is more than enoughfor our usage we will have avery small amount of data to behonest. And then next step thereare additional settings youdon't have to touch them and thecluster name. Now you cancustomize the cluster name ifyouWish but I will just leave it ascluster zero since I like itthat way, then hit CreateclusterOkay, next up, you will have tocreate a new user for thiscluster. You can also use an SSHcertificate, but I will just gowith the old trusty usernamething. So I will name myusernames Solid Snake since I'ma Metal Gear Solid fan, but youcan name it anything you want.Now, when it comes to password,make sure you are alwayschoosing a very strong passwordand not ones that are easy toremember. Use a password managermaybe but always use hard toguess passwords. So I will justuse the auto generated securepassword.And I will also make sure that Iam copying my password to theclipboard, since I will beneeding this later on. But thenhit the Create User button.It shows Solid Snake and thepassword.And finally, you will have toset up some IP access list. Sothe way it works, once you haveset up a new database, you willhave to allow a set number of IPaddresses that can access thatserver. You know opening up adatabase server to the world isnot a good idea. Security wise,so you should always use yourcurrent IP address here.But since this is just a course,and we are using this databasefor development, I will open upthe server for all the IPaddresses out there. And to dothat, you can write 0.0 dot 0.0slash zero and in thedescription, you can just writea viewand hit Add Entry. See thatthat's there. And then click onfinish and close.Okay, they will congratulate youand whatnot Hi quickstart guideYes, go to databasedisclose it.Excellent. Now we have adatabase up and running onMongoDB Atlas. And we can usethis database ganache to eatread and write data from and toeat.And using just like a localdatabase that you may have usedin your computers, you seeMongoDB Atlas is a verybeautiful service. I have usedit for development as well asfor production in the past and Ihave never had any badexperiences with it.So next up, you can use somesort of database client toconnect to this database, maybesomething like MongoDB compass,so you can go ahead and click onConnect.And MongoDB will give youmultiple options that you canchoose from. So first, you canconnect to your database serverusing MongoDB shell, you canconnect to the MongoDB serverusing your application thatyou're working on right now, youcan connect to MongoDB serverusing MongoDB compass which isMongoDB own graphical userinterface for working withdatabases and I will just showyou that. Finally you can alsoconnect using VS code. And let'sbe connect using MongoDB compassfor now.And I do not have MongoDBcompass on my computer. So Iwill be Windows 64 bitand I will just hit downloadcompass.Once you have downloaded andinstalled MongoDB compass onyour computer, you can start thesoftware from your start menu ordesktop. Once you start MongoDBcompass it looks something likethis where they are giving youthe option to connect to a newdatabase by using this kind ofURI. Now where do you get thisURI. If you come back to MongoDBAtlas, you will see that theyare actually giving that URIright here.Just use this copy button tocopy the entire URI and go backto MongoDB compass. Now removethis localhost URI from here andpaste it yours. Now as you cansee it says MongoDB plus SRVBenue username, followed by acolon and then it's looking fora password right. So what we aregoing to do, we will use thepassword that we created earlierand paste it in here. And thenwe'll leave everything as is andweHe can say Save and connect. Youcan name it anything. So I'mnaming it V Avi,you can change its color if youwant to, and say Save andconnect.Okay, so it took a few seconds.And as you can see, we havesuccessfully connected to ourmoving API cluster. Now, as youcan see, there are twodatabases, one of them is calledadmin. And the other one iscalled Local. Now, we do nothave to do anything with these,these come by default with allthe clusters out there. So justleave them be and we will createnew databases very soon. Tocreate a new database, you canalways go and click this plussign.And inside database name,let's put bWhat really, let's call itmovie,API deep.And inside collection them. Nowif you're new to databases, likelike MongoDB, or document baseddatabase, you may or may notknow that collections are liketables in case of relationaldatabase systems. So insomething like MySQL, or Oracledatabase system, you havedatabases, and inside thosedatabases, you have tables. Now,in case of MongoDB, and othernon relational databases, youhave the database name first,and then collections. Forexample, in our cases, we willhave a collection of movieswhere we will save informationabout different movies. So wecan say movies and in createdatabase. So as you can see, wehave a new database sitting heremovie API dv, and there is acollection called movies. Soright now, there is no data atall.Now in order to work with ourAPI, it would be convenient ifwe have a bunch of data in ourcollections. And if you navigateto github.com/ach, si n ch y,which is my username and slashmovies, you will get the entirecode for this API alreadywritten. And inside thatrepository, you will see afolder that says underscoredata. Now inside this folder,there is a JSON file that youcan use as a source of data forthe collection we have justcreated. So I would suggest yougo into this JSON file, thenselect raw,and then hit CTRL S and say thisJSON file somewhere on yourcomputer.So once you have downloaded thefile, you can then import it toyour collection. To do so, comeback to MongoDB compass. Andwhile you have the moviescollection selected, you canclick on this Import Data buttonor this Add Data button. Thenselect Import File. And ourformat is JSON. And we'll selectthe file from our downloads andmovies dot JSON. And you canalso take a stop on errors, thenhit import, wait a few moment.It done. And viola, we have theinformation of n differentmovies on our database. So asyou can see,each of this movie is a documentOkay, as it as it says documentsthen. So inside the collection,each of this movie are a singledocument. And what do we haveinside these documents? Well, wehave an ID we have the IMDB IDfor this title whose inputs, wehave the release date, which isa string, we have the link for atrailer on YouTube. Then we havean array of genres. So thisparticular movie belongs to fivegenres. Then we have a link toour poster.We have linked to end backdropsthat will be later utilized inthe front end application as youcan see, finally, we have anempty array for review IDs. Now,this will come into play lateron in this course, so just bepatient with me for now.Okay, so one thing that I'd liketo mention right here I am usingthe tmdb.org API for thisimages are TMDb is an excellentwebsite. And they provide a freeto use API for developers aslong as you are giving themcredit. So I do, so I will beusing the API for portraying theimages. So now that we havecreated a new database onMongoDB. Plus, we have set up anew collection, we have importedsome data into it, it's time forus to start working on our APIcode.Now the first step to writingour API using Spring Boot, is toinitialize it first. To do that,navigate to start.spring.io.Again, links will be in thedescription. And let's startinitializing our project. First,we'll have to pick a programminglanguage, which is going to Javain this case. But if you'refamiliar with groovy or Kotlin,you may go with them, then wewill have to pick a projectautumn build automation tool.And the initializer supportsboth Gradle and Maven which arenot the most popular buildautomation tool for Java, I amdoing with Maven, simply becauseI have more experience workingwith this then Gradle. Next up,picking up the Spring Bootversion 3.0. Point one is thelatest stable version. And wewill be using that throughoutthe course. But if you wouldlike to try out some morebleeding edge features, you canuse the snapshots once you havebecome more familiar with theframework.After that, we will have to fillup the project metadata.Now the group is usually writtenin reverse domain format. So forexample, my website is Farhandot Dev. And I would like toname my group date dot for her.So if you do not have a domainof yourself, you can name itanything you like, as long asthat package group is notreferring to someone else'sprojectnextra that artifact name, theartifact name is simply the nameof the project. So in this case,I will be putting movies inhere, but feel free to call insomething else if you feel likethat.Next there is a descriptionfield and you can put somethinglikeafter that, we will have to pickup packaging for now java is avery popular packaging formatfor Java and it stands for Javaarchive wire. On the other hand,it stands for web archive. Andyou may think that will wire ismore suited for this projectsince it's going to be a webapplication, right? Maybe yes,but since jar is more widelyused than where I will be goingwith.Next speaking the Java version,obviously, I'm going to pick 17,since we just spent quite sometime setting up Java 17 on ourcomputers. Once you are donewith the left column, let'sfocus on the right column. Inthis one, you will have to pickthe dependencies that you wouldlike to use in your project. Souse this add button, and youwill be presented with a long,very long list of dependencies.And the first one that we aregoing to use in our project isLombok, it's an additionallibrary that saves you fromwriting a lot of boilerplatecode. And you will see what Imean in action very soon. Soplease be patient. Since we aregoing to pick multipledependencies, you will have tokeep pressing either Ctrl onWindows or Linux and command onMac. In fact, it says here,right on the right corner pressControl to multiple apps. Okayfor multiple ads, so I'mpressing down on control and Iwill pick LombokLombok has been picked. Next upspring web.And finally,let's see.No nada SQL under no SQL, wewill need Spring Data MongoDBYeah, that's that's pretty muchit. You can also search forthings here, for example, devtools, and let's add that aswell. Once done, you can exitout of this selector by pressingEscape on your keyboard and havea look at the list ofdependencies and make sure youhave theEverything. Now there are otherdependencies that you may learnabout later on, such as thereactive web,or Graph QL, or restrepositories or something likemaybe spring security, which canbe used for authentication andauthorization. There is more toclient if you're into auth, andthings like that. But since wewill not be getting intoauthentication and authorizationin this course, we will stay outfrom theget go. Once you are happy withthe configuration in thisinitializer to go ahead andclick Generate.It will take a few seconds togenerate the SIP archive, and itwill start downloadingautomatically. Once downloaded,you have to extract these moviesdot zip or whatever you havenamed your artifact dot c fileto somewhere in your computereasily accessible.After you have extracted thedownloaded zip file somewhere onyour computer, you can go aheadand open it in your favorite IDEor code editor. In my case, it'sIntelliJ IDEA and I haveextracted my project on my Ddrive.So I will go ahead and click onopen first.Then come to the folder where Ihave extracted the project and Iwill pick it up.Okay, so IntelliJ IDEA will askwhether you actually just thisproject or not. This is a safetyfeature to save you frommalicious code from running onyour computer. So since we arewriting it ourself, I just picktrust project.And give ideas some time forresolving all the dependencies.And once it's ready, you arefree to go.Let's try to understand theproject structure first. Soignore the dot env and folder,it's managed by Maven. So youdon't have to worry about itright now. There is the srcfolder, which is short forsource. And it will contain yourprogram source code as well asthe test code. So we are notgoing to write any tests. Solet's jump into the main folder.So inside main there is Java andresources, we will have to workinside both of thesedirectories. So let's go insideJava. And as you can see, hereis the name of our project after400 movies, it it may bedifferent in your computerdepends on what you have chosenin the initializer. But itshould be something similar.Then there is a class thatrepresents your applicationsnames. So since I have named myartifact movies, it says moviesapplication, which is prettyappropriate to be honest.In other movies applicationclass contains around 10 linesof code minus spaces in between.So let's try to understand whatit's doing. The first line isactually declaring a packagewhich is pretty selfexplanatory. Next, there are twoinput statements. The first oneis a class called Springapplication. Now this particularclass contains a method calledRun. And to start your Springapplication, you actually haveto call this run method, andthen pass your application classto it. And then you can alsopass some command line argumentswhich we are not going to touchthe second import a statementimports like the Spring Bootapplication annotation. Soannotations in Java are usuallyused to let the compiler knowabout what this class does.So other than this class, thereis more or less nothing insidethis package. So let's try torun our application and see ifwe can we can have anything onour browser. Okay.So you can actually click onthis play button, besides themain method to run the programor this class play button, orthis play button at the top.Let's use this one.Okay, so if your IDE says Lombokrequires enabled annotationprocessing, just go ahead andclick on Enable annotationprocessing and it should befine.Now, if you look at theterminal, you will see thatthere is a nice arc that saysthe spring the springs versionand there's bunch of logs andThere is an exception. Thatexception states that theapplication is failing toconnect to any MongoDB databaseat all. Which is true, since wehave not let the applicationknow about our, our cluster, ourusername, our passwords andthings like that applicationcannot connect to our MongoDBdatabase. Now, it's fine if youwant to leave this error here.Or if you want to get rid ofthis error,you can just first stop thatapplication.Open the POM dot XML file, whichcontains a list of all thedifferent dependencies that weare using.And then look forMongoDB.It should be here somewhereyeah, there you go. Dependencyartifact the Spring Boot starterdata MongoDB. So just highlightthe entire thing. And press ctrland the forward slash which willcomment this out.Then right click on form dot XMLand then go to Mavenand go to reload projectnow try to run the applicationonce again.No your whatsoever.So if you look at the logs, itwill say that Tomcat started onport 8080 Tomcat is actually anweb server that will serve asthe web server the developmentweb server for our application.Now, you'd have to switch to aweb browser to see theapplication in action. So let'sdo that.And then you can navigate tolocalhost88080.There you go. Now it sayswhitelabel error page, that'sfine. At least we know that theapplication is booting up and weare actually hitting the APIitself. And not just some otherpage when what is zero states isthat there is no endpoint atall. So although we have an API,there is no API to hit. I hopethat makes sense. Now let's goback to our code and try towrite our first endpoint.But after where it says theSpring Boot application,we will sayRest Controller.It's another annotation thatletsthe framework note that thisclass is actually a REST APIcontroller and not just anotherclass. Then inside this class,you will have to sayget mapping.And next we'll have to create anew method called public. Andthe return type will be string.And the name of the method canbe anything but let's just callit API index for now. Becausethis is theroute endpoint or or list, let'scall it API route.And we can say return.Have no orI know have our programs areboring, but it's essential, youknow.So this gate mapping andnotation to each, what it does,is that it lets the frameworkknow that this method righthere, API route, is a goodendpoint. So if I put a bracketright here, and then inside,I'll say slash just a forwardslash. Let's stop ourapplication and run it again.Let's see if there are anyerrors.looks fine to me. Let's switchto our web browserand do a refresh. As you cansee, it says hello world. Let mejust increase the zoom level abit. So you cantell alright.Now instead of putting a forwardslash here, if I say for sayslash route,rerun the applicationyou will see that the whitelabelerror page is back. But if younavigate to slash route, youwill seeHello world. I hope this makessense. Although DCS are valideight point, we are not going tomake our API like this, we willactually divide our applicationinto separate layers, there willbe a service layer, there willbe a data access layer, andthere will be an API layer. Solet's go forward and get rid ofthis code and restart to puttogether our movies API.Now, in my opinion, the firstlogical step would be toconfigure the database for ourapplication so that we cansuccessfully connect to theMongoDB cluster that we have setup previously, and talk to it.To do so, open up the src folderright here, go inside main,go inside resources, and openthe file that says applicationdot properties.Now, in this file, you will haveto write the differentapplication properties that isrelated to your project. Forexample, right now, we aretrying to configure our MongoDBdependency.And to do that, you will have towritespring dot data dot Mongo DB dotdatabaseequals to the name of thedatabase. I hope you rememberthat we named our databasesomething like movies API dB. Sowe will write movies API dB,and next springdot data dot Mongo DB dot URI.Now in here, you will have toactually write that URI to yourMongoDB cluster like you didwith Compass.I have my URL already copied tomy clipboard. And I hope thatyou have saved it somewheresafe. Like I said in thebeginning of the course that Iwill just go ahead and paste itright there.And you can get rid of thisslash test thing. And the lastslash, and it should be fine.Okay, soour application should be ableto connect to our database. Nowto test it out. Let's go back toPOM dot XML. Let's remove thecomments.And then let's start ourapplication.Oh, see, we have forgot toreload our project. And the IDEis actually suggested me to loadthe map and changes. So I canjust click this button or youcan go ahead and right click andgo to Melbourne and reloadproject. Let's use this buttonand see if it works fine or not.Of course it does. Let's run theapplication.And now the Euro is called. Andactually it says some thingsabout the MongoDB drivercluster. And this is a positivesign. If it failed to connect tothe database itself, it wouldhave screamed at us and whatnot.But thankfully, it's fine.Now, if you have worked with anyapplications, specifically webapplications in the past, you'vemay already know that puttingsensitive data like this in afile that's going to be in yourGitHub repository is not safe atall.Instead, what you should bedoing is putting all thesethings in a dot env file. So wecan right click on Resource, goto new and create a dot env filefor ourselves.And we can write down a fewproperties here.Mongo database, then Mongo user,then Mongopassword,finally, Mongocluster.Now you can go back to theproperties file, and you canstart moving these values one byone to your env file. So this isgoing to be the Mongo database.Next up the Mongo user namewhich isSolid Snake in my case, goodamong but then Mongo password.Finally, the cluster.And I sometimes like to put theminside quotes, this makes surethat if one of the passwords orusername or clusters containsome special characters in them,it would notdisturb the order of things. SoI like to put this quotationmarks around each fabs. Okay,now we have our env file readyto go, what I would suggest thatyou create another env file,simply called dot env, dotexample,for later reference referencesthen make sure you open up thedot Git ignore file. And as youcan see, the Initialize projectactually comes with a prettygood Git ignore file already.But we'll have to add a fewthings for ourselves, right. Soyou will say, you can actuallycopy this thing from here andpaste it and say,in the white.Yeah. And then you say.in Withthis will make sure that you donot accidentally commit that dotenv file into your repositoryand open up your database to theword.Now, the only problem with thisspring is that spring doesn'tsupport reading dot env filesout of the box.So what we'll need is weactually need to installa new dependencies to ourproject. And I would like totake this opportunity to showyou how you can add newdependencies to the projectlater on. So I'll switch back tomy browser. I'll open up a newtab and I will search forMavendependencies, something likethat. Yeah. And here is Mavenrepository.Then let's search for somethingalong the line spring. DogIan's.Yeah, I am referring to this oneby Paul Suarez. I apologize if Ihave pronounced his name wrong.Let's select this one. And wecan see that it says this springplugins 1.0. And it says Centraland whatnot. Okay, so the nameof the thing is made up PaulTorres spring dot EMV. So as youcan guess this is his group,group name and thesis, the nameof the artifact or the or theproject itself. So we can goback to our code. Let's open upPOM dot XML. And inside thedependencies bar, make sure youare inside dependencies and notoutside somewhere here. Afterthe last dependency, we willcreate a new one.So it is a dependency.And the ID helps us by autocompleting this. And we will saythat the group ID is mi dotPaulis he h, w A are set just tomake sure you can always copyfrom here.No one's going to judge you forthat. And then name of theartifact which is spring dot Eandnow it's not strictly necessaryto define a version as well. Butyou can do so by sayingversion and then put maybe thelatest from two point 5.4by one. Yeah.So that's it, let's reloadMaven.And yet now our project has theability to use the spring dotenv artifact and three dot envfights. Let's go back to ourapplication properties andreplace these hard coded valueswith our dot env references. Todo so open up the resources andwe need theenv so Mongo database Mongo userMongo password, okay?So you will first have to getrid of this value and then startwith $1 signand curly braces. And inside theset of curly braces, you willsee say e NV dotMongo.What do they call it? Database?Yeah, Mongo database, and youcan kind of copy it from herethenreplace Solid Snake by Mongouser.And then they should be Mongopassword.But sore tricked.Yes. And finally a cluster.Cluster Yes. Does this mean?Okay, we can ignore this typo.And if you want Singapore, youcan actually come to thisproblem step and have a look atwhat are what's the ID iscomplaining about. So theannuals property, let's justignore them from now.Which ones per year? Yeah. Okay,let's ignore these for now. Andthe typos. Okay, Mongo is not atypo.Except let's try running ourapplication once again and seeif our env file has taken anyeffect or not.So as it turns out, our MongoDBconnection is fine, which meansthe end file has been readsuccessfully. And we havesuccessfully secured ourconfidential information fromgoing out into the world. Nowyou, you don't have to writeeverything inside an env file,you can actually use this en vdot name of the variablenotation to access anyenvironment variable variable inyour operating system. But Iwill not get into that anymoresince we don't need it. Let's goahead and get along with ourproject.Now in our application, thereare two types of data that weare going to work with. Firstthere are the movies and thenthere are the reviews. So wewill need to first create twoseparate classes forrepresenting these two entitiesin our application. So first,letleft click on your project namenew and Java class let's call itmovie.And inside this movie, we willfirst have to annotate thisclass as a document.This will let the framework notethat this class sheet presentseach document in the moviescollection.And we will also define the nameof the collection here movies.Then inside here we will have abunch of private data. Soprivateobject ID ID this will representthe ID of this movie and privateIMDb ID sorry,stringIMDb ID which will represent theIMDB ID of this movie. Andpreferredstring, title,private stringrelease datefor private stringSchadler link this will be alink to the YouTube page for thetrailerprivate is string poster a linkto the image on the internetprivate list string this will bethe genres because there can bemultiple genres of a singlemovie. And these lists classneed to be importedat Java utilby any private list stringandthis will be the backdrops nowthis backdrop images willactually be used in the frontend application as you will seelater. Let's just quickly jumpto MongoDB compass and make surethat we have indeed written allthe necessary properties forthis class.So as you canLet's see we have written high DIMDb ID title yes released atrailer link genres poster,backdrops, air review ID. So youyou, we will add review IDs, afew moments later.Now, we will have to alsoannotate this ID fieldas an actual ID, this will leadthe framework know thatthis property should be treatedas the unique identifier foreach movie inside the database.Okay, apart from this we willalso need getters setters thatdo is string methods and someconstructors. So instead ofwriting out getters setters to astring for each of these privateproperties, we can just sayat the read data, and this isone of the annotations thatcomes from the Lombok project.And it takes care of all thosedifferent gators setters and twostring methods. Next, we'll alsoadd all args constructor, thisis basically an addition forcreating a constructor thattakes all this private field asargument finally, no argsconstructor, which means anotherconstructor that takes noparameters whatsoever.Okay, next, let's create thereviews. So Java classreveal,it's the same deal.So this will be documentand the collection name will beG fields. Now, we haven'tcreated this collection yet. Butthe application itself has theability to create newcollections. So we don't have toworry about that. We'll add datajust like before.Allargs constructor, Nords.constructor, and thenthere will be two privateproperties for a strong privateobject ID.ID, this will be the ID in thiscase.And then privatereview bodyjust just body string body.Okay, so as you may have alreadyseen in the database design,that each of these movies has anarray of this review, and wehaven't yet added this this areaof reviews to the movie modelyet. So to do that, we will goback to the movie class,go near the end and sayprivateleastreview.Review IDs. Okay, so it matchesthis name review IDs, and thehall that our names are matchingas well. Yes. Now if you writeit like this, this will be anembedded relationship. So allthe reviews that are related,this movie will be added to thislist of reviews. Now this iscompletely fine. In fact, if youare modeling a one to manyrelationship, such as one moviecan have many reviews, this isthe way to go. But since I'mtrying to demonstrate some ofthe features of SpringboardMongoDB data, I will show you anifty annotation right here. SoI will saydocument reference.So this will cause the databaseto store only the IDs of thereview. And the views will be ina separate collection. So thisis calledmanual reference relationship.And there are some other ways tocreate relationships in MongoDB.I would suggest that you searchthem up on Google or MongoDBsufficient documentation andread about them on your leisure.It will give you a lot ofcontext. So now that we have ourmovie and review models ready togo, we can go ahead and startwriting on controllers. So I'dright click onmy packet then a Java class.This will be called Moviecontroller.And this is our first officialdayAPI controller that we arewriting in this API. Previously,we wrote a simple controller inour movies application class,but this time, it's going to bea bit different. So first, wewill need to annotate this classas a Rest Controller.And instead of mapping it tolocalhost 8080, I want to makeit sorry.Mapping request mapping, I wantto make it map to slash APIslash v1 slash movies. So anyrequests to slash API slash v1slash movies endpoint will behandled by this particularcontroller. Next, I will createa new gate method. So I will sayget mapping. And thenpublic.Let's return string for now.All movies,and then we can returnall movies.OK, let's try to run our programand see if it works or not.Let's hit the play button.Okay, it's compiled fine. Let'sgo back to our browser. And herelocalhost 8080 slash route.We will get rid of fruit and sayslash API, slash V one, slashmovies.And it works. Now although it'sokay to return these stringsfrom this endpoint, it's betterto return a responseentity I'll show you why in aminute. So this is a genericpipe. So we'll say string.And then instead of returning orreturning, and instead ofreturning all of this like this,we will say,new response entity of type isString. And this is the value.Then HTTP status dot O.HTTP status dot okay means 200.Let's read on this program.Refresh, and it works just asexpected. Now, you may not seeany difference there. But if yougo back to your terminaland say, curl, I HTTP localhost8080 slash API slash v1 slashmovies, you will see we areindeed returning the 200response code.This comes in handy when workingon a front end application andany REST API out there shouldreturn proper status codes.Since we have the movie modelright here,let's try to use it and pullsome data from the database.For that, we will need a serviceclass as well as a repositoryclass. So let's create therepository first, because that'sthe shorter one. So it's a Javaclass. And we'll selectinterface because repositoriesare of type interface. And thenwe'll say movie in repository.Yeah, now this interface willextendMongo repository. This is thegeneric type. And we will haveto let it know what type of datawe are dealing with. So movie,and we'll also need to let itknow what type of ID we'redealing with, which will beobjectID, there you go. That's all forthis interface, you will need tounnoted this interface as arepository. So that frameworkknows that this is a repository.And then let's create a serviceclass which will be movieservice.And this class will not extendanything, you will just need toannotate as service.Now, inside this class, we willwrite the database accessmethods. So the first one willbe publicGet on movies.Let's just name it all movies.And let's just change ourcontroller method name to get onthis because since it's a getmapping, we're saying get allmodes.And the return type will be listof what will return a list ofmovie from this method.Now, inside the service class,you will need a reference of therepository to do that you willsaymovie repositoryit will be a private field.And its name will be movierepository.Now if you know Java, you mayknow that you will have to firstinitialize this bit of code, youwill either have to initializeit using a constructor, or youcan just use auto wire anaudition what this will cause itwill let the framework know thatwe want the framework toinstantiate this class here forus, okay.Let's go inside the method now.And we will say returnmove the repository dot find allthese find all method isdescribed inside the Mongorepository class. As you cansee, it says right here find alland it will return and least ofthe data type that we havepassed right here certainlystock movie. So that's ourservice class right there. Andthen let's go back to ourcontroller, we will need areference to our service class.So we will say privatemovie service movie surface. Andjust like we did in the serviceclass, we will auto wired theservice class. Since it has theservice and audition right here,we will set auto wire.Excellent. And it's alsonow inside the good old movies.Instead of returning a responseentity of type stringchange it to listso we are returning a responseentity of type list movie.Then inside the method, we willhave to write returnmovie service.of moviesnew response entityof type listmovieand inside movie service drugcalled movies comma HTTP statusdot okay.Yeah, let's take a look at ourrepository. Once again, it's allset up.Services fine, the controller isfine. Let's cross our fingersand see if this works or not.Going to go back to our browserand hit refresh.And the reason behind thisproblem lies in my EMV file. Soas you can see,we have called our databasemovie API dB.But in our configuration, wemistakenly put an S right here.So we'll get rid of the s.Res restart the application andhope for the best.And yeah, it works. As you cansee, there are 10 movies in thislist. Since it starts at zeroand ends at nine. There are 10movies in this list and the codeis perfectly fine. Now let's goback to the code and let me reiterate on what we have done sofar. So in rest API's, usuallythere are multiple layers. Soone of the layers is the APIlayer, which is this controllerand it will only concern itselfhave about the task of getting arequest from the user andreturning a response and nothingelse. And that's what it'sdoing. All it's doing is it'susing a service class anddelegating the task of fetchingall the movies from thedatabase. And give me giving itback to the API layer. So itcalls the all movies methodinsidethe service, gets the list ofthe movie and returns them withHTTP status. Okay, it doesn'tknow what's going on inside theservice class. Now, when we comeback to the service class, thisis where most of our businesslogic will go.For now, there is nothing to beworried about in this classes.But soon, we will work with alittle bit more complex businesslogic in this API. So theservice class does is it usesthe repository class, and talksto the database, get the list ofthe movies and returns to theAPI layer. Finally, therepository layer is kind of thedata access layer for our API IIdoes the job of actually talkingto the database and getting thedata back.I hope that makes sense. Now,since we have a list of all themovies in our databases, let'scomplicate it a bit more bytrying to access a single movie.Now, we will begin by creating anew get mapping.And that isget mapping and this willactually take an parameter.And we will have this a slashthat inside a pair of curlybraces will say ID. So we aretrying to search a movie by itsID.So we can set publicresponse entity. This time, wewill return a single movie.And we'll say get singlemovie. Sorry for the type book.We'll closethe pair of parenthesesand we'll start our method.Now inside the pair ofparentheses, we'll have to sayPATH variable, which lets theframework know that we will bepassing the information we gotin the mapping as a pathvariable. Or we will be usingthe information passed in thePATH variableas a string,or just object.Id ID.So what this does is it lets theframework know that whatever weare getting through this pathvariable, we want to convertthat to an object ID called ID.And then we can sayreturn first we'll have to goback to our service layer andwrite a new method here.Publicmovie single movieand we will say returnmovie repository dotfind by IDand we will get that ID righthere.And it goes here itDavid and the squiggly line itsays that whichever option okay?So the thing here is that thefind by ID method may not findany movie at all, maybe the IDyou have passed doesn't exist.So in those cases, you it willhave to return now, so we'llhave to let Java know that itmay return null by sayingoptionalmovieand we will just import theoptional classwe will also have to fix ourresponse entity movie will sayoptional.Movieoptional has been imported niceand thenWe can say return new responseentityoptionalmovie. And inside there we cansay movie servicedot single movie, we will passthe ID that we have receivedcommaHTTP status dot. Okay.Let's restart the applicationlet's go to our MongoDB compassinside the movie collection andcopy one of the object IDs righthere let's copyfor Roald Dahl's Matilda themusical. Let's copy the objectIdgo back to our browser.And we can say movies, slash andthen the object ID.As you can see, we have foundRoald Dahl's Matilda themusical. Now, the problem isthat I do not want to expose theobject IDs of my collectionentities to the public. Instead,what I want to do is use thisIMDb ID to search for newmovies.So let's see if we can find away to do that.Now although the repositorycomes with built in methods forsearching with ID, it doesn'tcome with methods for searchingwith IMDb ID so what we'll haveto do is we'll have to implementthat method ourselves. And it'sreally easy because there issomething called automaticqueries that lets youfarm where it is dynamicallyfrom.property names so we will sayoptional.Movie because it may return nullonce again, we'll have the inputoptionalmovie and we will call itfind moviebyin dB ID and it takes a stringI am DB ID.Now just by naming this methodfind movie by IMDb IDMongoDB data Spring Data MongoDBwill understand what we aretrying to do. It's that muchintelligent. So now we can goback to our service class.We are no longer getting anobject ID but we are getting astringIMDb IDand instead of find by ID wewill sayfind a movie by IMDb ID, IMDb IDand that's it.Let's go back to controller.We'll change this from ID toIMDb ID by the way you do nothave to name the ID IMDb IDexactly in this method. It'sIt's just that I know what I'mdoing in a later date. So wewill replace object ID by stringIMDb IDand then response entityoptional movie. This is fine.Yeah IMDB.So technically, this should doour job. Let's check it outlet's see seems like there hasbeen a mistake.Let's go upit looks like there is aproblem. Let's go back toour movie repository.And the musicIt is it should be IMDb and notIMBD. So as you can see, theframework is clever enough tosee that I have misspelledthe property name right here.So let's run the program onceagain and see if you're trans ornotfine tuned by cannot findup here, I have to correctterrorism,DIA. And yeah, it shouldn't befinelet's go back to our browser.And as you can see API slash varslash movies. And then I haveused the IMDB ID for this movie.Hit enter, and it works justfine. We can use the IMDB ID tosearch for movies.Now, you can actually formdynamic queries like this usingany property name in your modelclass.As long as they're unique,because if that's not unique,you will get multiplemovies with the same ID or samename. Okay.Now that we have our moviecontroller sorted out, let'sstart working on our reviewcontroller, where we will letthe user send us review. And wewill add those under a moviename.So let's first create a newrepository.Viewposit Oriand it spends Mongo D. B,Mongo repository and the diewill be revealed.And object ID is our type. Yeah,yeah, that's theirnext let's create a new serviceclass. Oh, I almost forget toenter this as repository.So, create a new class calledthe views service.And this will be a serviceclass. So I'll go servicehere I will say publicthenthis method will create a newreviews so it will return a newreview then here she viewbycreativethen this method will take twoparameters. The first one willbe a stringwhich will be the reveal bodyand the sincethe second one will be stringIMDb ID so what we are trying todo here we will first look forthe movie with the given IMDbID. And then we will create anew review and associate thatreview with the found movie. Solet's first create a new review.Reviewfew quotes from new review.Now you maynow you may remember that in thereview class, we have an polarcs constructor and an aurochsconstructor. But since IDs areauto generated, we cannot passan ID to this class. So what wewill do we will also generate acustom constructor that takesonly the body. Now in IntelliJIDEA you can right click insidea class go to generate and thenconstructor and we only need thebody part of this class. Sothat'snow let's go back to our serviceclass and new review and we willpass the review bodyExcellent.Now that we have a new review,we will have to associate theseto one of the moviesnow that we have a new reviewobject, we will have to insertit to the database and forAfter that, we will needa reference to ourreview repository.So review repository viewrepository and needs to be auto.Fine. And we will say,review repositorydot insert, and review.X. And that's the review takencare of now we can have toassociate with this with one ofthe movies, right? To do that,weneed a few things. Now the firstthing that we need is called atemplate to create a templatewith set private Mongo template,Mongo template. Now, you havealready learned aboutrepositories as one of the waysto talk to the database. Theother way is using a template.You see there are times when arepository just doesn't cut it,maybe you have an operations socomplex that it cannot beimplemented within a repository,or even if you can implement itwithin a repository, it will benotsuitable. So what we need, weneed atemplate, you can use thistemplate to form up a newdynamic query and do the jobinside the database withoutusing the repository. So we willalter this.And then down here, we will sayMongo templatedot update, since it's an updateoperation, and we need to saywhich class to you do we want toupdate. So we want to update allof the movies.And then come to the second lineand put a dot here. And then asyou can see, there are multipleoperations that we can perform.So we want the match.Now inside the matching ofversion, we will need a newcriteria. So we'll set criteriadot fire.And inside where we will sayIMDb ID, make sure it's matchingup with the column name or theproperty name inside thedatabasethen.is the IMDB ID that we havegot.Then come to the next line andput a dot once again and thenwe'll say Apply.We'll say new update. This iscalled an update definitiondot pushreview IDsand then dotvaluesheet view.See, that's pretty much it.Okay, so what we are doing is weare using the template toperform an update call on themovie class. Because I hope thatyou'll remember that each moviein our collection contains anempty array of review IDs. Sowhat we need to do,what we need to do is we need toupdate this array and push a newreview ID into this.So we are saying movie dot classthen we have to perform thematching. So which movie are youupdating? We are updating amovie where the IMDB ID of themovie in the database matchesthe IMDB ID that we havereceived from the user. Okay,then we want to apply thisupdate. To do so we call apply.And then we create a new updatedefinition which does the job ofmaking the change inside thedatabase. So we say Update, pushand review IDs. So we want toupdate the review IDs in thisfound movie and the value ofthis movie will be revealed. Sothat review that we have justcreated it will be pushed insidethe review IDs array okay.Now, finally, we will have seetheFirst, to make sure that we aregetting a single movie and weare updating that. Now one thingthat I have done, which Ishouldn't have is we cannot newup a review like this.Rather, what we need to do is wewill just save the review oninsert, because when you callinsert, it actually returns thedata you just pushed inside yourdatabase. Okay?First, finally, we can returnthat view we just created.So let's review the Createreview method. We are taking anew Mongo template, we are usingit to update the movie with thenew review, we just pushed usingthe repository.So likely say sometimes you willhave to code up complex businesslogics by yourself. And as yougrow as a software engineer andan web developer, you will startto understand all these thingsall by yourself.So let's go back to our reviewservice. Yeah. So I mean, ourreviewis is fine. If you're inpositions where you feelservice, yeah. Now let's createa new review controller.And inside this controller, wewill have only one post method.But you may think, why only asingle post method? How are wegoing to get all these reviewsthat are associated with amovie, I'll show you how.Now let's begin by annotating itas a Rest Controller.And then of course, we will haveinput request mappingwhich isslash API slash v1 slashmobile moviesOkay, sincethe review form will be inside amovies Details page, or in thepage where you are viewing asingle movie so we can make therequests to the movies and pointinstead of creating a new if weuse NS N bar. Now when it comesto creating endpoints like this,it really depends on the on thedevelopers preferences, you mayyou may choose to organize yourAPI differently from what I amdoing here. And in a real lifeproject I maybe I will dosomething different but sinceit's just for learning, and weare just getting started, Ithink it's fine.Inside the controller, we'llfirst need our service. So we'llsay privatereveal Service Review serviceand we will auto add thisnicethen we'll create a new postmappingand then a new method of Lakewill again return a responseentity and this will be of typereview. And we will call itcreate review method.Inside this pair of parentheseswe will sayrequest bodythen mapstring, comma stringand we will call it payloadso we'll import map.So, what we are saying to theframework here that whatever weget as the request body we wouldlike to convert it to a map ofthe key string and value stringand we want to name this map aspayload you will see why this isthen we will sayreturn new response entity.And yeah we can say review thisreviewand then it says Service Reviewservice dot create review and wewill pass two tests. First onepayload dot getis the review bodyand the second one will bepayloadDon't getIMDb ID Okay.Finally we saycommaHTT bestatus dot created, it will be201. Since we are creating a newreview, we want to send 201instead of the plane 200 Becausethis means created and thatmeans okay. So now that we havethe post mapping done, we needour REST client a separate riskflying to test our test out ourcode. But before that, I can seethat there is this squiggly lineunderneath the view controller.So I will just go to problemsand see what's wrong. cannotresolve symbol IMDb ID Okay,let's see where I missed a typohere. So it should be inside apair of quotation mark. Andthat's gone. See, this is thebeauty of IntelliJ IDEA. Ithelps you a lot. Now let'srestart our program. And I willuse postman to test out our API.In fact, I just thought insteadof mapping the reviews requestto API slash API slash movies,let's just go with reviews.Because that sounds moreappropriate. Now let's start ourapplicationand let's jump to postman.So inside postman first, I'llcreate a new collection. AndI'll call the movies API.Then let's create a new GETrequest get all moviesso it would be localhost 8080slash API slash VLANs slash x.So it works out just fine. Let'scopy the IMDB ID from one ofthese movies so that we can testout our next requestwhich will beget a single movieand we should be able to carryeverything from the previousrequestwill host slash view and slashmovies slash then the IMDB ID.Let's execute and the works justfine.Finally, let's try to create anew review here to review.And let's say v1 slash reviews.Okay, that's I set that becauseby mistake so it has to be postinside body I would say raw datain JSON format.So I will say reviewbody will be I really enjoyedthe movie withI.Yeah. And then I will say IMDbID,column and timed ID. Now youhave to make sure that the nameor the key in this JSON datareview body and IMDb IDexactly matches the two keysinside the payload which isreview body and IMDb ID. So whatwill happen is this endpointwill receive a JSON data fromthe user and then convert it toa map where the keys are extremeand the values are history. Thenfrom this map, we'll be able toaccess the review body which isa string and the IMDB ID, whichis another string. And thenthrough the service layer, wecan create a new review on thedatabase, update the movie to beassociated with that review, andthen return the review. And ofcourse, there's a repositorythat works as the intermediarylayerbetween the service class andthe database to let's let's golet's come backpostman, and let's see if itactually works onhere. So we have got 201created. So theoretically, weshould have created a new reviewfor the movie boosting boards.And let's go back to get asingle movie it sent,come down to review ideas. Andof course, we have the newreview associated with thismovie.That's how we can get the listof review ideas, they will beembedded with the data of themovie they're referred to.So in terms of the API, that'sit, I know, it's a pretty simpleAPI. But the goal of thiscourse, or the first half ofthis course, was to give yousome idea about how you cancreate a new back end API.Powered by Spring Boot andMongoDB. I hope that you haveunderstood the basic concepts.using MongoDB. And Spring Boottogether, you can go ahead andfurther your study by learningabout how to implementauthorization andauthentication. You can alsolearn about more complexrelationships, and maybe try tobuild a bigger API with Gilletteand ports and other kinds ofrequests. I will be leaving thisstretch right now. And from nowon Gavin long will teach you howyou can create a Reactapplication that can go withthis API. So take care, I willmaybe see you in another coursein the future. Now that you'velearned how to develop the backend, Gavin will teach you how todevelop the front end usingReact. Just a quick note beforewe get started, this will not bea deep dive into React. My onlygoal here is to demonstrate howwe can interface with a remoteAPI from a front end applicationcreated using React throughwhich we are able to retrievedata from a MongoDB databasehosted on a remote server, aswell as posting data to ourMongoDB database. Now, any datathat we retrieve from the serverwill be in JSON format. JSONformatted data may be pleasingto some people. But most usersof application I think wouldmuch prefer something like this.So we're going to transform thedata passed to us in a JSONformat into an aestheticallypleasing front end display.React and associatedtechnologies provide anefficient way to create bothaesthetically pleasing frontends, as well as help usdevelopers to facilitate a greatUX user experience. I'd like togive a shout out to the moviedb.org All the movie posterimages and backdrop images thatwe are going to use in the Reactapplication that we are going tobuild in this course, come fromthe movie db.org Right, let'sget into it. Let's start bylaunching VS code.And let's create a workingfolder on our local machines.I'm going to name my foldermovie client.Let's open our working folderlike this from within VS code.So we are going to use theCreate dash react dash appcommand to generate our Reactprojects infrastructure. You ofcourse, must have Node js,preferably the latest versioninstalled on your local machineas a prerequisite beforecreating a React application.If you don't have no JSinstalled, you can navigate tothis URL to install the latestrelease of node j s. So fromwithin VS code, let's launch theterminal window so that we cancreate our React projectinfrastructure using the Createdash react dash app command.You can launch the terminalwindow from within VS code bypressing Ctrl and the tildecharacter.Great.So the current directoryreflected at the terminal promptshould be the working directorythat we have just created. myworking directory is named movieclient.Then at the terminal prompt,let's type in MPX space createdash react dash app followed bythe name we'd like to call ourReact project. So I'm going toname my react project movie dashgold dash v oneThen let's press the enter key.And the Create dash react dashapp command generates the Reactproject infrastructure, whichincludes all the relevant nodemodules that contain componentsthat we are able to import intoour React application. Thisprocess can take a while tocomplete.And we can see the process on mylocal machine has now completed.So at this stage, we don'treally need the movie clientfolder. Opened within VS code,we only want the foldercontaining the files for ourReact project. So at theterminal, let's use the cdcommand and then enter the nameof the React application that wecreated using create dash reactdash app. So I'm going to typecd space movie dash gold dash vone, and press the Enter key. Soonce we have made the foldercontaining the files for ourReact projects infrastructure,we can launch another instanceof VS code by typing and codespace dot and then pressing theEnter key. This command opensanother instance of VS code,where we are now directly withinthe folder that contains thefiles for our React projectsinfrastructure.We can now close down the firstinstance of VS code, because weonly need the instance that wehave just launched.So we are almost ready to createour React application.We won't be using some of thefiles that the Create dash reactdash app commands generated forus. So let's delete thefollowing files from within theSRC directory. Let's delete thesetup tests dot j s file, thereport vitals dot j s file andthe app dot test dot j s file.We must also delete a settingfrom within the package dot jsonfile, which has to do withlinting. We don't need thislinting setting in our project.Let's save our changes.Lastly, let's open the index.jsfile and remove the code relatedto the report web vitalsfunctionality like this.Let's save our changesand let's move on to installinga few NPM packages that containcomponents that we are going tointegrate into our application.If your project terminal is notavailable within VS code at themoment, you're able to launchthe terminal by pressing Ctrland the tilde character.The next package we are going toinstall is Axios Axios will makeit easy for us to make HTTPrequests from our React clientto the relevant API hosted on adistant remote machine. So thatwe can retrieve relevant moviedata from the MongoDB databasealso hosted on the relevantdistant remote machine throughHTTP GET requests.We will also be able to addmovie reviews to the relevantMongo DB database through theuse of HTTP POST request, whichwill be facilitated on our Reactclient through the use of Axios.We'll implement thisfunctionality later in thisvideo.So to install Axios, we can typethis command at the commandprompt NPM space install spaceAxios.And let's press the enter key.Great, so let's install our nextNPM packagewhich will enable us to useBootstrap for layout and stylingpurposes from within our Reactproject. So let's type thefollowing at our command promptNPM space install spaceBootstrap.Note that in order to integratebootstrap into our project, wemust include this importstatement within the index.jsfile.Let's save our changes.The next NPM package that wemust installallows us to use Bootstraprelated components for layoutand styling purposes. So let'sinstall react dash Bootstrap.For this purpose, we can installreact dash bootstrap by typingNPM space I space react dashBootstrap.And of course, follow this bypressing the Enter key.Great. The next NPM package thatwe are going to install enablesus to easily install fontawesome icons within our Reactapplication. The first fontawesome related package can beinstalled by typing in npm spaceI space at Fort dash awesome,forward slash react dash FontAwesome.So make sure you type at Fortdash awesome here and not atfont stash awesome, which I knowis a little bit confusing. Soit's add 14 Awesome dash, reactdash and then Font Awesome.Great.Let's install the second font orsome related package by typingin npm space I space at FortAwesome forward slash free dashsolid dash SVG dash icons.And let's Of course, press theenter key.Excellent.To play movie trailers fromwithin our application, we'regoing to use the React playercomponent. So let's install theappropriate NPM package. So thatwe can integrate react playerinto our React application. Solet's type npm space I spacereact dash playerand press the Enter key.Great in order to declare thepaths where our components willreside, in order to map theroutes to our components as itwere, we are going to userelevant components from theReact dash router dash DOM NPMpackage. So in order to installthe React dash router, dash DOMNPM package, let's type in thiscommand npm space I space reactdash router dash DOM.And of course, press the enterkey.Great.On our homepage, we want todisplay relevant movies in acarousel.We can easily implement acarousel using material UI. Soin order to do this, we mustinstall three material UI NPMpackages. So we can install therelevant three NPM packages bytyping the following NPM spaceinstall space at Nui forwardslash material space at emotionforward slash react space atemotion forward slash styles.And let's press the enter key.Excellent.In order to use the material UIcarousel component, let'sinstall the material UI carouselNPM package. We can do this bytyping in npm space installspace react dash material, dashUI dash carouseland press the Enter key.Great,and we have now installed allthe NPM packages we need inorder to integrate thefunctionality we want to includewithin our React application.Excellent. Let's get startedwith writing the code for ourReact application. So the firstthing I'd like to do is set upAxios. So to do this, let'screate a folder within the srcfolderandLet's name our folder API.Let's create a file within theAPI folder named Axios configdot j s.We can import Axios into ourproject with this line of code.So we can configure and exportthe Axios object that we willuse to make HTTP requests to therelevant remote API through thiscode.Notes the settings that havebeen included here,we have the base URL setting,which provides the base addressof the API endpoints that ourclient react application will becalling. So you'll see later onwhen we use Axios. To call anendpoint, we won't need torepeat the base URL with eachHTTP request within our code, wewill only need to include theadditional path informationrequired to target a specificendpoint. If this isn't clear,at the moment, it will becomeclear. When we write code tomake a HTTP request to therelevant remote endpoint. Thissetting here is necessary.Because during the developmentphase, the technology that theremote machine is using toexpose the relevant APIendpoints is called ngrok.I won't go into the specifics ofN grok. But we need to includethis setting in order for ourclient HTTP requests to not beblocked by cause I won't go intothe details, of course, but itstands for cross origin resourcesharing. So all we need to knowis that because the relevant webAPI is running in a differentdomain, or origin, that causemay block our access to the endpoint. The server code hasincluded settings in order toovercome the restrictionsimposed by cores. And we areincluding this setting in theHTTP headers of our requestsfrom the client, so that we canovercome the restrictionsimposed by cause IE, so that weare able to access the resourcesmade available through therelevant API endpoints. Great,so we have now set up Axios.Let's open the app.js file andwrite code to call an endpointthat will return an array ofmovie data.Let's write code to import ourAxios object from within ourAxios config.js file.Let's import the use state hookand the use effect hook fromreact.Let's return a D structuredarray from the use state hook.The first item in the destructured array is named moviesand will store an array of moviedata returned from a call to therelevant API endpoint.The second item in the array isa function that can be used tochange the state of the moviesvariable.When the state of the variabletracked by react through the usestate hook is changed thecomponent is re rendered byreact. So in this case, the appcomponent will be re renderedwhen the state of the moviesvariable changes. Let's create afunction that will handle a HTTPget request to an endpoint thatreturns an array of movie data.Once the movie data issuccessfully returned, this codethat changes the state of themovies array is executed.You can see here we are passingthe additional path informationto the get method. This pathinformation is appended to thebase URL setting that we createdwhen setting up theconfiguration for Axios.We are using async await forasynchronous thread managementfunctionalityto the client, I won't go intodetail explaining async awaitand promises. But thisfunctionality can be effectivein ensuring that the UI is notblocked. When potentially longrunning operations, like forexample, a remote API call areprocessed, the UI thread willnot be blocked, and thereforethe use of screen will not, forexample, freeze, the use thescreen will still be responsive,while a potentially long runningIO bound operation isprocessing. Once the relevanttask has completed, the codedirectly below the code thatkicks off the awaited processwill be executed. So it's like apromises made to return to theappropriate line of code. Oncethe task potentially longrunning IO bound task, forexample, has completed.As explained, this async awaitfunctionality is useful in orderto ensure a better UX userexperience. In case somethinggoes wrong during the executionof our HTTP request, let's wrapthe relevant code in a try catchblock. And let's include code inthe catch block to log therelevant exception to thebrowser console window. So youcould be more thorough here inyour code and check the HTTPstatus code. For example, if theHTTP status code returned fromthe server is 200. Thisindicates that the operationperformed on the server wassuccessful.I'm not going to include thisfunctionality in this course, inorder to keep the code fairlybasic for our HTTP requests thatwe are executing from theclient.Let's implement the use effecthook so that the get moviesfunction is executed when theapp component first loads.Let's also write code to log theresults returned from the callto the relevant endpoint to thebrowser console window.Let's use the npm start commandto run our React application.Let's look at the browserconsole window to see if ourresults have been returned fromthe server.Excellent our HTTP get requestmade through the use of Axiosexecuted successfully.So the next step is to startimplementing our routingfunctionality or routingfunctionality.Let's create a React componentnamed layout dots Jas.Let's open the layout.js fileand import the outlet componentfrom the React Router DOM NPMpackage to generate boilerplatecode for our layout component,we can type ra F C E and pressthe Tab key like this.Let's rather use semantic HTMLhere and include main tagsinstead of div tags. Within ourmain tags, let's include areference to the outletcomponent.Let's go back to the app.js fileand write code to import thelayout component that we havejust created.Right, so I'm going to create acomponents folder within the srcfolder, and move the layout.jsfile into the components folder.Let's write the code to importthe layout component into theapp component.Let's write code to import theroutes component and the routecomponent from the React RouterDOM NPM packagein the return part of the appcomponent, ie where JSX code isreturned from our component,let's write code to establishthe route mappings as it werefor our applications Reactcomponents. So let's first addthe routes.elements herewithin the root element, let'sinclude a parent root element.It's a parent root elementbecause child root elements willbe included within this parentroot element. Like, for example,a child route component thatpoints to the home component wewill write the home component ina bit, will be a child of theparent route component thatpoints to the layout component.So the layout componentreferenced through the outletelement in the layout.js filedenotes the components pointedto by the child root componentreferences that will includewithin the parent root elementhere, we'll include the relevantchild root elements as weprogress with the development ofour React application. The nextstep is to open the index.jsfile and write code to importthe browser router component,the routes component and theroute component into the indexcomponent.Let's include code to establishthe relevant route mapping forthe app component.Great, let's create our homecomponent. Let's first create afolder within the componentsfolder named home. Let's ensurethat the first letter in ourhome folder name is lowercase.Let's add a file named home withan uppercase H to our homefolder. Let's type in ra f c efollowed by pressing the tab keyto generate boilerplate code forthe home component.Let's simply type in the textwelcome so that we can test ourroute functionality.We'll create the code for ourhome component in just a bitlet's create the code for theroute element that points to ourhome component within the app.jsfile.Oops, I can see a little bug inour code. This reference tolayoutis not correctly formed. Let'sinclude the layout elementproperly within our code here.Let's type in npm. Start at ourcommand prompt and press Enterto launch the applicationGreat.So let's create a component thatwill be a child component of thehome component. We will namethis component hero. Thiscomponents denotes the herosection of our home page thatwill display items in a carouselthat are representative ofmovies to the users of thisapplication. So let's create afolder within the componentsfolder named hero.Within the hero folder, let'sadd a file named hero dot j s.Let's also add a file to thehero folder named hero dot csswhere we will of course includeCSS code for our hero component.Let's write code to import thehero dot css file into our herocomponent.Let's import the carouselcomponent from the relevant manTerrio UI NPM packagelet's import the paper componentfrom the relevant material UINPM packagelet's write code to destructure.The props passed into thiscomponent, only one destructuredvalue containing an array ofmovie data needs to be includedherelet's implement the carouselfunctionality. Let's include thecarousel element like this.Within the carousel element,let's write code to map eachitem in the movies array to anitem displayed in the carousel.The pay per element encapsulateseach movie item displayed in thecarousel.Let's include div tags, so thatthe movie poster is displayed,as well as the movie title isdisplayed for each carouselitem.As you can see, I've includedCSS class references in therelevant div tags, we'll styleour components in the hero dotcss file in a bit,where we will implement theappropriate CSS properties forthese CSS classes.Oops, let's make sure that weare importing the hero dot cssclass correctly here.Let's open the home.js file andinclude the hero element in thepart of the code that isreturned as JSX code from thehome component.Let's make sure that we areimporting the hero componentinto our home component.Let's write code to ensure thatthe movies array is being passeddown from the app component tothe home component andsubsequently the hero component.And that's great. We aredisplaying the relevant datafrom the JSON data returned fromthe relevant API's endpoint. Butlet's customize the styling ofour carousel through CSS code.We can position our Vyas codeeditors to a pane on the leftside of our screens. And we canposition our browsers to a paneon the right side of our screenslike this. In this way, we canwatch the effects of our CSScode changes in real time. I'mnot going to go into a lot ofdetail regarding the CSS code.The code will be available onGitHub, where you can examine itin more detail if you'd like.Let's first update the CSS codein the app dot css file. ThisCSS code effects all componentsthat are child components of theapp component.And you're able to observe theeffects of the CSS code on thebrowser in real time as the CSScode evolves.So let's importquicksand font from Google withthis line of codelet's set up the box sizing andfont family properties for allelementslet's set the body elementspadding and margin properties tozero.Let's style the App class. Notethat all of our components arechildren of the app component.Let's remove this code from theindex dot css file because it isnot neededlet's style the carouselcomponent that has beenimplemented within our herocomponent. So let's include ourCSS code in the hero dot cssfile.And we are able to watch theeffects on the carouseldisplayed in our browsers inreal time as the relevant CSScode evolves.And we don't actually want thepost image to take up thecarousel display. As it is atthe moment, we want anappropriate backdrop image alarger image to fill thebackground for each item in thecarousel.I want to include a gradientthat fades from dark to lightfrom the bottom of each carouselitem to where the title isdisplayed. In order todynamically reference thebackground image URL for eachcarousel card,I'm going to use a CSS customvariable.So we can do this by includingan inline style within the divelement that references themovie dash card CSS class. Andwithin that inline style, assigna variable to the property thatwe wish to reference within therelevant CSS file. So here, weare naming our custom CSSvariable image.We are setting the CSS URL valueto the CSS background dash imageCSS property from the backdropsproperty of each movie in themovies array returned from theserver. Note that the backdropsproperty returned from theserver is an array containingpause to movie backdrop images.In this code, I'm choosing toreference the first backdropimage path in the backdropsarray returned from the server.Each backdrop points to an imagethat we want displayed as abackground image appropriatelyfor each movie item in thecarousel. We can now referenceeach background image fromwithin our CSS class and stylethe background appropriately.So we are assigning thebackground dash image CSSproperty or gradient that fadesfrom light to dark?This is just a stylistic choice.For our front end display, youcan see here in our CSS code howwe are using the dash dash imagecustom CSS variable to link theURL property value referenced inthe JSX code in the herocomponent to the background dashimage CSS property in the herodot css file. You can see thatthe poster image is lookingdistorted so let's style theposter and the titleappropriately.Great and we have used absolutepositioning and the CSS Flexboxto style our poster and handlewhere it appears in the layoutlet's style the titleappropriately.Great, and our carousel islooking pretty good. Let'screate the components to houseour navigation display. Let'screate the header component. Solet's create a folder within thecomponents folder named header.Let's create a file within theheader folder named header.js.Let's import the appropriatefont awesome componentslet's import the appropriatebootstrap components.And let's use React bootstrapcomponents to create aresponsive layout for ournavigation menu which will bedisplayed at the top of thescreen. This is one of the hugeadvantages of using Bootstrap itcan save us a lot of time increating responsive layouts.We are using the FA video flashfont awesome icon for our logothat will be displayed in thetop left corner of our screenwithin the navigation bar thatwe are creating within theheader component.The login and registrationbuttons are being included here.Superficially, they are purelycosmetic indicating that wecould extend the functionalityof this application to includelogin and registrationfunctionality at a later stage.For example, if we wanted toenable users to create their ownlist of favorite movies or awatch list, the watch list linkhere is also there purely forcosmetic reasons. We won'timplement a watch list componentin this course.So above the routesfunctionality within the app.jsfile, let's reference the headercomponentlet's go back to the header.jsfile and make sure that ourimports are correct.Let's run the codeExcellent, our navigation bar,and our logo looks pretty goodthe next step is we want to beable for a user to click a playbutton icon on each carouselitem. And for an appropriatemovie trailer to play willenlist the help of the Reactplayer component for thispurpose. Let's first create afolder named trailer within thecomponents folder.Let's create a file namedtrailer dot j s within thetrailer folder. Let's alsocreate a file named trailer dotcss within the trailer folder.Let's create the relevant inputcode in the trailer.js file.Let's import the use params hookinto our code from the ReactRouter DOM NPM package, aYouTube video ID will be passedinto this component as aparameter. So we are going touse the use params hook toextract the relevant parametervalue from the relevant URL. Therelevant parameter will containa YouTube video ID which willallow us to play a YouTubevideo, which is a trailer of therelevant movie to the user.Let's import the React playercomponent.Let's import the trailer dot cssfile.Let's create the boilerplatecode for our trailer componentby typing in our AFC E andpressing the tab key. Let'screate a div container in whichour React player components willresidelet's assign the Pastonparameter value to a const namedkeythen we can include the Reactplayer component appropriatelylike thiswe want the player to includecontrols. So here we can set thecontrols property to true we canset the playing property to trueso that the relevant video playsas soon as the trailer componentloadsand lastly, and mostimportantly, we can set the URLproperty to the relevant videoon YouTube so we can append therelevant YouTube video ID storedin the key const to the baseYouTube address to point reactplayer to the YouTube video thatwill be played within reactplayer greatlet's go to the app.js file andinclude the relevant routeinformation for the trailercomponentnotice how we are able to letReact Router DOM know as it wereabout the YouTube video IDparameter then our code withinthe trailer component mustaccesslet's include a play button iconprovided by font awesome withinour carousel.Okay so the play button icon ispresent, but it needs to beappropriately styleOkay, as it is tiny at themoment, let's go to the hero dotcss file and style the playbutton icon appropriately.Great, let's include a mediaquery so that our carouseladapts to smaller screensGreat, let's go to the trailerdot css file and create CSS codeso that the React player takesup 90% of the viewport height.Lastly, we need to create thelink so when the play buttonicon is clicked, that thetrailer component is invoked,and the appropriate parameterspassed through to the trailercomponent.So the trailer link propertyretrieved from the servercontains the entire URL to theYouTube video, we only want topass the ID of the YouTube videoto the trailer component fromthe hero component. We canextract the YouTube video ID byusing the JavaScript substringmethod to extract the last 11characters from the trailer linkproperty like thislet's run the code.Excellent. The last component weneed to create is the reviewscomponent. The reviews componentwill enable users to viewreviews from other users as wellas add reviews for movies intothe system, ie, which entails aHTTP POST request being made.From our React component to therelevant remote API endpointscarrying the review data enteredby the user and the server sideJava code will then save thereview data appropriately to theMongoDB database. Firstly, let'screate a component named reviewform. This component willcontain a form component thatcontains a text area controlwhere the user can enter textthat denotes a movie review. asubmit button will also beincluded so that the user canclick this button in order tosubmit the user's movie review.So let's create a folder namedreview form.Let's create a file named reviewform dot j s within the reviewform folder.Let's include the code for thefunctionality we have justdiscussed.Let's create the reviewscomponent that will be a parentcomponent of the review formchild component. Let's create afolder named reviews.Let's include a file within thereviews folder named reviews dotj slet's include the appropriateimport code at the top of thereviews.js file.Let's generate the appropriateboilerplate code for the reviewsReact component by typing in RFCE and then pressing the tab key.Let's use the use ref hook toreference the text area controlwithin the review form. Let'suse the use params hook so thatwe can extract the movie IDparameter value from therelevant URL.This movie ID is actually theIMDB ID of the movie that wehave retrieved through the APIcall that is made to retrievethe array of movie data from theserver. The IMDb ID value, ofcourse, is used to uniquelyidentify a specific movie.So when our component firstloads,we want to call a method that ispassed in as a prop to ourcomponent in order to retrievethe appropriate data for therelevant movie that the userwishes to review. So we can usethe use effect hook like thisfor this purpose.Let's use React bootstrapcomponents for example, the rowand col components to create anappropriate layout for thereviews component, we want todisplay the poster for therelevant movie in the left partof the screen and the reviews inthe right part of the screen wecan use the row and colcomponents appropriately toachieve this.Let's include the review formelement here like this.Let's create a method named addreview and create the relevantHTTP POST request functionalityfor adding a review to theMongoDB database which resideson a remote server.And let's write code to updatethe state of the reviews arrayon the client side.optimistically meaning that weare not using data returned fromthe server ie data that is savedto the database for updating thestate of the reviews array. Weare updating the arraydirectly from the data enteredon the client.We also want to include codethat clears the relevant textarea control. Once the user hassuccessfully submitted a review,we are updating the state of thereviews array on the clientthrough the use of the setreviews method that will bepassed as a prop from the appcomponent.Let's go to the app.js file andcreate a method that uses Axiosto make a get request for datapertaining to a single movieso an IMDB ID value will bepassed into this method to themovie ID parameter and HTTP getrequest. Using the movie IDvalue appropriately in the URLwill be made to retrieve datafor a single movie from theremote server.So let's set the state for themovie variable.And to make our code clearer,let's extract the reviews arrayfrom the movie data and trackthe state of the reviews array.Let's make sure that theappropriate props are beingpassed down to the reviewscomponent.We are now able to createreviews for the movies retrievedfrom the remote serverultimately from a MongoDBdatabase that stores our moviedata. So we are adding reviewsto our MongoDB database throughan appropriate HTTP POST requestto inappropriate endpointExcellent.One thing we must do whenever weimplement a list of uniquelyidentifiable AIitems in our JSX code like thisis appropriately includes thekey property for each list item.to uniquely identify each itemin the carousel, we can set thekey property for each movie itemdisplayed within the carousel tothe appropriate IMDb ID valuefor each movie. This value hasbeen passed down to us with themovie data array that weretrieved from the remote serverusing the appropriate HTTP getrequest. I hope you've enjoyedbuilding this front end usingReact. And I hope you feel thatyou have benefited from thiscourse.If you've got to the end of thiscourse you've done exceptionallywell. Thank you and take care\n"