Build a REST API with Node JS and Express | CRUD API Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Good stuff. But been using NestJS and typeorm-model-generator and I don't wanna go back.

👍︎︎ 11 👤︎︎ u/crazysteave 📅︎︎ Jul 12 2020 🗫︎ replies

why is he still using the stand-alone body-parser package when it's builtin in express right?

👍︎︎ 3 👤︎︎ u/theUnknown777 📅︎︎ Jul 13 2020 🗫︎ replies

Hey. Exactly what i need for a project. u/Hollydayinternet

👍︎︎ 1 👤︎︎ u/WilliamRails 📅︎︎ Jul 13 2020 🗫︎ replies

What do you think about instead of having specific folders for types of files (routes, controllers, services...) having directories per business logic? Folder users with user.routes.js user.controller.js user.service.js etc.

👍︎︎ 1 👤︎︎ u/zittoone 📅︎︎ Jul 13 2020 🗫︎ replies
Captions
hello everyone and welcome to javascript mastery in this video i'll teach you everything you need to know about creating a simple api using node and express there's a high chance you came across the term rest api if you thought about getting data from a source on the internet such as facebook or github but what is a rest api and more importantly how can you build one there are some more often used terms and technologies when building apis such as express node postman and crud api i don't like talking too much about ideas architectures and methodologies i'm here to show you how all of that works in practice so that you can build your own apis let's dive right in [Music] let's say you're trying to find videos on youtube you open up youtube type something into a search bar and hit enter and then you see a list of videos about that search term a rest api works in a similar way you search for something and you get a list of results back from the service you're requesting from an api is an application programming interface it is a set of rules that allow programs to talk to each other the developer creates the api on the server and allows the client to talk to it rest determines how the api looks like it stands for representational state transfer it is a set of rules that developers follow when they create their apis nowadays almost all apis are rest apis so don't worry about that too much and finally what is crud crud is an acronym for create read update and delete it is another set of rules we are going to follow while building our api almost every website is a crowd in a sense for example whenever we have a database of users we need to be able to create user accounts get or read the profile details update the profile details and finally delete an account this was just a short theory introduction but as i said at the beginning i'm here to show you how all of that works in practice so that you can build your own apis now let's start coding first we need to download node.js node.js is a javascript runtime and all that it does is it allows javascript to be run in places other than the chrome or other browsers we can run it in the console or in our terminal we're gonna use that to create server-side javascript applications if you worked with front-end so far this is going to be something that's completely new to you but don't worry this video is for everyone who is just starting with node and express and has never built their own api before so now how do we download it well we just click this button i would recommend downloading the new current version because there we can use imports and exports so just do that even if you do have it installed already just install it one more time and then you can check for your version once we go to visual studio code secondly we'll be using express express is as you can see fast unopinionated minimalist web framework for node just keep in mind these last words so it is a framework for nodejs express is going to help us create different routes for our api and finally we'll be using postman postman is going to help us make different requests to our apis so that we can test all of our endpoints with that out of the way let's move to visual studio code right now i'm inside of visual studio code in an empty folder it's called node express api you can create your own empty folder and just drag and drop it into visual studio code and we should be good to go i prefer visual studio code because it has a nice built-in terminal we're going to use so if you go under view at the top and then terminal the terminal is going to show up and then we can run some commands right there so what do we need to do to initialize our backhand javascript application you can run mpm init and then put a flag off y just like this and then click enter this is going to create an empty package.json with barely something in it we have the name we have the version description and the main file which we are going to create right away in here you can see that we do have some scripts later we are going to add our own starting script with that out of the way we can create an index.js file which is going to be the starting point of our server inside of here we'll be using express so let's install it right away npm install dash there save and just express like so it's gonna install and then we'll be able to do import express from express before we had to do something like this const express is equal to require and then in here we put the express these two are equivalent right now you should be running the latest node version so you can type node and then dash v in the terminal and you should be getting 14.5 if you have that installed then we can go back to the package.json and just add one simple thing that's going to allow us to use the imports that something is going to be type make sure to use double quotes equal to module as soon as you add this we'll be able to use normal or let's say newer import statements like this great the second thing we're gonna need is going to be import body parser from body dash parser just like this this allows us to take in incoming post request bodies again that sentence maybe doesn't make a lot of sense right now but you're going to see it in action really really soon then we need to initialize our express application by doing const app is equal to express and we call that express as a function now our whole application lies in this little variable below that we can specify the port of our application we can use capital letters because we are never going to change this port and since front ends are often on localhost 3000 let's use 5000 for for backhand of course this can be any number then we can initialize the body parser middleware by doing something like app.use and then in there we do body parser dot json we call it as a function this is just gonna say that we're gonna be using json data in our whole application json stands for javascript object notation and it is a common format for sending and requesting data to a rest api don't worry about the syntax because a json object looks like a javascript object so you're going to be completely at home with this there are some small differences though in json each property and value must be wrapped with double quotation marks instead of single quotation marks but that's just it and finally we can make our application listen for incoming requests by saying app.listen in here we specify the port we want to listen on and then we create a callback function which is going to be executed once we run the server okay in this case we're just going to have a simple console log console.log and we're gonna say server running on port and then that's gonna be http make sure to do http and not https uh forward slash forward slash localhost and then in there we can use the template strings to put the port in inside like this but make sure to change this from regular strings to template strings using the backticks just like this okay now our server is ready and we can actually run it so right now if i do node and then run our index.js like so it's gonna say server running on port localhost 5000 and i just noticed we are missing a small detail right there it should be localhost with a column just after it so now if we save notice how nothing is happening in the console that's because once we run it we need to rerun it one more time every time to get the changes as you can see right there now we can click it that's the problem we don't want to save the file and then every time close the server and then run it again for changes to occur that's why we have a package called nodemon we can install nodemon by typing npm install save dash dev and then we can say nodemon why did we use the dev well because when we push or publish our application no one is gonna be running our server so we are installing this dependency only for our own development purposes it's not gonna be used later that's why we have it as a dev dependency now if you go back to our package.json you should be able to see dependencies express and dev dependency nodemon great so how do we run our application with nodemon well let's set up a script in here we're going to remove this test script create our own start script so we can say start and then just after it we need to use double quotation marks and in here we'll just do nodemon index.js this is going to make sure that we start our application using nodemon and as i said node1 is going to keep making changes whenever we save a file so if we now save this go back to our index.js let's try running our mpm start command okay great server running on port lock host 5000 and if i was for example to change this r to capital r and then save the file you can see nodemon restarting due to changes and then starting the server again and we do get our change right here that's amazing we just set up a basic express server so what can we do with it now that our application is running we can visit our api by going to http localhost 5000. you can control or command click this or copy it and paste it into a url bar if we go there right now we do get some kind of an error cannot get forward slash why is that happening well if we go back node and express primarily are all about routing so we need to create some routes which we can then visit with our browser or we can send requests to so in this case we're going to create our first route that's going to be app.get as you can see we can create different routes of different types right there if we do dot and then something in this case we are expecting a get request and then the first parameter is the path we are expecting that request too in this case this is going to be a get request to the forward slash or the home page then the second parameter is the callback function we can do it like so callback function it accepts two parameters request and response in here let's do a simple cons log just so we can see if it is running so let's do um let's just do test just like so it's really noticeable all uppercase and then also let's do rest.send so we'll do res.send and we will say hello from homepage just like that whenever we have just a root page this one here that usually means that it is a home page so if you now save this and we go back to our home page feel free to refresh and we do get hello from home page that's not the only thing that happened the console log is not going to be in the chrome's console rather it's going to be right here as you can see we do get console log of test with an exclamation mark which means that the code from this callback function was ran once we visited the forward slash when i say visited i mean we made a get request to the forward slash remember browsers can only may get requests for example if you visit google.com you are making a get request to the google.com domain the same thing happened here we visited localhost 5000 and that made the get request to the slash or just to the home root route of course our api is going to have many more routes so right now we can delete this we can just have the res dot send and since this is only one thing we can immediately leave it in a short error function syntax amazing so what is our api going to do well we will be handling some users handling users in a database is a great example because that is something you're going to be using in each and every application this is how it's going to look like we're going to make five different routes the first one is going to be the get route to the slash users this is going to find all the users in our mock database the second thing is a post request to slash users it is going to create a user then if we want to find user details for a specific user by id we're going to make a get request to slash users and then slash the dynamic parameter of id we can also delete a user by id or update user details by id so now let's start with creating the roots so now let's start creating routes for users we mentioned that this index.js file is only going to be for the setup of the server we don't want to add 10 or 20 different complex routes here so how are we going to do the routing well we're going to create a folder called routes and then inside of there we can create the name of the file and that's going to be something which all of our routes are starting with in our case that's going to be users.js inside of here we'll also use express from express so import express from express and then we need to use something called a router coming from express.router watch out there is a capital r here on express that router with this we initialized our router in the similar fashion to this thing here app that gets something in here we'll use the that get something or router that delete or router that post you'll see in a moment why are we doing it this way the path of the first route is going to be to slash users once we visit that we do have a callback function each callback function in express has the request and the response objects in here for now let's just say rest.send and let's put hello from here just so we can know if we've gotten to the correct route in the browser okay so now this is just a new file in the new folder we are never actually using it so we need to export default the router so that we can make use of it in the index.js file so export default router once we go to the index.js file we can now import that so let's do that like import users routes from dot slash routes slash users.js make sure to include this js extension and we named it user routes because as you can see uh the file is called users when using default imports we can name this anything we'd like but users routes is really descriptive and then how do we make use of that well just below this body parser will say app.u and in here we set the starting pad for all the routes in the users file what do you think that's going to be if we go back to this picture you can see something that all routes have they are all starting with users so in here we are going to specify the path of slash users and what's going to happen when people visit slash users in here we're going to run these routes so users routes the routes we just imported from the users file in the routes folder so how does this work if we now go back to the slash users and let's try to actually reach this we said we want to get the get request to slash users right here slash users if you now go to the browser you should be able to see that of course we have the home page we had that before but now in the url bar if you type slash users you see cannot get slash users which means that our request is not correct we are not getting the hello why is that so that's because in the index.js file we specify that all user routes are already gonna be starting with users so in here we're getting kinda redundant this is actually pointing to slash users slash users which doesn't make any sense so in here we just need to have the slash all routes in here are starting with slash users and then whatever we add on to them in this case we don't want to add anything as you can see in the image here great so now if we do that if we save it and go back to the browser we should be able to refresh and see hello as you can see there it is that means that our route is correctly set up and now we can actually move to the logic of creating different users let's create a mod representation of our user schema so in here we can create a new file and we can say user.json just for example in here we can create a representation of how our user document should look like it's going to be a pair of curly braces and then inside remember this is jason so we need to use double quotes uh we're going to have a user that's going to have a name let's do john for the first one and then let's say last name of course we can then do this to be the first name last name john doe you're gonna see john doe popping off in in tutorials that's just a generic name and then let's also do age for example let's do 25. as you can see it's really similar to normal javascript objects but there is only one thing that you need to have double quotes you also cannot have so-called trailing commas you need to do it like this okay so now we know how our person object is going to look like let's try to create our mock database containing two different users inside of the user's routes i'm going to create just a normal array so just array and we're gonna call it users const users is gonna be equal to an array and then inside of there i'm gonna copy our joan person and just paste them inside of here now our users array has one object with the first name of john last name of do and the age of 25. great since this is not json we can also remove the string signs on the keys of objects great so now if we do that and save the file let's try to console.log our john right here so console.log users and let's console.log all the users although we currently have one okay when we go to slash users we get some json data as you can see we can collapse it or uncollapse it maybe this looks just like a plain text for you just a plain empty black string if that's the case go to your chrome store with the extensions or any other browser store and download something called json formatter as you can see here with json formatter i can see the text raw or parsed so if i click raw this is how our json file looks like but of course it's much nicer having it parsed so feel free to download that and that's it as you can see we already have our get route for all the users let's add one more just so we can have two for example let's do first name that's gonna be um jane and then we can do the last name also though and the age is gonna be for example 24 just like that if we save it go back to our browser and also as you can see here we also got our users in the console log once we visited that route if we go back save it we now do get two users that's great and in here we have our users now we need to add the functionality of adding users to our database we're going to go below this router.get and we're going to create a new route this time it's going to be router dot post it can no longer be a get route or get request because we need to send some data from the front end to the server that data being the values in the forms user inputted for example whenever you see a sign up or login form there you have username first name age these are data values that we need to send from the client to the server for the user to be created so that's why we are using a router.post method in here the path is going to be again just slash users we're just saying slash and then we have the request and response callback function in here now we'll have to deal with some actual data we'll be sending in for testing the post route we can no longer use chrome or any browser for that matter why is that so because whenever you type something into the url bar it's making only a get request so browsers can only make get requests that's why we need a software which can help us test our api and that's where postman comes in handy you can just go to the postman.com and then to the download page in here you can just click download install it your device and then open it once you do you should be having something like this so how can we make different requests with that well we go to this plus icon on the top and in here you can see that we have something similar to the browser's url bar in here we can say localhost and then 5000 and right now let's try making a get request to localhost 5000 to see if we get anything and we do get we get hello from homepage let's now do localhost 5000 slash users we know that that's going to give us some json data as you can see here in a nicely formatted way even with some line numbers and now what we can do here but what we cannot do in chrome is we can change the type of the request so in here we can make a post request to the same or different route so how do we send some data in well you need to move here from params to the body tab then you need to go to raw and then change the text to json so we'll be sending data in the json format so what data do we want to send to the database well we want to create a user of course so we're going to create something similar we created in the mock user.json file in here of course the user needs to have a first name keep in mind that this needs to be wrapped in double quotes the name is going to be let's say johnny this time then we have the last name that can be a sun so let's do do one more time and then let's do the age of 10 that's it so if we do this we are sending some data to our post route how can we see that if we go back to our visual studio code in here let's do a simple console.log and we'll say route reached or let's add post route reached so that we can know if this callback function was fired along with the console log let's also add the rest that send that's something that's going to be sent back to the client side and we can say the same thing post route reached just for now so if you save the file and then go back to postman you should be able to click the send button and as you can see the response is going to pop up right there it says post route reached and also in here in the terminal you can see post route reached great so how can we actually add the user to our database well in this case we are using a mock database which is just a single array with some objects it's not going to be stored once we add the user every time we call a new server or we refresh a server it's going to be change and go back to just two users so if you want me to create a new video where we are going to interact with real database mongodb in this case just let me know and that's going to be the topic of the next video but for now let's keep working with the mock database of course the point of this video is to learn express and node so just think about it how would you add a value to the array just a push method right so let's do exactly that in here we're going to call the users and then do the push method what do we want to push that's the great question we want to push what we send from here this is the user so how do we get to that data when we are working with post requests we have something known as a request dot body so let's console log the full request that body so we can see what's hidden inside of it if we save the file one more time and restart this request now you can see we do get the full object right here it's being stored in the request.body now we can put that into a constant so let's do const user is equal to rec.body and now that we have the user the easy thing to do is to just push that user to our current users array the other thing that we can do is we can provide a useful message to the client side once they make the request so let's remove these kinds of logs and this one as well and let's just send something useful we'll send a template string which is going to say user with the username and then in here we can use template strings user that first name sorry it's not going to be username it's going to be user with the name something added to the database that's it so now if we save this if we go back one more time and let's try adding um johnny again save it user with the name johnny added to the database that way we can be sure we added johnny great so now why is this special what did we do we just pushed the user but can we somehow see the action of our doing well if we go back to our browser right here and now refresh the page or rather make a get request to the localhost 5000 slash users you should be able to see that now we do have 3 users we can also check that out if we make the get request to the same route using postman right here send and as you can see we do get three values that's amazing you just created the get route to get all the users and we also create the post route so that we can add users to our database amazing the thing that we need to do next is we need to be able to get the details of only one single user for example if we are logged in as john we need to get back the details about john's profile so for that we need some kind of an id some kind of difference from which we can differentiate all the users right now of course the name john only shows up so we could search by that but of course there are going to be many other people named john in our big application so for that it's good to use some kind of unique id there is a package on mpm called uuid and as you can see it has 31 million weekly downloads which means that it is a really popular package so what does it do we can install it of course by just typing npm install uuid let's do that right away to close this terminal you need to press ctrl c to close it and then we can run this command in here you can see that we just imported and we just call it as a function once we do call it it gives us this huge string with unique numbers this string is never going to be the same as any other string created it uses different time stamp it uses different type stamp it uses different time stamps name spaces random cryptography and a lot of different things to make sure that this is never going to occur again that way we can guarantee that no two users in the database are going to have the same id great now that we install it we can copy this go back to our application and now go back to the top import version 4 as uuid version 4 and as you can see we can just call it like this so let's copy that and now the question is where do we actually want to add that id well of course when creating the user so we need to use that right here and this thing actually is the user id and now the question is how we can add this to the current user we are getting from the rec.body well we can create a new object let's call it user with id and then in there we need to spread all the properties from our current user and also add the property of id equal to user id this may be a bit complex depending on how well do you know the spread operator and creation of objects but as you can see we just created a new object which now represents the user and then we spread all the properties of the user meaning the name the age and then we just added one more value on top of it and now instead of returning user or pushing user we can now push user with id of course we can even simplify that as you can see user id is a variable only mentioned once so we can just take the value and paste it here immediately getting rid of this and as you can see user with id is also mentioned only once so we can just take the value and immediately have it right here this way we have almost the same thing as before having the user but this time we are also adding the id to it great so can we somehow see this in action or not well of course we can if we save this and now run npm start again considering we've closed in our server as you can see server running we go back to our localhost 5000 and now refresh the page these two users do not have an id and that's because we created them we just created a mock database here we don't want to have any users here let's let's just leave it empty for for starting right the database is empty at the start and then if we go back and refresh now we have no users good but now how can we push new users we already tested that out so if we go here to the post request and we try adding one user let's always keep adding the john so i'll delete this and i'll just push the oh we already have it here so we'll just push johnny for example in here click send okay user with the name johnny added to the database and now if we go back to the browser refresh you see we do have johnny doe with the id of some random gibberish numbers great let's try to add one more for example john doe save it and as you can see if you refresh now we have john doe as well but this is completely different c c r b here we have c l and of course everything else is different you can see for the ending letters great now we know that each user is different in a way we have something that we can differentiate it by so now we can create a new route router.get this one is also gonna be get but this time the path is gonna be to slash users and then slash id in a moment i'm gonna show you why i put this column sign right there but for now let's just test it out let's create wreck res as we always do you can see the pattern now and let's just return rest.send the get id route just like that now you can either test it with browser or the postman because you know that when we have a get request you can make the get request from the browser as well so if we now go to slash users and then slash id as we specified right we should be able to get the the get id route and we do that's great so what if we do something like slash users slash test oh that also works what if we do something like slash users and then put the id of some random numbers and then do that that also works that's because when you put the colon sign here you're expecting anything after the user's path so we can put anything and this route is gonna hit so can we somehow get this id which the user sends for example if he does the route to the slash users and then slash 2 2 being the id can we somehow retrieve the value of 2 in this callback function we can it's stored in the request that params params being the parameters to our function in this case the only param that we do have is the id so we're going to have an object and the id is going to be 2. of course we don't only want to see comments let me show you that in action in here i'm going to do console log request that params if we save that or you know what we can also show that if we do in here wreck that ramps now it's going to show in the browser as well so let's go back do one more request to let's say this url and now as you can see we do get an object that has the value of our id why do we need that well because we want to access the data of the user's id specified right in here great now we know that we get the id to direct that params so let's do const id is equal to reg.params that id and you can also use destruction here so we just take the id value from the regedit params great but we don't only want to send the id that doesn't make any sense we want to send the user data for a specific id for that to work we need to find a user in our user's database that has the same id so we can do users that find in here we get each user and what are we searching for well we are searching for if the user that id is equal to the id right there if that's the case then we're gonna get the user let's try putting that into a new variable const found user and let's try doing a let's just let's just try to return it so instead of returning reg.rams we'll return the found user let's see if that's gonna work now of course if we go back just to slash users we don't have any users right now because we need to add them so let's go to postman make another post request with the john doe great we just populated the array if we refresh we now see the john doe with the id that's nothing special let's add one more person there johnny for example okay if you refresh one more time we do get another object but what's special now is that each user can look at his own profile or right now everyone can look at everyone's profile because we don't have any authentication but if we take this id here and then go to slash users slash and put that id in now we get the data only for that specific profile that's great the advancement to this would be for the user to be able to edit some of things only under the id of this user or also that we can delete the user by certain id so let's implement these routes now we know how we need to use the route parameters to make this work so let's create another route the route we are going to add next is going to be router.delete so this route is going to be for deleting users which users do we want to delete well only the user specified in the query parameters then again we do a callback function where we have the request and the response and afterwards of course we need to get the id one more time from the request that params and now we want to remove that element from the array for that we can use the filter function const let's say let's say users is equal to and now we need to filter out the user's array so users that filter in here we get an each user for each iteration and then a filter function works so that if whatever is here returned is equal to true it keeps that user in the array but if it is false then it removes it from the array so we want to keep all the users except the one whose id is equal to the id we have here with that said how are we going to make the logic of this work well let's say that we have john john has an id of 1 to 3 and we also have johnny or let's say j now uh we we mentioned johnny too many times uh jane has the id of three two one and the id we specified id to delete is equal to one two three for example great so now we go into this function user the first time the user is john and the user that id is equal to 1 to 3. so we want to do false for that so we do not equal to id and that's it so let's explain one more time how does this work for the first iteration the user is going to be john and his id is going to be one two three the id we want to delete is also going to be one two three we said that the filter function works so that it removes the elements for those that the function returned false since we have an unequality operator here and these two are equal this is going to return false and therefore user john is going to be deleted from the array i know it might be a bit confusing but once you go through it a few times is going to start making sense now if we go for the jane jane's id is 3 2 1 and 3 to 1 is indeed not equal to 1 to 3 which is true so we keep jane in the array if we do this now our delete route should work but let's also send some information to the user res dot send user with the id and then we can use the template strings id deleted from the database just like that and we need to change this to be template strings okay so now if we test that out let's go back to the postman remember we cannot make delete requests or any other requests other than get requests from the browser so we need to go back here let's create johnny let's also create jane you can see jane added to the database and now if you make a get request we should be able to see all the users and you can see them right here first name johnny and first name jane with their own corresponding id now if we want to remove johnny we take his id go here change this to be a delete request and just do slash users slash his id with that if we if we send it we should be able to get request in this case we get assignment to constant variable that's of course not good i forgot to change this from const to let because in this case we are changing the users array as you can see right here so let's save that let's add two users one more time so we go to the post delete this and do we have yeah we have our jane create that create john and then we go to the get just to make sure that users are there they are we take john's id we go to delete request and then append that to the url append his id if we send that the user should be deleted and we see user with the id deleted from the database but now when we go to the get of the users we should see that john is no longer there we only have jane which means that our delete request works completely great again in here we are just using the user's array but in the real database in the mongodb for example you'd be using real methods to access the user from the database and also to change or delete users from the database again if you'd like that just let me know i'm going to create a video on that as well great with that out of the way we only have one thing left to do and that is to change the user details for example if john wants to change his first name or the last name he should be able to do that or maybe age each year he can update his age great to update the user you can see here we'll be using a patch request patch is used when we want to partially modify something when you want to create something completely new then you use post when you want to get something you just get of course when you want to delete you use delete but with update it's a bit confusing we have a patch method and we also have a put method put is used when you want to completely overwrite something so if you want to change everything there is in the user in that case you would use a so-called put method but to apply a partial modification meaning if you just want to change the age or just the name or the name and the age doesn't really matter then we use a patch and that's a perfect method for our use case so let's go there and we'll do router.patch and the path is again going to be the dynamic id because we want to know which user do we want to update then we have the request and the response we also get the id don't forget the forward slash here and now how are we going to update that specific user well first we need to find the user to be updated so let's say user to be updated and how are we going to find him well using the users.find or rather array.find method array.find goes through a lot of different um users or elements in the array and then the first one that matches it returns it so what do we need to match well we need to match the user's id so user.id to the id coming from request.parameters and then it's going to return the user to be updated once we have that user let's let's just rename it to user because user to be updated is a mouthful so once we have that user patch is going to be the most complicated method in here we use as you can see query parameters to get the id but also we're going to send something from the client sides for something from the postman and what is that something going to be well that something is going to be things we want to replace so if we go back right here and we do let's take this id which we have right now we put it after the users in this case we'll be uh doing a patch request so let's go to the patch and now we're going to send what do we want to update so in this case we want to send something like let's say first name equal to johnny and then that's going to update the current uh first name of the user with this id now that we know that we know that we're going to receive some data through the request.body so let's take these things out what can we receive we can receive the first name we can also receive the last name and the age of course user shouldn't be able to change his id we take that from request.body and then we can change those things just a simple if statement to check if there is a first name if there is a first name then we're going to set the user that first name user of course being this user here which we found which we want to update to be simply first name and then we can repeat this for everything for example in here for the last name and also we can repeat this one more time for the age so if there is age then user that age is equal to h with this we can now change one or many different properties of the user just to go through this one more time because patch indeed is the most complicated function here we are receiving a request parameter as you can see here which is the id that id specifies which user do we want to update we find it here using the find method and declare a variable user then we take all the things coming from the request of the body remember we send these ourselves from the front end or the client in this case postmen and then if we have the values which we want to replace something with then we change the user that first name with the first name user that last name with the last name and user that age with the age we can also write this in single line by removing the curly braces because this is a single line if statement and then it's going to look a bit cleaner so let's leave it like this and also now we can do a console log or just rest that send user with the id and then of course we can specify the id has been updated that's it okay if we test that out we should be able to go back to the postman create one user first so post 2d slash users and we need to have everything in the post so first name johnny last name do and the age is equal to 10 okay we send that we should get a response saying user with the name johnny added to the database let's make a get request just to be 100 sure okay we do get it and now we have this id now we can add that id to the url so that we know about which user are we talking about and then we can make a patch request to that but this time we can include only the things we want to change regarding johnny so let's say that he just had his birthday and that we just want to change the age everything else should be left unchanged and in here you can see user with the id oh my bad there i forgot to make this into a template string okay just like that has been updated great now if we go to the get request to get all the users we should get the johnny with the age of 11 and all of his other first name and last name and the id have been left unchanged amazing that's exactly what we try to accomplish our application is almost done i would like to just get your attention to one thing notice how this users routes files is not only routes of course we do have the routes but these routes have a lot of logic in them and we should try to separate the logic from the routing if you just keep scrolling you can easily get lost we have the delete route the patch route then we have two different get routes you can get lost and maybe not know which route is doing what so what people usually do is that they create a folder called controllers controllers just like this we created the routes and we created the controllers inside of the controllers you can create a file with the same name users.js and then what are we going to put into it well let me give you an example our first get route is really simple so let's do something with the post route the post route has two parameters first one being the slash route just slash users and the second one being callback function which is going to be executed once someone visits that route so we can take that and we can separate that into a new function const and that's going to be create user and that's going to be a function but we don't actually have to create this function block we just did we copied it right here so if i paste this you can see this is now a separate function create user function and it does exactly that it creates a user so right now we can just put that here instead of having it immediately in the route we now took it out into a new function and are using it right there you may say that this doesn't make a lot of sense and some may agree but now we're going to take this function and extract it into a separate file and that file is users.js of the controllers section in here we have the create user the only thing we have to do is export it so export cons create user once you do that save the file head back to the routes and then at the top make sure to import it so in here we're going to do import let's do it after this one import curly braces create user from dot slash controllers slash users.js and now as you can see we are using this function i would like you to do the same thing for all the other routes let me show you how to do it for a few more in here we're gonna take this function call it get user and now we can also go to the controllers export const get user is equal to and now i just paste it and that's it we just transferred the get user function as well as the create user function so now the functions are in a separate window or a separate file and all the routes are nicely tucked in here that's great we also need to import it so let's do import get user as well now we have those two and in here for some reason i have user user it should be create user of course okay notice how in here we have this but it's being unused it isn't used so we need to take it and move it back to the controllers because we are using the uuid right in here in the create user and that's also one way to show you we want to deal with the logic right there in here we add the ids we do something different we import different modules we return some things but in the routes we only want to have routes looks like we have an error right now and let's see why is that happening oh we are missing the dot js extension right here in the routes if we add that we should be fine server running on port localhost http 5000 great now let's do the same thing for all the other routes this one is going to be get user and again i made an error in here we have the get users plural because it's getting multiple users so i'm going to just change that move to controllers change it here as well and keep adding more functions so export const get user singular this time and make it equal to what we just copied there okay gonna keep doing that for a few more functions let's just add all the names here so get user then we're gonna have delete user and also update user okay let me take the code for the delete user and move to the controllers to add it export cons delete user is equal to this function right there and finally we have one more left which is the update user or the patch i'm gonna take this code call it update user and then in the controllers export const update user it's equal to this whole function which we just copied right there now you can see we have all the logic for our handlers right there all the functions you can even collapse them like this and now in the routes see how simple this looks now we only have the routes here and they are telling you so much more than they used to before now you can see once we do these slash users we just do the function responsible for getting the users once we want to get a user with a specific id then we have get user if we want to delete user with a specific id we call the delete user function and then you can see the function is actually in the controllers the last thing i forgot to do is to take this user's array and also move it to the controllers just at the top great that's it now let's give our application one last test let's go to our localhost and see if everything works perfectly because we did change a lot of things okay starting with the browser if we do make a get request to slash users we do see an empty array now in the postman let's make a post request to create a few users so inside of the postman make a post request and let's take the data for one specific user in this case i'm just gonna copy this johnny one and have it like this there we have the johnny and let's add him so i do post requests send user johnny added to the database let's add jane as well and finally we can add john okay user john added now we can go back to the browser refresh and we indeed do see all three users in the database great so what can we do with them let's take the id and let's go to slash users slash dot id then we get the information only for that specific user what else can we do well if we go here and now try to delete a user i'm going to do the delete route and then add the id after the users in the path run the function and as you can see user with the id deleted from the database how can we be sure that that happened we go back here to slash users make a get request and you can see we only have jane and john and the last thing to test out would be if we can actually modify a user to do that we're going to make a patch request to a specific user's id we cannot do this one because we just deleted it so we need to take a new one let's do jane for example and modified here and now we need to send some data let's say that jane remarried and now she's married to joan with two e's at the end of the surname let's do that and let's save it as you can see user with the id has been updated and now if we go back to the users save it you can see it's still jane the age is still 24 but now the last name has changed which means that our update function works perfectly and there you have it this is the full application as you can see the file structure is not that bad we have the index.js file with the setup of the server then we have the routes for all the routing and finally we have the controllers for making things work and adding the logic if you'd like me to create a video with connecting this to the database or maybe even creating a full stack mern application on this topic let me know in the comments and like this video thank you so much and see you in the next one [Music] you
Info
Channel: JavaScript Mastery
Views: 127,079
Rating: 4.9696126 out of 5
Keywords: nodejs, expressjs, backend, javascript backend, javascript node js, node js, node, javascript express, express js, learn backend, javascript node js tutorial, node js tutorial, express js tutorial, express js project, node js project, node js api, express js api tutorial, rest api node, rest api, crud api, node rest api, restful api, build a rest api, build a nodejs api, build a nodejs app, how to build an api, api express, node js api tutorial
Id: l8WPWK9mS5M
Channel Id: undefined
Length: 61min 16sec (3676 seconds)
Published: Sun Jul 12 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.