Build A REST API With Node.js, Express, & MongoDB - Quick

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today we're gonna build your very first rest api as quickly as possible let's get started now now in order to create this REST API we're going to be using nodejs Express and MongoDB in order to get started with that we first need to run NPM in it so we just type in NPM in it and we just want to hit enter a bunch of times in order to get all the default values and as soon as we do that it's going to create a package JSON for us next we want to install all the dependencies that we're going to use so our dependencies we can just type NPM I and our first dependency is going to be expressed and then in the next dependency that we're going to be having is Mongoose which is going to allow us to interact with MongoDB easily Express is really useful for when we want to create an application using no GS because it's just much easier to create a web application using Express then standard Medici is next we want to use NPM to install our development dependencies so we can say m PMI and we just want to say - - save dev which is going to make these B development dependencies that do not get installed in production and we want to use a and V and we also want to use node Mon now dot env is going to allow us to pull an environment variables from a DNV file and node montt will allow us to refresh our server every time we make changes without having to manually end it and restart it now that we have all those installed let's remove this test script and create our own script called dev start which will allow us to start our server using node montt and we just want to type in node Hmong followed by the name of our script which we're just going to call server Jas we can save that and actually create that new file called server jeaious and here we go this is where we're going to put all over a different server code and before we get started on you further we want to create that env folder file right here and this is going to have our environment variables and we also want to create a dot git ignore since we're going to be storing this on git using github or bitbucket or whatever you want to use and we want to ignore env file since that's going to have sensitive information and we also want to ignore our node modules folder because this can be installed and created by just running npm install whenever you download the code from github or wherever it's stored now with that out of the way let's create our actual server and the first thing we want to do is we want to require Express so we'll just create a variable which is called require Express just like that and that's going to pulling the Express library next we want to create a variable called app and we just want to run Express function just like this and that's going to create an app variable which we can use to configure our server next we can just say app dot listen tell what the port we want to listen on in our case 3000 and we're just going to pass it a function here and this gets run whenever our server gets started so we're just going to log out that our server was started so we'll say console dot log and we'll just want to say that this server has started now if we save that we run that method that we created earlier which is NPM run data start hit enter and this is going to start off our server using node montt and as you can see it says server started down here and we can go to this app localhost 3000 and our server is going to be running there but right now it doesn't do anything so let's make our application actually do something next we want to configure Mongoose to connect to our MongoDB database so we're going to require that library we'll just call it Mongoose and we're going to type in require Mongoose which again is going to require the library Mongoose and allow us to set it up the next thing we need to do is actually connect to our diet database so we'll type in Mongoose connect and we want to put in here the string which is our database connection and in our case this is going to be MongoDB colon backslash backslash and then it's going to be local host since we're on localhost and then again slash and we want to type in whatever our database name is going to be called and we're just going to call this subscribers because this is going to be a database that holds subscriber information which is what our REST API is going to handle and then after that's done we can just save this and you can see down here we get this deprecation warning saying you use new URL parser true needs to be passed in because the old one is deprecated so what we can do is we can pass that option in to the end of our connect just like this now if we say that you see that that warning message goes away and we have nothing else to worry about also what we can do is we can actually create a variable here called DB which going to be equal to Mongoose connection and from here we can hook up some events to run when our database is connected to so we know it's working correctly we can just say DB dot on and what we want to do is on error we want to log out that there's an error so we'll just say here this is going to take a function with an error and we can come in here and say console err and we can pass it that air this will just allow us to see if there's a problem connecting to our database also what we want to do is that once we connect so we'll say data DB dot once which means it so only one runs and whenever we open the database what we want to do is we want to console that log saying that we've opened the database so we can just say connected to database just like that and now when we say if we should get the message down here saying connected to database and that's perfect but one thing that you'll notice immediately is that we have our MongoDB database string inside of our application and when we deploy our application we're going to want to use something that's not our localhost so we need to pull this out into an environment variable so let's remove this right here go into our env we can just create a variable which we're going to call database URL and we want to set that equal to our MongoDB library right here and now inside of our server we can come in here and use process a and V dot database URL or just whatever you name this inside of your diet UV folder and this will pull from our die and V but you'll notice we get an error and that's because we need to use the dot env library so all the way at the beginning we can say require env and all we need to do after require this is call the config method so we'll just say config and this is going to load all of our environment variables from our env now when we say that you'll see we no longer get an error down here and it says we connected to our database successfully so now we have a database completely done our server is completely hooked up and listening all we need to do is actually create routes for our server and also set up our server to accept JSON so let's first set up our server to accept JSON we can just say app dot use which will allow us to use any middleware that we want which is essentially code that runs when the server gets a request but before it gets passed to your routes and what we want to do is we want to use Express JSON and this essentially just lets our server accept JSON as a body instead of a post element or get elmer or whatever also what we want to do is we want to set up our routes so since we're going to have a subscriber API we're going to have some routes that are going to be called subscribers routes oops subscribers router there we go host I cannot spell subscribers router there we go and this is going to route all of our subscriber information and we can just say require and this is going to be inside of a folder inside of our application called browse and it's just going to be called subscribers so we can create that now let's create a new folder this is going to be called routes and inside of this folder we want to create a file which is going to be called subscribers j/s it just needs to match the name that we added in here for subscribers right here now once we have that we can go in here until our app that we want to use that route so we can say app dot use we pass it the path we want which in our case we want to use this whenever we query subscribers so our URL is gonna look like this localhost 3000 slash subscribers and this is going to be right here this URL everything that has this URL or anything after it is going to go into this subscribers router which we created right here so now that we have that done we need to actually tell it we want to use the subscribers router and there we go our application is set up and working and you'll see that we get an error and this is because our router dot use requires middleware this subscriber router right now is absolutely nothing this is completely blank so let's set that up we again need to use Express so we're going to say require Express in here this is because our entire application uses Express and what we want is we want the router portion of Express so we can just say Express dot writer and this is going to get us the router from Express and for now all we want to do is export that so we can say module exports is going to equal to router this is just going to fix our errors down here and as you can see we no longer get any errors everything's working fine but we have no routes actually configured yet so this is going to be a restful api we're going to use restful endpoints and if you don't already have a strong grasp of what rest is and what restful endpoints are i have a really short video going over rest in depth which you can check out in the cards and the description linked below so now let's start creating our different routes we're going to want some routes for getting all subscribers we're going to want to route for getting one we're also going to want to route for creating one we're going to want to route for updating a single one whoops updating one and we're also going to want to route here for deleting one and let's configure those routes to do that we can just say oops router dot git for example which is going to be get and to get all we just want to use this blake path right here and of course all these are going to take a request and a response and that is going to be a function and inside of here we're going to do all of our code for our different routes so let's bid all these routes created for getting one we're going to want an ID in here and with a colon in front of it like this this means that this is a parameter that we can access by typing in request dr. Ramsey and this would be whoops Rams dot ID and this would give us access to whatever they pass in after the first slash next we want to create our crate route and this is going to be a post instead of a git so we can say dot post and again we're not going to need an ID here since they're not actually going to be creating it with an ID they're going to be creating it on just the general route next we need to do update so come in down here and we're going to be using patch instead of put for our update because we only want to update based on what the user passes us if they only pass us the name of the subscriber we only want to update the name and none of the other information about the subscriber because if we used put it would update all the information to describe it all at once instead of just the information that gets passed now lastly we want to create our delete route what are you going to be extremely self-explanatory those are just going to be delete and again we need an ID here as well as on the patch route we're going to need an ID and this is the basic shell of all the different routes that we're going to create now in order to test these routes what's create in here just a res dot send which is just going to send text down to the server and we're just going to say hello world so that we know that we actually have called this get route here for getting all of our subscribers and normally to test these you may go into the browser and open it up but you can't really test a REST API very well in a browser because you have nothing to interact with so what we're going to use is we're going to use an extension in Visual Studio code and this extension is called right here rest client has two million downloads is incredibly great and it allows you to call a REST API directly from Visual Studio code you can also use a program such as postman if you want to instead but I really like being able to do this directly in Visual Studio code so what we want to do is we want to create a path here a file which is going to be should be called route dot rest you can call it whatever you want it just has to end in either dot rest HTTP and in here we can create our request so in our case we want to create a get request and we want this get request to go to HTTP slash slash will host 3,000 and we want it to be in the subscribers so we're going to say slash subscribers oops that added a little bit more than I wanted and this is actually going to request that route that we just set up right here or get all route and what we can do is we can just click send request and it's going to send that request and as you see we get a hello world back at the top here we have all the different headers and statuses we can pretty much ignore this for the most part but down here is going to be the actual content of the request that we get sent so as you can see right here we got hello world and if we go into this one we can do res dot send and we want to send the request dot params that ID for example and we can make a request to that in our route rest we can even do multiple so if we just add in here three hashtags and then we do another route this will separate these into two different requests and we can do an ID let's say 12 for example we click send and we get that ID 12 back change it to 15 and we get 15 back so we know that our routing is working and we're able to call it directly from visual studio code now with all that out of the way let's actually create our model that we're going to use for our application so we can create a folder called models which is going to hold our model which is going to be a subscriber model so we'll just call it subscribe yes and in here we're going to be using Mongoose so we're going to require mongoose call it Mongoose equals required and again Mongoose and this is going to allow us to create a model which we can use to interact with the database in a really easy way so what we want to do is we want to create a schema we're just going to call this our subscriber schema Wolf's cannot spell there we go and we're gonna set this equal to a new Mongoose dot schema and this is going to take in here a JavaScript object and this object is going to have keys for all the different properties of our subscriber in our case we're going to have a name and this is going to have an object as a value we'll fill it in later it's going to have a subscribed to channel so this is who the user is subscribing to which again we're gonna fill in the details later and lastly we're going to have a subscribe whoops subscribe date and this is just going to be the date that they subscribe to the channel and again this is going to take value in here and it looks like I spelled this incorrectly there we go and what we want to do instead of here is actually define the different properties for our schema so we want to put the type in our case the name is going to be a type of string and we always want the name to be required so we're just going to have required true here we're going to do the exact same thing for the subscribe to channel it's going to be a string and it's always going to be required and then lastly we have our date this is going to be a type of date it's going to have a required of true as well because we always want to have the date they subscribed but lastly we want to default this so we're just going to use here default and we want to set this to date now so if we don't pass our subscribed date it's just going to default it to the current date now with that schema created we can go down here we can export that so we can set it modules module about exports we want to set that equal to Mongoose top model and now this model function takes two properties the first is the name of the model in our database in our case we're going to call a subscriber and the next is the schema that corresponds to that model which in our case is subscriber schema and the reason we need this model function is because when we export this and import it in a different file this model allows us to interact directly with the database using this schema which is perfect so now let's save that go into our subscriber J's here and we can include that so we can say subscriber is going to be equal to require we want to require back one folder in the module models folder subscriber and now this is going to pull in our subscriber which we've created in this model here and this is where the fun really begins so let's do our first to get Oliver out because this is about the easiest one we're going to use async await in order to do this so if you don't understand a single link I have a video linked in the cards and description which you can check out but essentially what we're going to do is we're going to wrap this all in a try-catch just like this and inside the try we're going to get all of the different subscribers for our model so we're gonna say Const subscribers is going to be equal to our subscriber model dot find and this is just going to get all of the different subscribers and we need to make sure we await this because this is an asynchronous method so if we await this as soon as it's done executing we're going to get all the subscribers here in this method but if for example there's an error we want to make sure that we catch that error so if there is an error we want to send that to the user and we want to send it as JSON because this is a JSON API and in here we're just going to send a message which is to be error message just like that and we also want to make sure we set the status so the user know that it was failure so we can say dot status and here we want to send the status code in our case we're going to send a status code of 500 now 500 status code means that there's an error on your server it means that the actual server in our case our database had some kind of error which caused the actual transaction not to work and it had nothing to do with the actual user or client using the API it was entirely our fault that's what 500 means and any error code that's in the 500 range means that now if we actually were successful we want to send this using JSON we just want to send all the subscribers to the user now we can go in here we can test our route and we should get back just an empty array and as you can see that's exactly what we get we get an empty array because we have no subscribership so let's create our create route so we can actually add subscribers and see what it looks like we'll scroll down to that and we're also going to make this an asynchronous function because we're going to be trying to save that model which is an asynchronous operation so we want to create a variable called subscriber set it equal to new subscriber and this is just going to take a javascript object first thing we want to set is the name and this is going to come from the request from the body so the body is whatever the user sends to us which is going to be JSON and we want to get the name property of the body we want to do the same thing with the subscribed to channel and we want to set this to the request from top body dot subscribe to channel and let's close out of this request here and there we go that's our subscriber created but now we actually need to save it and that's where the asynchronous part comes in so we're just going to wrap this in a track catch again and we want to catch that error of course and inside the try here what we want to do is we want to try to save our subscriber so we're gonna say a new subscriber is going to be equal to a waiting the subscriber which we just created that save and this is going to try to persist that to the database and if it's successful it's going to put it into this new subscriber variable and if it is successful we want to send this to our user using JSON so we'll say native subscriber and we also want to set a specific status here we want to set a status of 201 and the status 201 means successfully created an object by default if you don't send any status it sends a status at 200 which means everything was successful but 201 is just a more specific way to say that you created something so when you're using a post route you always want to make sure to send 201 when you're successful instead of 200 now let's catch that error so we want to say res dive status and this time we're going to send a status of 400 instead of 500 and this is because our thing is going to fail here if the user doesn't pass in the name or they don't pass in a subscribe channel for example so if the user gives us bad data it'll fail and whenever the user gives you bad data at the client you want to send a 400 error because that means there's something wrong with the user input and not something wrong with your server and of course we want to send that error message to them so we'll say JSON error message and of course we want to make sure we wrap this in an object just like that and there we go we can save that and now let's actually test that so down here make sure we put in our three hash tags and we want to do a post route and we want to post to essentially the same exact voice HTTP localhost 3,000 subscribers and that's exactly perfect and now to send data to it we had to make sure we leave a blank line here but and then here we can put our JSON so let's type it in we want to send a name whoops make sure it's enclosed name and we want this person to be amazing person is their name and the subscribe to channel whoops type that out correctly subscribed to channel is of course going to be web dev simplified because all of my subscribers are amazing people web dev simplified and there we go and now that we want our server to know that this is going to be JSON that we sent to it so we need to set the content type to be a clone application slash JSON now we can click send request and you'll see that we get a message as a subscriber validation failed subscriber to channel path subscriber to channel is required and this means I spelled something wrong I spelled subscribe to channel as subscriber to channel so let's see where I did that we can just do a search all hit enter and it looks like in here in our schema I just misspelled this it should be subscribed to channel instead of subscriber to channel now let's go back and tell starter out we can click send request again and you see that we get our model back it has an automatically generated ID as well as the name subscribe to channel and subscribe date which you can see is set to whatever the current date that I'm recording this is and if we don't pass in the name for example and we hit send request we're going to get back that error message and you'll also notice we get that 400 status which says bad request which is perfect because it'll come back as an error to the user using our API let's plug that back to how it was so we have a successfully working API now let's go back to our route here and you may notice that all the rest of our routes are going to be taking an ID our update our delete as well as our get all have an ID that we're going to pass to it and they're all going to do the exact same code at the beginning in order to get the subscriber so instead of writing that code in every single one of our routes we're going to use what's called a middleware so we're gonna create a function which will be that middleware and these functions have the exact same syntax as this function right here we're gonna call this one get subscriber because essentially that's all it's going to do it's going to take an ID and get us a subscriber and as I mentioned it has a request response and next as the final property and essentially all that this next function does is this says if we call this move on to the next section of our code which is going to be this callback right here this is what the middleware is and of course we're going to make this asynchronous because we're going to be accessing the database inside of this code and now of course we want to wrap everything inside of a try-catch so put the try right here and of course we want to catch our error and now inside of this track we want to give up subscriber so we're just going to say subscriber is going to be equal to awaiting the subscriber dot find by ID and this all we have to do is pass an ID which as you remember I said that request dot params dot ID is going to be the correlating to the variable that they pass inside of the route here so this is going to try to get a user based on the ID that they pass us inside of the URL and then what we can do is we can check to see if that subscriber actually exists so we can say subscriber equals null so if the script scriber does not exist what we want to do is we want to return here and we want to set the status right here to be equal to 404 and a 404 status means that you could not find something and which is exactly what happened in our case we're not able to find this was and then of course we want to send back a message to the user knows that whoops so we'll send back a message here and this message you're just going to say cannot find subscriber there we go now that we have out of the way let's actually create our subscriber up here we're just going to default this to undefined and what we want to do is we want to set our response dot subscriber this is just a variable worker crating on the response object we're going to set that equal to subscriber and this way inside of all these other functions we can just call res dot subscriber right here and this is going to be the subscriber that we set down here so let's leave that now and the reason we're calling return here is because if there is no subscriber we want to immediately leave this function and no longer go any further and inside of this catch here we just want to do essentially the same thing we want to do a return we want to set the status this case it's going to be a 500 because there's something wrong with our circuit that's causing this problem and we want to send that message back to the user so we're going to set a message is going to be equal to error message just like that which is perfect and then lastly that next function we want to call all the way down here because we successfully completed this entire gift subscriber function so next will allow us to move on to the next piece of middleware or the actual request itself so now let's use that get subscribed or middleware we'll go up here and all you do is put it before your actual function you don't actually call it you just put the name of that function right there and that'll be your entire middleware setup now instead of here we can say that we want to send a request response dot subscriber dot name for example and if we save that since we have this gift subscriber in here this is actually going to get the name of the subscriber and send it back to us this is just for testing purposes so let's get all of our subscribers here we'll send a request we're going to take an ID and we want to use that instead of this request to get a single subscriber and if we click on that you'll see that we get the name of that subscriber which is amazing person and that's perfect if for example we send a different ID which does not exist and we click send you'll see we get a message that says cannot find subscriber so we know that our middleware that we created is working so now we can apply that middleware to the rest of all of our routes so let's copy this down do this inside of here and we also want to do this inside of here for our deleting let's exit out list so we have a little bit more room to work with and now we can actually create our route right here for getting one and this is really straight for it all we want to do is send that actual subscriber so we'll say res dot whoops not res die json read subscriber and this is just going to send us a json version of that subscriber and of course we can try calling that right here and you'll see we get the JSON version of that back which is perfect now back to our Reb's we can work on the delete route because that one's also really straightforward we want to make sure this is asynchronous because we're going to be calling this using try catch so what stead of that try catch just like that and we of course want to be able to catch an error in here if something for example happens and inside of here all we want to do is we would want to wait res dot subscriber dot remove now this is just going to try to remove that subscriber from the database and if it fails we're going to get an error down here which we can just send back a status of 500 because something obviously is wrong on our end if we get an error trying to remove it and we'll just want to send back the message as the error dot message and if we did successfully remove this subscriber we can just send back some JSON that says that we did that so we can just say in here we want to send a message that says deleted subscriber so now let's try to call that we can just come down here separate it with three hashtags just like this and we want to call delete and we just want to call it on the route up here for the user with the correct ID so let's copy that down and let's call send request and you'll see message deleted subscriber and if we try it again you'll see cannot find subscriber because we deleted that subscriber and if we try to get all of our subscribers we now get an empty array again because no more subscribers exist so let's send that request to add a new subscriber back so we have at least one subscriber here as you can see inside of our database so we can use that with our new patch route that we're going to be creating now now in order to update we need to as I said only update for things that actually are sent to us in the request so what we want to do is we want to check the request we can say if the request dot body dot name is not equal to null so if the user actually passed a name to us we want to take that res dot subscribe and we want to set the name equal to the request body dot name and we wanted to the exact same thing but we're gonna do this for this subscribe to two channel so in here we'll type in subscribe to channel and we want to set the subscribe to channel to the subscribe to channel that's passed in try saying that ten times fast now we can actually use the try catch down here in order to try to update our user we of course want to catch that error and instead of here all we're going to do is we want to say this is going to be our updated subscriber whoops subscriber is going to be equal to a wait so res dot subscriber just want to get our subscriber and again we're going to use that save function so this is going to give us the updated version of our subscriber if they successfully saved and then of course we can use res Jes on here in order to send back that updated subscriber and if we have an error we can set the status here equal to 400 because again if the user is pass in like a name that's not acceptable or subscribed to channel that's not acceptable that's their fault and not ours so we want to make sure we send a 400 error instead of a 500 and we want to send in a message which is just going to be error message so now we can actually try testing that but before we do that you can see we get an error and it says a weight is only valid in async functions so we need to just make sure that this is an asynchronous function and now everything is green which is perfect we can come in here let's just copy this delete for now put in the 3 hashtags and we can just say here we want to do a patch and we want to patch this user we want to send application JSON as our content type just like here and let's say we want to change the name so we're going to set the name here to new name and now if we actually send this request you'll see that it says it cannot find the subscriber with this ID and that's because this ID no longer exists so let's get a new ik new ID from our currently existing subscriber you see their name is amazing person so we'll copy that ID paste it down here in our patch and we'll send that request and you see we get back a new object here which is the updated object and it has that new name and now if we query all of our subscribers you see this subscriber now has the name of new name and that's it the entire REST API is complete if you want to go deeper into nodejs and Express make sure to check out my completely free full stack course on YouTube which is linked over here also subscribe to the channel to not miss any more videos like this thank you all very much for watching and have a good day
Info
Channel: Web Dev Simplified
Views: 298,133
Rating: 4.9481511 out of 5
Keywords: webdevsimplified, nodejs api, node js api, express api, nodejs express api, node js express api, node js mongodb express, node js mongodb, node js mongodb api, node js tutorial, node js mongodb tutorial, node js api tutorial, node js express tutorial, node js express api tutorial, api tutorial, api tutorial javascript, js api, js api tutorial, node js, rest api, node js rest, node js rest api, node rest api, rest api tutorial, rest api javascript, rest api js, restful
Id: fgTGADljAeg
Channel Id: undefined
Length: 28min 55sec (1735 seconds)
Published: Tue May 14 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.