Lets Build a Node Rest API | Node Rest Api Using Express and SQLite

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up everybody welcome to coding with crayon in this week's video we're going to be taking a look at node.js so we're going to be covering the sort of fundamental concepts within this sort of note ecosystem and then we're actually going to go ahead and build a simple node rest api powered by a sql database one thing i do want to point out before we actually jump into this is that i'm assuming that you're already comfortable with javascript because this is of course a no tutorial and not so much a javascript tutorial so i'm assuming that you're already comfortable with javascript as a language so with that introduction out of the way let's get into this so the first step that we need to take is of course to make sure that we have node installed in our machines so in order to do that what we can do is we can navigate on over to nodejs.org a link to which you'll find down in the description box below and then when we actually come to the site we're going to be prompted with the sort of buttons to download the correct node version depending on our sort of operating system so of course since i'm on a mac it's already prompting me to download for them for my mac but if you're on a windows or on linux it'll basically prompt you accordingly now you may notice that you're given a choice of these two buttons whether you want to install the lts version or the current version the difference only is that the current version has the sort of most bleeding edge features and the lts version is kind of like the latest stable version but for the sake of what we're trying to do whichever version you want to use is totally fine personally i have the latest stable version currently installed but it really doesn't make much of a difference you can choose whichever one you want so click on the button of the whichever one you want to install go ahead and follow the prompts very straightforward it only take about a minute or two and then you'll have node installed on your machine so now once your installation is done let's head on over to our terminal and let's run the command node v just like so now as you can see when i ran that i got the output of exactly which version it is that i have installed on my machine of node now honestly i don't really care too much about specifically which version it is that i have installed but what this does tell me is that i do in fact have node installed on my machine so now you've basically gone through the process of trying to install node a nice way to kind of verify an easy way to verify that the installation went off without a hitch is to go into your terminal and then simply run this command node v and if you get an output of the version of node that's been installed you then know that node was successfully installed but if it wasn't successfully installed you're presumably going to get some kind of error saying that the note command isn't found so when you install node on your machine one of the sort of different tools that kind of comes along with that installation is the node package manager or more commonly referred to as npm so npm is basically this tool that lets us do multiple different things so the two things that are most commonly done with npm is a do we want to go ahead and install third-party libraries from the npm registry so in other words when you're writing your node application you might want to go ahead and reach for some kind of third-party library from github that you want to use within your application using npm the sort of node package manager allows it actually go and install those packages within your project in addition to that note npm also gives us some kind of commands that we can run to kind of help our node workflow one such command that we're going to be using right now is the init command so as is right now this folder that i'm navigated on over to the cwc cars folder that i have open right now it's currently not actually a node project so let's go ahead and change that and the way that we're going to change that is by simply saying npm init dash y so the init command is the one that actually goes ahead and initializes a new uh node project so again we're using this npm tool that came along with our node installation we're then calling its init command and then we're passing it the dash y flag and all the dash y flag basically does it kind of just says yes to all the questions that we typically get asked when we go ahead and bootstrap a new node project so again all npm and it does is it kind of turns this simple regular mundane folder into a node project so let's hit enter and see what happens okay so now that we hit enter we can see that we get some kind of output we see that we have this new file called package.json let's go ahead and open up this particular folder now in our in our editor of choice which for me is going to be vbs code and let's inspect this package json a little bit more closely so here we are now in the editor we have the package json file open and as you can see it has the sort of the name of the project the version of the project the description if you try to choose to give it some kind of a description the main file the kind of entry point and again all these um values were given by default by the fact that i said that's why had i not have sent said that's why it would have kind of prompted me all along the way like what's the name of the project who the author of the project was the version of the project so on and so forth and then in my command line it could have answered all these questions and in a real life project you might want to do this but for the sake of this tutorial simply passing that's why flag is of course good enough and then you can just choose the default values which by the way you can always just go into the package json and then of course manually change the values if you so choose to so now that we see this package.json we don't really have a lot of insight about what it is that it actually does for us so i think the best way to kind of see what the package.json really does for us within a node project is to actually kind of take a bit of a detour first and go ahead and install the first library the first sort of third-party module that we need in order to start building up our rest api and so essentially since we're gonna be building a rest api we have to kind of build up some kind of server that can listen out for requests on a certain port and then of course go ahead and be able to respond those incoming requests so the tool of choice that i'm gonna use for this particular project for our node rest api is a tool called express so let's head on back over to our terminal and let's go ahead and look at another command that mpmi that npm offers and that's going to be the install command which of course can also just be short headed to npm i and then we're going to be passing it the name of the module that we want to install and that in this case is going to be express so again the command is simply npm calling upon the npm tool giving it the i command which pretty much stands for install and then after telling it which library do we want to install and of course in this case like i said it's called express we hit enter and then we let it install this library for us so now that now that npm is done installing express for us if we come on back into our project we're going to notice that aside from having the package json we have this new folder called node modules so essentially every single time that you install something from the npm registry using this npm tool essentially you're going to be getting this sort of bit of code the actual code that is being given to you from github from the npm registry and then that's going to get put into this node modules folder i want to actually show you something interesting as it is right now the only thing that i installed was express but despite that when i actually go ahead and open up the node modules folder you'll notice that there's at least 30 to 40 folders already in here within the node modules folder and this only happened due to the fact that i went ahead and installed express and now this is going to start leading into why does that we need to package json in the first place so here's the problem since node modules is the kind of folder that can grow to be really really big in fact there's some memes on the internet where node module is like the heaviest object on the internet if i can find it i'll overlay it on the screen right now so you can actually go and see that but the basic idea is that node modules can grow to insane insane insane insane weights because every single library you want to install just installs its dependencies and its dependencies and it just grows insane now because this node modules is so big we of course don't actually go ahead and check it into source control but obviously that's now going to be posing a problem because what happens if you have two or more developers working on a team and then one developer actually goes out and install that installs a dependency which now the project relies on its dependency to be able to work and function correctly now when the other person the other person on the team tries to then go ahead and pull down the code they're now not going to have the dependency because again we're not actually checking the dependencies this node modules folder into the source control it's not being put into git so now how is the other person supposed to be able to run their code if they don't actually have the dependency installed well it turns out that's exactly what the package.json is going to do for us so if you now come back to the packages you'll notice that one of the additional fields that have been added for us by npm is going to be this dependencies section so this dependency section is now as you can see is listing express and so now we can start to kind of see what the package.json is doing for us essentially the way that we now can have our node modules uh be source controlled without actually having to commit the actual node modules folder is through using this dependencies section within the package.json so this this would basically be the flow i would like to work on a feature that requires me to go and install another module i will then install the module it's going to show up inside the dependency section within my package json i'm then going to go ahead and commit my work push it back up to github and then my co-worker can come and pull down now of course i didn't check it into node modules i only checked in the actual packages and that includes the list of the dependencies that i've installed now my co-working then go ahead and pull down the work and then i can say i can tell them by the way i installed a new dependency and then what that means for them is simply they can open up the project going back to their terminal and then simply run the command npm i without passing it any other name simply saying npmi or npm install is going to be enough and then what that's going to do is node is going to go ahead and scan the list of dependencies that have been specified within the dependency section of the package package.json compare that against what's currently not yet installed from within the node modules and anything that's missing would get installed just like that so effectively without actually going and checking in the node modules to source control we still have the concept of actually having source controlled mods within a project through the package.json's dependency section and that's pretty much what the package.json does for us okay so now that we actually have express installed within our project let's start writing the sort of basic code that we need to kind of start writing the server that we're ultimately going to end up using to kind of listen out for the requests for our rest api that we're gonna be building down the line so you'll now notice that i actually created a new file called server.js and these few lines of code is all it takes to kind of build up a simple server that can now start listening out for um actual requests and then be able to respond back those requests to whoever's making the request so let's examine this code so already in line one you'll notice that we're saying const express is equal to require express and there's a good sense that you're thinking well what exactly does require do i've never actually seen that in browser-based code so let me quickly explain what require actually does since this is a sort of more node specific concept it turns out that node actually offers something called file based scope essentially when you're writing browser-based javascript so you might have like one html file and then on that html file you might have a couple of link tags or a couple of script tags where you're kind of referencing different javascript files so in the browser despite the fact that you have multiple different javascript files all of those files with all of those javascript files actually share the same scope because they're all linked to the same html file and then what that means is if let's say in file a i might declare a variable const my variable in file b i then can't go ahead and once again declare const my variable because the variable already exists and i'm going to have a naming collision almost if i actually write my own function or my write my own iffy or some kind of way create my own separate scope but individually the file itself just because it's a separate file does not in fact create a separate scope on the other hand in node we actually have file based scope which means that if we have some kind of code that's written in one file and then i have another file one file scope does not share another file scope which means if i have a variable declared myvariable in file a i can very safely then once ahead once again go ahead and write my variable in file b and there's not going to be any naming collisions because each individual file creates its own module and then basically every module has its own scope now the thing is sometimes you might want to actually go ahead and reference code that lives within a different file or within a different module and that's exactly where the require function comes into play so essentially the require function can be used to either require something from within the node modules folder in this case we're actually requiring express express was installed for us by npm and then put into the node modules folder so we kind of want to get that code out of the node modules folder out of that express folder so we're telling it to simply go to express and get that for us alternatively require can also be used to kind of import or require our own local code so let me show you a quick example of that okay so let's take a look so here i have a file called foo.js in this file i'm basically saying module that exports i'm calling upon the sort of module object that gets passed into me into my file i'm calling it exports objects and i'm basically telling it i want you to go ahead and export this function and then all this function is going to do whenever somebody calls it is just log icon from another file we then move on over to our bar file which we've also just created and then i'm saying const func is equal to required dot slash foo so the only difference between this required statement here and this requires statement here is that here i'm not using any kind of relative path i'm just specifying the name of the module and then node is going to go look into my node modules folder to find my module whereas here in the bar file i'm actually specifying a relative path and i'm saying go to dot slash foo and that means that instead of going to the node modules folder go look at my own individual file system and find my own relative path so now if we actually go ahead and run the bar file we can actually see that we get the output icon from another file so it's all working exactly as expected and that's basically what the require statement actually does so now moving on further down the line of what we're doing within this particular file we're basically saying that we're going to be uh getting this app object by calling this express so notice when we import express from the express module express is basically like a factory function when you call it you're basically going to get this app object and then this apps object basically is your interface to start building up your entire server so what we're doing here is we're pretty much specifying a get method off of this app object and this get method is going to be listing out for the endpoint of slash test when we get a request to slash test we're going to have this callback function fire which this callback function will receive a request object and response object and then off of the response object we're going to be sending back a status code of 200 and then a json message of success is equal to true and then down here on line 8 we're basically telling the express object of the app that it's going to be listing out on port 1337 and then when the server successfully starts up this callback function here is just gonna lock to our terminal that the server is running on whatever ports it is that we specified so let's actually see this in action so in order to actually run this once again we simply use the command node in other words now we're not gonna use the npm command we can if we want to by actually creating a script and i'll demonstrate that in just a second but for now if you want to just be able to run a file any kind of javascript file that's that lives in node you can just use the node executable to actually go ahead and run those files in this case we're going to be trying to run the server file so we're going to say node server.js that's going to bring up our server and now if we actually go into the browser go to localhost one three three seven slash test we should actually get the object of success is equal to true so let's see that happen so as you now notice i've navigated on over to localhost one three three one three three seven slash test and here you can see i'm getting back my json object of success is equal to true so as i've mentioned right now the way that actually brought up this particular uh server the way that i kind of started up my application was actually calling upon the node uh command and then calling server and then telling it to run the server.js file but as i said we can also use npm to make that happen and let me show you how if you head on back over to your package.json you'll notice that we have this section called scripts so we can do is we can create a new script called start and then what we can tell the script to do is to very simply say node server now if we come on back to our terminal hit ctrl c to stop the process and so now instead of saying node server.js we can actually say npm start and it's going to do the exact same thing so now we're actually calling upon npm to run our own local start command and then what that start command is doing is actually going to go and say node server.js and then this is going to bring our application up and running and now once again we could if we want to go to localhost 13337 and start listing out and start making some requests so now that we actually have our server up and running the next step to kind of get our rest api to work is actually go ahead and set up our database now before we actually jump into the actual database setup i just want to point out very quickly that whatever i'm about to do with our particular database and i'm going to be using sql lite would just as easily be working for using mysql or if you're using postgres and if you're on windows you can even do this with all with sql server so since i'm going to be using sql lite the first thing i need to do is actually go ahead and create a sqlite file to kind of act as our database within this particular project okay so i've basically created a new file called cwc standing for coding with haim.sqlite3 so essentially all sqlite is it's basically a file based database now they actually have this file set up and we actually have our sort of database setup we now have to actually have some kind of gui that's going to let us manipulate this database and go ahead and add tables to it and then of course the schema of those particular tables to this particular database now now because i'm going to be using sql lite i'm going to be using a tool called db browser which is going to be the gui that i'm going to be using to kind of actually uh manipulate my sqlite database and if you want to actually be able to follow along if you want to install this i'll leave a download link down in the description box below where you can actually find uh the download link to go install db browser and you can install it for either windows or mac and potentially linux oh so i'm not entirely sure but you can just follow the link and see if there's an option for you to install it on linux as well okay so i pretty much clicked on this open database button right over here this brings up the sort of file explorer i then navigated in over to cwc cars which is the project that we're currently working in and as you can see right over here we have the cwc sql lite3 file we're going to go ahead and open and now we basically have our actual database open within this gui and now we can actually start using the gui to manipulate our database by adding tables to it and of course adding a schema to that particular table so i'm going to quickly speed through that and i'll catch you when the actual setup for the database is done okay so now as you can see we now have a table called cars and this table has a primary key that's going to be an id it's going to have a make a model and a year and that's basically going to be the actual database and table already read up ready and set up and now we can actually move on into the code and start writing the functions that we need in order to start being able to manipulate the data within this particular database the next thing we need to do is head on back over to our terminal and we're gonna have to install two more dependencies to be able to start working with our database and start actually carrying out all the sort of basic crud operations against our database that is you have to create read update and delete cars within our database we're gonna have to install two more modules to kind of make that work so as you can see i'm once again calling upon the npm tool i'm calling upon the node package manager and then i'm calling upon its i command which basically stands for install and this time instead of only passing one dependency at a time i can actually pass more than one dependency and then it will just install all the dependencies that have been specified after the i command so in this case i'm installing something called connects and connects will basically be the tool that will allow us to actually go and execute our sql statements against our database and then under the covers connects actually will be relying on sql lite3 since that's the database of choice that we're using here we have to make sure we have sqlite installed so that connects and go ahead and rely on it because as i mentioned what we're doing doesn't only have to work against the sqlite database it can just as easily work against a mysql or a sql server or postgres and all that's due to the fact that we're using this tool called connex and the way that that works is you install connects and in addition that you install the driver that you want to use but the syntax will basically be pretty much the same because connex is mostly a database agnostic tool that lets you execute uh sql queries against a whole host of different sql databases without really having to change your syntax so let's hit enter and let both of these dependencies install okay so now that our dependencies are done installing let's head back on into the code and start writing the functions necessary to execute all these sort of crowd operations against our cars table okay so here's what i've done so far as you can see i've created a new folder called db and within this folder all i've basically done so far is i've created a file called connect.js and then within that file i went ahead and imported kinect by calling the require function again passing the name of the module that i want to import which in this case is just connects now by default when you actually import connect at this point you don't yet have the ability to start using connects to execute queries against your database because you're not yet connected to your database connex doesn't quite know how to actually go and connect your database which is why what we're doing here on line three we're actually saying we're calling the connect function passing in this configuration object and then what this is going to return to us is going to be a connected instance of connect because within this object we're basically passing this sort of configuration object of teaching it how to actually go and connect to our database so in this case we're just using sqlite which makes it a lot simpler but if you're using something mysql or postgres or sql server this is where you kind of be passing in your connection string to teach it how to go ahead and connect to your actual database in this case we're saying that the client of choice that we're going to be using is going to be sqlite and then the connection here in this case is just going to be the fact that we're going to be going to a file called cwc dot sql lite3 now the next thing that i've done is i've actually gone ahead and created a new file within the db folder called cars.js and what you'll notice here now is i'm actually going and i'm importing uh connects from required dot slash connect so you see now i'm using a relative path which means i'm going to my own local file here going to this connects file and what i'm trying to import is i'm trying to import my own connected instance of connect which means i don't want to use the actual module at this point because that one doesn't actually have the ability to go ahead and connect to my database at this point i'm trying to use the connected version of it and that's why over here if you come back to my car's file i'm saying dot slash connects go to my own relative file and get me what that file is going and exporting towards me and then here these are all very very self-explanatory all i've really done is i've created the sort of four functions to allow me to go and execute the sort of four basic operations against my card table so i've got the ability to go ahead and create a car which will accept a car object that's then i'm going to return the promise that connects return so whenever you call a connect function against your database it's going to go ahead and return the promise so we're going to actually just take that promise and return it onward to whoever's actually going to call this function and so all the thing connects of the table cards go ahead and call the insert method passing in the car object then down here we're going to go to the get all cars method which is going to go to the cars table select everything from it delete car is going to be accepting an id it's going to then go ahead and say that where the id is equal to the id that's being passed in we're going to go ahead and call the delete method and then update car works kind of in a similar fashion we're going to be accepting the id of the one that we want to update as well as the car itself the sort of new values for that particular car we're going to go ahead and say connects of the cars table where the id is equal to the one that's currently being passed in i want you to go and go ahead and update the car and then finally down here on line 19 we're basically saying module that exports we're going to be exporting an object this object is going to be having four keys and these keys are pretty much just nothing more than the actual function that we've gone ahead and just created right now to be able to execute sql commands against our cards table so finally the last thing we really need to do at this point is actually just go ahead and build up our actual express endpoints to be able to listen for the incoming request and then go ahead and call the corresponding function depending on which endpoint is getting hit so let's do that now okay so let me walk you through what i've just done so you'll notice right over here on line three i'm actually going and i'm importing this db object which again references that object that has those keys on it to sort of db that cards right so in other words if i can do a db.createcar db that delete card get all cards right so in other words we actually go to the dot db folder and within that folder we're going to the actual cards file we're going to be importing the sort of object that that folder that that file is going to be exporting for us and it's going to be the object that contains those individual keys where each key represents a function to execute some kind of sql against our cards table and then down here what we're basically starting to do is just specifying the sort of four necessary endpoints to go ahead and handle the four basic operations that we want to have on our cards table so let's walk through each one very simply over here i'm making a post request to slash cards the callback function that i'm passing to slash cards is marked with the async keyword which will then allow me to actually use the await uh keyword within the actual callback function and then what we're doing is we're basically saying db.createcar passing in rec.body now right over here i do want to already point that that we are currently in trouble as it is right now we don't actually have a fully working rest api just yet because as it turns out when you're actually using express by default when you're actually sort of accepting some kind of post request or even if it's a patch or put or whatever something that includes a body by default express doesn't actually have the sort of ability to extract the data that lives within that body and so what's end up happening is when you actually try to call upon the request object calling upon its body key the body is going to just be an empty object and it's not actually going to have the data you kind of pass along within your post request now there's actually a way to solve this and the way to solve this by installing a tool called body parser so let me actually go ahead and quickly install body parser and show you very quickly how we use it so once again we're gonna be calling upon the npm tool calling upon its i command the install command and we're gonna say that we wanted to install body parser okay so let's let's take a quick look at the additional code that i've just added so we come back now to line three you'll now notice that i'm actually importing body parts or by saying require body parser and then here on line six and seven you'll see that i'm actually saying app that use body parts of the url encoded i'm basically telling express i'm gonna let body parts or teach you how to parse any requests that are of the type url encoded and then on line seven i'm basically telling express that i'm gonna let body parts teach you how to go and parse the sort of json uh body now i'm not gonna dive too deep into what this is actually doing and how this actually works but this is basically known as the concept of express middleware and so all you need to know for the sake of this video is that essentially by time we now actually are going to get to our app that post you're going to go to the slash cars at this point direct that body instead of actually being an empty object is actually going to be the object that you actually passed in along with your actual post request and that's all thanks to the fact that we're saying app that use body parts without url encoded body parts about json essentially this sort of middleware this app that used that's going to be accepting the body parser function will actually allow express to now learn and understand how to actually go and parse the body out so therefore by time we actually get to our actual end point wreck that body instead of it being an empty object is of course going to be the actual values that we actually went ahead and passed along with our post request now i understand that's kind of vague but that's all i'm going to say for the sake of this particular video if you like to understand a little bit more about how the body parts are and how middleware actually works i actually have a video about just that particular topic to which you're going to find a link to that video down in the description box below so once again we have our endpoints set up we have the post request going to slash cards this is we're going to be calling the create car method passing in direct divided which is now no longer going to be an empty object here we're pretty much going to go to slash cars making get requested slash cars getting all of those cars sending back a status code of 200 with a json object of cars where the cars are going to be representing the array of all the cars here we're making a patch request to slash cars colon id but essentially we want to make sure that the request is going to be slash cars slash the actual id of the car they're trying to update and so the way they were specifying that is by saying slash cars slash colon id which now means that we actually go ahead and call the update car which expects us to pass in an id of individual car we can pull that out of the url by saying rekt.params an id this id variable name here is going to match up with what we actually specified after the colon in the actual url and then the same thing kind of happens within the leap method the delete car method actually expects us to actually pass the id of the card we're trying to delete so once again we're gonna say we're gonna go to slash cars slash colon id and then we can call upon wreck the params that i need to actually go and pull that id out and again this id here matches whatever has been specified in the colon after what's been specified in the url after the colon now that's actually all the code that we need to kind of build a simple node rest api now let's actually go back to our terminal run our npm start command get the server to be fired back up again and then we can move on over to postman and start seeing whether we can actually go ahead and start executing some of these commands against our cards table in a sqlite database okay so our server is now running on port one three three seven let's head on over to postman and start executing some of these requests okay so here i am now in postman as you can see i have a post request specified going to http localhost one three through seven slash cars i've got the body specified of type raw i'm saying that's going to be a json body and here you actually you can actually see i'm saying that we're going to have a make of honda the model is going to be a chord you're going to be 2019. let's go ahead and run this particular request and if it all works well we should of course get back idf1 which is basically the idea of the newly created card that we just uh inserted which so far it seems like the actual ability to go ahead and post a new car seems to work but the best way to verify this of course is if you move on over to the next tab we're gonna be trying to make a get request to get all the cards if we run this particular command we should of course get back a car's key that's going to be in a rape all the cars which of course in this case is just the one car that we actually just went ahead and created now let's actually go ahead and see if we can go ahead and delete a car if you move on over to the next tab we're basically saying we're gonna go to slash cars slash one that's gonna be the id of the car that we currently have in the database the one that we want to go ahead and delete right now if we actually go ahead and run this command now we see that we get successes equal to true which means if we now go back to our get request we're trying to get all the cards if we run this now again we should just get an empty array which we do which means that our rest api is actually working exactly as expected well that does it for this video hope you enjoyed it i hope you found it useful if you did please drop a like subscribe and i'll see you next week in another video [Music] perfect [Music] you
Info
Channel: Coding With Chaim
Views: 29,966
Rating: undefined out of 5
Keywords: lets build a node rest api, node rest api, node crud rest api, node crud api, node with sql, node with mysql, node tutorial, node rest api with sql, nodejs basics, nodejs rest api, lets build a nodejs rest api, calvin friedman, chaim friedman, coding with chaim, node js api tutorial, node js tutorial, node js, express tutorial, express api
Id: cr3pX6fSUpc
Channel Id: undefined
Length: 25min 31sec (1531 seconds)
Published: Wed Dec 02 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.