Skip to main content
Loading Explore guides…
Express.js REST API · Acedra
Home
Explore
Computer Science
Express.js REST API
Sign in to save
Chat
If YouTube asks you to sign in, open the video on YouTube.
Watch on YouTube
Reload player
Transcript
66 segments
Copy
Hide video
0:05
hello everybody and welcome back to the channel in this video we're gonna learn how to build a rest api with express js now for this crash course you do not need to know any express of course but i do expect you to know what a restful api is because that's what we are building with express so let's just get right into it so the first thing we need to do is of course create a directory where our express application is going to live so let's open up our terminal i'm just going to
0:36
go ahead and clear everything and i am going to move into my desktop and what we're going to be building is simply a to do application so we're going to have multiple routes so we can fetch our to-do's we can fetch one specific to-do we can update it to do we can add a to-do as well as delete a to-do so let's go here and let's create a directory i'm going to do that with uh mikter and then i'm going to say to-do's app i'm going to move into to-do's app and i'm going to do code dot to open up my
1:10
application in vs code if you don't have this command set up that is not a problem you can just simply open up your vs code instance and uh and open up your new application so i'm going to open up the new integrated terminal and to do this of course we need to have node.js installed being that well this is a node restful api because express is a framework that is built on top of node so we need to initialize a node application and we can do that with npm init-y let's go ahead and do that
1:43
and now over here you can see we have our package.json file now in here of course what we need to do is we'll install express and express is really the only dependency that we need to build this rest api so let's do npm install and then express very very simple and this might take maybe 10 seconds i don't presume it will take too long and it didn't take too long awesome so you can see here we have express so let's actually go ahead and create our express server now where is that
2:16
going to live well it's going to live inside of the index.js file you can call this whatever it is that you want many people call it main.js file but i think many more call it index.js file so that's what we're that's what i'm going to be sticking with so the first thing we need to do is get express from well the express express package that we downloaded so over here we have express now let me just zoom in here a little bit now what we need to do is well create a new express app
2:51
now to do that we can say const app this is going to be our express app and we can invoke express so that is what we are going to be doing so we're going to invoke express and now the last thing we need to do is listen on a specific port so let's go ahead here and let's do app dot listen and we're gonna go ahead and listen on port 3000 so that's the first parameter the second parameter is an uh is a callback where we can console.log that we are now listening on
3:29
port 3000 let's get rid of this rubber rubbish okay cool so that is our application we are getting very very very close i mean we have pretty much built out our express app now what we need to do is run our application so to do this let's open up our terminal and in here all we have to do is execute node index and what that will do is now we are listening on port 3000 awesome so this is terrific now if we were to actually go to port 3000 let's let's get rid of the canva for now
4:07
and let's go to localhost 3000 what we see is this right now we do not have a route at the moment so we really can't fetch any data so the way that express works and the way that any restful api works is that we're exposing routes so we expose route after route after route so we have a route for getting to-do's we have a route for getting one to do we have a route for a bunch of different things so we need to create those routes of course and let's actually begin well right now let's
4:42
create our very first route where we can get all of the to do's so to define a route we use app and then we say dot get now this right here is the verb so this is the verb so what we want to do is we want to get data so we're going to define that this is a get route this is just a verb we can have the exact same functionality with any different verbs and we're going to encounter all of the verbs as you can see here we have get and then there should be something like
5:16
patch there's something like put there's post but because this route handler is responsible for getting data it is best practice and you should probably use the get verb okay so the first thing that we have to do is define we have to define well the path of this route so it's going to be localhost 3000 slash what well we're going to say slash to do's because we want to get all the to-do's the second uh parameter is a callback and this callback also takes in two parameters
5:54
the request and the response so what is the request well when we hit this endpoint we are making a request to this endpoint and within that request you can have multiple different things you can append some data within the request you can have some data within the parameters so this right here is the request and sometimes we're going to need to parse the request in order to uh in order to do the functionality that we want to and over here this is the response so this is ultimately what we do
6:29
inside of this route handler and what we send back so this is a response what we want to send back to the user after they made a request so that is what these two things are and they're usually not written in full because they're too long so they're just abbreviated rec and res okay so what we want to do here what do what do we want to do here well we want to respond with an array of to-do's now in here we can have our logic we can go fetch our data with an orm but again
7:02
just for simplicity's sake let's create a to do's array right over here and simply all we want to do is respond we want to respond back with those who do's now we could do a res.send or because at the end of the day we want to send back json data we can do res.json and send back those to-do's and we can actually end the call by having a return very very simple now we're gonna have to uh close the server and run it again in order to actually see the changes now in order to
7:39
set up hot reload and this is what i am going to do i highly encourage you to run let me just clear here inside of your terminal do an npm install nodemon and then dash g i already installed it but what this will allow us to do is hot reload our node application and if you're on with mac or linux you might have to prepend sudo and then enter your credentials so once you have that installed globally let's go back here what we can do is open up our package.json file and inside
8:16
of our package.json file well not in the dependencies inside of the scripts we can write a dev script and what we want to execute in dev is nodemon index.js so now let's open up our terminal again and now let's do npm run dev so you can see here now we're running on localhost 3000 i don't think we'll need our terminal much more okay cool so now let's actually go ahead and test this route now any get requests we can actually test in the browser itself so we can do now localhost 3000 slash to do's
9:00
and if we were to do that you can see here that we get back an array we can also test out our stuff in something called postman let me zoom in here a little bit i think this is good so we can use postman and what this does is it simulates a client making a bunch of requests and you can see here these are the different verbs that we can utilize so we can have get post put patch delete and there's actually much much more and we're not going to look into these ones honestly i don't
9:28
even know what some of these do so we want to make a request to localhost 3000 so if you don't have postman you can go ahead and install it by the way it's not a very difficult installation and you could use either use this or something like insomnia but once you have it go over here and what i want you to do is create a new thing a new collection for your brand new app you can call this to do or whatever it is that you want but i already have one over here for express
10:03
so over here now what we can do is we can right click on this and add a new request once you add a new request you can see here that we have this new request i already have one pre-built a get request that gets all of the to-do's and this is making a request to local host colon 3000 slash to dose so if we were to make this request and send it off you can see here let me zoom in a little bit more actually you can see here that we got back a wonderful array that's it very simple we get back this
10:35
array okay cool that is awesome so now what we need is the ability to actually add to do's so let's do something like app dot post and then to do's and so this is a brand new verb that we are going to be utilizing because this is something this is def this verb is used when we are adding data this is a very common uh verb that is used when adding data so post request so over here we have the wreck and the rest so the request and the response now in this case what we need to do
11:16
is we need to well know well what kind of data or or what the to do is so within the request we actually have to pass in what the to do is so within the request we have to pass in the to do itself and we actually do that inside of the request body so just to quickly illustrate this i have another request here a post request of slash to do and if i want to pass data in i would pass that in inside of the request body so let's actually go over here so to reach this
11:57
place what you need to do is to go to body then in here make sure that you're on json and over here well what is the title of the to-do well i can change it to a proper to do maybe clean the house the house so that is going to be the title of the to-do and this is going to be passed along within the request all right awesome so that is terrific but before we do anything what we need to do is tell express that we need to parse the json because over here we're passing the body as json
12:31
so what we're going to need to do and this is something that we'll talk about a little bit later is do something like app.use and this is known as a middleware and we'll talk about that in great detail a little bit later do not worry but then we're going to need to do something like parse dot or app.use and then express json and what this simply does is say that hey you can utilize json within your application your express application but we'll talk about middleware a little bit later but for
13:00
now just understand that this is a very important step in order to get this data from the request okay cool so here what we want to do is first we want to get the title of the to-do how do we get that well we go to the request dot body and then dot title so we get that from the request.body.title now another way we can do it is simply destructure out the title from the request dot body so that's the exact same thing now what we want to do is assemble the new to do so
13:35
what we want to supply it with is an id that is a string and we also want to supply it with the title which is well defined over here and we want to supply it with a completed status that initially is false okay now what we want to simply do is uh go ahead and inside of the to do's array i want to push that to do that new constructed to do and then to respond what i want to do is respond with the new to do that we added this is something that i just want to do i want
14:10
to respond with the new to do that i added we could also respond with a success response or we can respond with the array itself but i think for most post requests that add data you respond with the record that you added okay now one thing that we need to address here is this over here well this is just a string we need a unique identifier for this what we can actually utilize is uuids so let's go here and what we can do is install a package called uuid and what this will allow us to do
14:45
what this will allow us to do is create random ids or string ids for each particular record so over here what we can say is we want uuid and we want to get that from well uuid now in this case i want a specific type of uuid known as the v4 uuid you don't have to know what that means but it's just it's just it has different algorithm that creates different strings but at the end of the day it's all unique strings so what we can just say is we can destructure out v4
15:24
and what we can also do is say as uuid or i guess that doesn't work here i guess it only works in typescript my apologies so we could just say v4 here and now over here what we can do is say v4 and invoke it and that's just going to create a brand new random string okay so let's actually test this out so this is a post request so let's go to postman and over here what we can do is make this request and let's go to the body seems like the request failed for some odd reason
16:04
how come i can't go to the body this is kind of strange
16:12
oh there we go now we can open the body a little bit so it seems like there is a bit of a problem and okay i see the problem actually the problem is is i have to have to do so this is a pulse request to to do is app.to do is not to do let's make this request again and now we have another error that i'm a little bit flustered about okay another problem we have to prepend the slash so save that and now i hope this is the one there we go so you can see we have added
16:46
this brand new to do and if we actually went and we made that get request you can see here that we have the array of that specific to do if i were to add another to-do let's say pet the cat made that request you can see we added this new record with a brand new uuid and we can go ahead and send this off and now we have an array of two um two uh uh to-do's okay cool and they both have unique ids all right so this is terrific now what we need to do is well let's write the
17:24
logic for getting one to do maybe we want to get just one to do so as you can imagine we are going to utilize an app.get so this is app.get we're going to do slash to do's but how do we get just one to do well we need to uniquely identify what that to do is and what better way to you can uniquely identify what the to do is than the id itself because well that's just a unique identifier so what we need to do is somehow pass the id uh inside of the rack now you might be thinking okay the best
18:04
way is to maybe pass it in the body so we can have something like um id and then over here whatever the id is and we can parse it and that would work but the body is usually reserved for actual data that we actually want to utilize inside of the tb here what we want to do is simply just fetch some data and actually the better approach is to do something like this is to change the route handler if i can get this thing at this element is to do something like this
18:37
so have to do's and then slash the id of the to-do we want to get that right there is a better approach the thing is is this is always going to be dynamic it's going to be changing depending on the id of the to-do we want to get so how do we specify that here in this handler well we can specify that by saying colon and then whatever that dynamic thing is called in this case we're going to say id and so this can be anything and we're going to store that thing in the id parameter
19:11
okay so now let's do the rack carets and now we need to get this id from the request so what we can say is const id we can destructure out the id from the request params so we can destructure the id from the request params awesome and now what we want to do is we want to get we want to find that to do with this id so what we can say is to do's dot find and then we can say something like well we want to iterate through every single element and what we want to do is we want to
19:48
find the to do where its id is equal to the id that we have inside of our params and then very simply what we want to do is well return that to do but of course we need to do a res dot json and then return it very simple very very simple okay so one thing i do want to note if i were to as you can see here we have two elements but if i were to send this request or actually let's get rid of this for now if i were to send this request again to get our array it's going to be an empty array
20:21
and the reason for this is because well we're storing this in a variable and every single time we make a change and save it we're restarting our server unless the to-do's is going to go back to an empty array if we had if you wanted to persist the data of course we would have to store it in a database but just for simplicity's sake i want to teach you express we're going to keep it as an empty array okay cool now let's actually go ahead and let's let's create a to-do let's add
20:48
a new to-do pet the cat and then let's grab this id and now i want to get a specific to-do so let's make this first make this request and let's have this id and we should get back an object that contains that specific to do awesome so what's the next step well the next probable step is to have the ability to update the to do so we need the ability to toggle whether this is true or false the completed status so let's go here and for updating things typically what we're
21:28
going to utilize is put so the verb put and over here we're going to say to do's so slash to do's and then we have to figure out what to do we want to update well in this case we can use the same thing over here we can have the id right in there so we can have the id in there and that's really all the information that we need so we have the rec res and then what we can do is we can get the id from the params and now what we want to do is we want to find the element in our array that has
22:08
that id and then just change it so what we can actually do is get the index of that specific element that's actually a really good idea you can do to do's dot find and then there's find index and this all it does is as soon as there's a condition that is met it is going to return the index for that element and then over here what we could say is to do and then we're going to say to do dot id is equal to the id that we have specified so that's going to be the index of that element
22:42
and then what we can simply do is we'll to do's of that index and then dot completed we're going to say that's equal to the to-do index.completed but the opposite of this because this is going to return a boolean value so this is true it's going to go back to false and if it's false it's going to go back to true and then simply put what we can do is a return res dot json and to do's dot index so we're in this case we're returning the element that we have updated
23:14
so let's give this a go again this should probably work so let's add in you to do pet the cats or pet the cats let's add this to do and now let's also add another to-do just for the sake of seeing things let's do clean the room and now if you were to get our to-do's you can see we get an array of these to do's both of them are false let's say we have cleaned the room already so what we can do now is make a put request we can say slash to do's slash this id update that and you can see now it is
23:53
true and if you were to make this request again you can see now that this is true now if i were to make this across again it's going to toggle it back to false and over here it will be back to false all right so the last route handler that i think is important is deleting we want to delete our to-do's so as you can imagine there's another verb that we can utilize called dot delete so in this case we of course have to identify which to do we want to delete so let's do the same thing to do colon
24:28
id we're going to do rec res and then in here let's copy this we want to get the id from the request and then what we want to do is what we want to delete that to do so let's actually filter out all of the or let's filter out the to do that matches this condition so very simply what we can say is new to do's is equal to and or or sorry actually what we can do is we can say const or we can say to do's is equal to and we can actually make this turn this into a let instead of a const so you can
25:10
say to do's is equal to to do's dot filter and then we can filter for each to do and what we want to do is return all of the to do's that have ids that are not the one that we have passed in in our parameter very simple and then for this what we could do is very simply just return the to-do list
25:37
all right let's try this again now so let's add this let's add pet to cat
25:47
let's make this request over here you can see that we have gotten this and let's say we want to just completely delete pet the cat so let's make a new request here this is going to have the delete verb and let's just copy this i'm going to copy that in there and what we want to do is we want this id and let's also we can also rename it delete to do save that and then in here what we can say is we want to delete this to do and send this off send this request now we get an array of well
26:29
the to do is with that deleted to do but to double check we can also make this request and you can see that that to do is completely gone and that's pretty much it that's really all you have to know for express because express is just a way for creating routes now one thing is that this is kind of getting a little bit messy so how can i make this well less messy so one thing that we can do instead of having all our routes live in one file we can actually group them together in multiple files
27:02
so for example we can have multiple routes over here all these routes have to do within them but we can have other routes like i don't know app.get and then this is like something like slash animals for some reason in our application we have a to-do application as well as an animals application what we can do is we can group all of these to-do's routes in one file and then group all of the animal routes in another so that's just a very simple thing that we can actually do
27:32
and let's actually do that right now so what we can do here is create a routes directory so we're going to create a routes directory and in here we're going to say that inside of this file we have this to do.js file and inside of here we're going to have all of our to do routes so let's go here and let's just cut everything out we're going to completely cut everything out we're going to paste it right in there so we're gonna paste that right in there and instead of using app we're gonna use
28:05
something else called router so we're gonna do get that from const and then we're gonna get router from where it's going to equal require express and then dot router we're going to go ahead and invoke this what this is going to do is allow us to create these routes without the app so we're gonna go here and instead of app we're gonna say router router router router and then router and then at the very end we're gonna do a modules dot exports and we're going to go ahead and export that router
28:49
and so now what we can do in here and of course what we need to do is get this and paste that in there because we're utilizing the uuid in here to actually use these routes what we can do is something similar to what we did here we can say app.use and then here the first thing that we can specify is a string of the uh of a common path that every single route inside of this handler will utilize i'll talk about that a little bit later but then we can specify the file where the routers live
29:25
in this case is going to be slash routes slash to do's so if we were to save this and we need to actually get the to do's and put it in here as well so you can save that and save this you can see here drastically simplified our file but we can still make the same requests so you can see here we get an array of nothing but we can of course add a to do we can get it to do we can also update it to do and then we can also delete the to do all right awesome awesome alright so this is terrific but
30:09
okay but what is this string that i was talking about this this uh where is it this string right here well this is going to be a common path that is going to exist on every single route inside of this file now let's actually go here and we can see that there is a comment path slash to do's for every single route we have slash to do's so what we can actually do is instead of defining that here in the routes what we can say is every single route handler will be slash to do's
30:42
and then inside of here we can actually get rid of the to do's because it's going to be slash to do's because if we left the slash to do so it's going to be slash to do slash to do so just to prove that to you right now if i go here and make this request again we don't have it so because the first path is slash to do's but we're also saying that we want another slash to use and if you want to make this request again we see it but obviously this is not something that we want
31:08
so what we can do is we can get rid of this we can get rid of this you can get rid of this you can get rid of this and we can get rid of this and anytime we want to actually uh uh uh append something to the route we can just simply do something like this so we can so we know it's gonna be slash to do slash whatever it is so if you were to save this and we were to make this request again it is exactly the same all right awesome so the last thing i want to quickly very
31:40
quickly discuss is middleware and middleware is actually what we're doing here with the app.use so middleware is something that runs before it actually reaches the route handler so first of all we make the request it is intercepted by middleware the middleware is going to be doing something and then it's going to send that off to the router so one very common use case for middleware is actually adding authentication so when you make a request the middleware gets it it checks if
32:15
you're authenticated and you're authorized to make that request if you're not it's going to throw an error and it's never going to reach that route handler but if you are then what it's going to do is just going to forward it to forward request to the route handler and so that is middleware and we actually utilize middleware with app.use so over here the express.json what it's doing is before we're getting our request to our rep handlers we're parsing to the json
32:46
so that's exactly what we're doing here with app.use so let's add a very simple authentication middleware it's not going to be cumbersome or difficult at all it's going to be very very easy so we're going to go here and we're going to add middleware let's create a middleware directory and in here we're going to create a check auth.js file so we're going to create a check auth.js file now inside of here we're going to have well our middleware that's going to check if we're authenticated
33:21
and to check if we're authenticated we're going to do something extremely simple we're just going to check uh if you have a boo a true or false value in the header the the the request header so another way we can actually store data is in the request header so we can supply it with key key value pairs and over here we're going to look for the authenticated status so authenticated and over here the value if it's if it's yes we're gonna say awesome you can move forward but if it's no
34:00
then no you cannot move forward we're gonna throw a forbidden error very simple that's all we're going to do so to create middleware all we have to do is create a function and so what we're going to do is we're going to go ahead and right away export that function out and this is similarly going to take in the request the response and then all we're gonna do is we need to of course get the uh the the uh this this value from the header remember the key is authenticated
34:33
so what we can do here is we can say const authenticated
34:42
authenticated is equal to rec dot header and then we can invoke this and pass in the key which is authenticated in this case let's pass that in there okay and so simply if authenticated triple equals yes then what we're going to do is we want to actually just move on to the actual route handler because remember this is going to live in the middle between the request and the actual route so to say that we want to move on there's actually a second or third parameter that we can utilize called next
35:21
and so simply what we can do is just invoke next and that's either going to move on to the next middleware or the route handler itself whatever is next down the line all right and now else what we can do is else well you're not authenticated at this point so what we want to do is we want to do arrest.json and we want to say message we can say not authenticated and what we also want to do is not return a 200 response but return another meaningful response so
35:56
typically when something is forbidden we can say that this is a 400 response so to change the response we can say dot status and then 403 and then append the dot json so let's save this and now what we want to do is actually utilize this middleware within these routes themselves this is also a very simple process so what we can do is over here we can add in between the path and the actual callback that has a route we can add as many middleware as we want in this case i want to add the check
36:35
check off middleware so you check off middleware and you can notice that i actually automatically appended it or imported it so now if you were to save this and let's go to our header we're going to say no you can see here that we're not authorized and there is a 403 forbidden if i were to change this to yes now we are actually authorized to do this and of course we could do this for every single for every single path here let's just have a check auth for every single one
37:13
because we want to be authenticated for every single one and this is obviously not the authenticated system that would happen in real life but it's just an example all right and that's pretty much it that's really all you have to know for uh express it's really simple i love the framework um and you can really utilize it to build very uh important and powerful rest apis
Here to help you learn
Sign in to keep a private conversation with your course tutor.
Ask me anything about the material…
Sign in to chat