How to build a REST API with Node js & Express

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

I've seen this tutorial everywhere, why people keep making this ? Are they running out of creativity ?

You know what are we lack of ? Building RESTful API with Event driven design pattern and inversion of control !!

👍︎︎ 15 👤︎︎ u/StupidRandomGuy 📅︎︎ Mar 23 2018 🗫︎ replies

i love this dood

👍︎︎ 3 👤︎︎ u/etuncoz 📅︎︎ Mar 23 2018 🗫︎ replies
Captions
[Music] so earlier in section 2 where we talked about nodes module system you learned about this HTTP module we use this to create a web server that listens on port 3000 and responds to requests for these endpoints so the route or such API slash courses now while this approach is perfectly fine it's not ideal for building a complex application because in a large complex application we might have various endpoints and we don't want to hard-code all these if statements in this function so in this section we're going to look at Express which is a fast and lightweight framework for building web applications so next we're gonna look at restful services let's start the section by a brief introduction to restful services also called restful api s-- if you already know what rest is all about feel free to skip this video so earlier at the beginning of the course I introduced you to the client-server architecture so most if not all applications we use these days follow this architecture the app itself is the client or the front-end part under the hood it needs to talk to a server or the back-end to get or save the data this communication happens using the HTTP protocol the same protocol that powers our web so on the server we expose a bunch of services that are accessible via the HTTP protocol the client can then directly call the services by sending HTTP requests now this is where rest comes into the picture rest is short for representational state transfer and I know it probably doesn't make any sense to you because it was introduced by PhD student as part of his thesis but the theory aside rest is basically a convention for building these HTTP services so we use simple HTTP protocol principles to provide support to create read update and delete data we refer to these operations all together as crud operations now let's explore this convention using a real world example let's say we have a company called bitly for renting out movies we have a client app where we manage the list of our customers on the server we should expose a service at an endpoint like this so vid lucam / api / customers so the client can send HTTP requests to this endpoint to talk to our service now a few things about this endpoint you need to know first of all the address can start with HTTP or HTTPS that depends on the application and its requirements if you want the data to be exchanged on a secure Channel you would use HTTPS after that we have the domain of the application next we have slash API this is not compulsory but you see a lot of companies follow this convention to expose their restful services they include the word API somewhere in the address it can't be after the domain or it can be a sub domain like API that vidlink aam there is no hard and fast rule after that we have slash customers which refers to the collection of customers in our application in the rest world you refer to this part as a resource we can expose our resources such as customers movies rentals on various endpoints so this is our endpoint to work with the customers all the operations around customers such as creating a customer or updating a customer would be done by sending an HTTP request to this endpoint the type of the HTTP request determines the kind of the operation so every HTTP request has what we call a verb or method that determines its type or intention here are the standard HTTP methods we have yet for getting data post or creating data put for updating data and delayed for deleting data now let's explore each of these using our customers example to get the list of all customers we should send an HTTP GET request to this address note the full name customers here it indicates a list of customers so when we send an HTTP GET request to this endpoint our service should send us something like this so we have an array of customer objects if you want a single customer we should include the idea of that customer in the address then our server would respond with a customer object like this now to update a customer we should send an HTTP put request to this endpoint and note that again here we're specifying the idea of the customer to be updated but also we should include the customer object in the body of the request so this is a complete representation of the customer object with updated properties we send this to the server and the server updates the customer with the given ID according to these values similarly to delete a customer we should send an HTTP delete request to this endpoint but here we don't need to include the customer object in the body of the request because all we need to delete a customer is an ID and finally to create a customer we need to send an HTTP POST request to this endpoint note that here because we're adding a new customer you're not dealing with a specific customer so we don't have the ID in the address you're working with the collection of customers so we're posting a new customer to this collector and that's why we should include the customer object in the body of the request the server gets this object and creates the customer for us so this is the restful convention we expose our resources such as customers using a simple meaningful address and support various operations around them such as creating or updating them using standard HTTP methods so throughout this section you're going to learn how to use the Express framework to build a restful service from managing the list of customers however in this section we won't be doing any database work because that will bring in additional complexity our focus will be purely on building HTTP services and we will use a simple array in memory to keep the list of our customers later in the course we'll look at using a database so here's the code that we wrote in the section about node core where I introduce you to the HTTP module so we can see with HTTP module we can create a web server here we have a callback function that takes two parameters request and response and with this request object we can check the URL of the incoming request so with this we can define various routes for our application so if you have a request for let's say slash API slash courses this is how we're going to respond to the client now while this approach certainly works it's not very maintainable because as we define more routes for our application we need to add more if blocks in this callback function so that's when a framework comes into the picture a framework gives our application a proper structure so we can easily add more routes while keeping our application code maintainable now there are various frameworks out there for building web applications and web servers on top of note the most popular one is Express so if you head over to NPM JSE org or NPM J is calm here let's search for Express so the current version is version 4.2 16.2 let's have a quick look here so here on the right side look at the statistics there have been over 700,000 downloads in the last day and over 15 million downloads in the last month it's a very popular framework it's also very fast lightweight and perfectly documented so now back in the terminal let's create a new folder for this section so I'm gonna call this Express demo now let's go inside this folder run NPM init with yes flag so now we have a package JSON file and finally we can install Express beautiful in the next lecture I'm gonna show you how to build your first web server using Express all right now in vs code let's add a new file index the jas we could also call it app to J's it doesn't really matter so in this file first we want to load the Express module so we use our require function give it the name of our module which is Express now this returns a function we call that Express okay now we need to call this function like this and as you can see this returns an object of type Express by convention we call this object app so we store the result in a constant called app so this represents our application now this app object has a bunch of useful methods we have methods like get post put and delete all these methods correspond to HTTP verbs or HTTP methods that I told you about earlier in this section so if you want to handle an HTTP POST request to an endpoint you would use app that post now in this lecture we just want to use app but yet we want to implement a couple of endpoints that respond to an HTTP GET request so this method takes two arguments the first argument is the pass or the URL so here I'm going to use slash to represent the route of the website now the second argument is a callback function this is the function that will be called when we have an HTTP GET request to this endpoint okay so this callback function shall have two arguments request and response so this goes to a code block now this request object has a bunch of useful properties that gives us information about the incoming request if you want to learn about all these properties it's best to look at the Express documentation because in this course we're going to use only a handful of these properties so head over to Express Jas comm on the top look at API reference version 4 now here you can see the request object and below that you can see all the properties that are available to you you have base URL we have body to read the body of the request cookies fresh host name IP method original URL parameters and so on so back to our code when we get an HTTP GET request to the root of our website you're gonna respond with a hello world message so response dots and hello world so this is how we define a route we specify the path or the URL and a callback function which is also called a route handler now finally we need to listen on a given point so we call app that listen we give it a port number like 3,000 and optionally we can pass a function that will be called when the application starts listening on the given port so once again we use the arrow function syntax to display something on the console so console dot log listening on port 3,000 now back in the terminal note index j s okay we're listening on port 3000 now let's switch over to Chrome and go to localhost port 3000 so here's our hello word message now let's define another route so once again we're gonna call app that get now this one is going to be slash API slash courses once again we pass a function with two arguments then it's request and response and this goes to a code block now in a real world scenario here you want to get the list of courses from the database and return them but as I told you before in this section our focus is purely on building these endpoints you're not gonna do any database work so I'm gonna simply return an array of numbers so response that's and it passed an array of three numbers in the future we can replace these numbers with actual course objects so save now back in the terminal we have to stop this process and started the game so press ctrl + C okay one more time node index J is now back in Chrome let's head over to slash API slash courses look we have an array of three numbers beautiful so this is what I want you to pay attention to here in this implementation we don't have those eve blocks we define new routes by calling app that yet and with this structure as our application grows we can move some of these routes to different files for example we can move all the route related to courses to a separate file like courses that Jas so Express gives our application is skeleton is structure so far you have noticed that every time we make a change to this code you have to go back in the terminal and stop this process and started the game this is very tedious so I'm gonna show you a better way we're gonna install a note package called note Mon which is short for node monitor so in the terminal and p.m. install - G because we want to install this globally so we can run it anywhere and the name of the package is node Mon now as I told you before if you're on Mac and you haven't configured the permissions properly in it put sudo at the front all right no one is installed so with this instead of running our application using node we use node Mon okay now you can see node Mon is watching all the files in this folder any files with any extensions so if we come back here and make a simple change and then save the file now look in the terminal node Hmong restarted our application or our process due to changes so we don't have to do this manually anymore now back in the browser if you send a request to the root of the website we can see our new message displayed here now one thing we need to improve in this code is this hard-coded value for the port so we have used 3000 as an arbitrary number while this may work on your development machine it's unlikely that this is gonna work in a production environment because when you deploy this application to a hosting environment the port is dynamically assigned by the hosting environment so we can't rely on 3000 to be available so the way to fix this is by using an environment variable so typically in hosting environments for node applications we have this environment variable called port an environment variable is basically a variable that is part of the environment in which a process runs its value is set outside this application I'm gonna show you how that works in a second so in this application we need to read the value of this port environment variable and the way we do that is by using the process object so we have this global object called process this object has a property called M which is short for environment variables and after that we add the name of our environment variable in this case port so if this is set we're gonna use this otherwise we're gonna use 3000 now we can store the result in a constant called port okay let's delete this and finally we need to replace 3000 with port and also change our message accordingly so I'm going to replace a single coat with backtick so we can use a template string and here we're gonna replace 3000 with a dynamic value so I'm here at dollar sign curly braces and then add our constant in this case port okay now back in the terminal let's run this application using node maaan so on this machine you can see I don't have an environment variable called port that's why 3000 is used as the port for this web server now I'm going to set an environment variable so let's stop this process on Mac we can set an environment variable by executing the export command if you're on Windows you should use set so export or set now we add the name of the environment variable in this case port and set its value I'm going to use 5,000 so now we have this environment variable called port with the value of 5,000 with this when we run this application node man you can see that now we are listening on port 5000 so this is the proper way to assign a port to your node applications you should attempt to read the value of an environment variable called port if there is a value you should use that otherwise use an arbitrary number for your development machine you all right so currently we have a route for getting the list of courses now in this lecture I'm going to show you how to create a route to get a single course so earlier in the section where I talked about restful services you learn that in order to get a single course we should include the idea of the course and the URL so our endpoint should be like this slash API slash courses slash one assuming that one is the idea of the course so let's see how we can implement a route like this so app that get we add the path that is slash API slash courses and here we need to define a parameter so we add : and ID so idea is the name of our parameter here you could use anything it doesn't have to be ID it could be course ID but ID is shorter and more conventional now we had our route handler function so request and response goes to now in order to read this parameter we use request dot params dot ID so for now let's just send this to the client so resource let's send okay back in the browser now let's head over to slash API is that courses slash one so you can see we successfully read the value of this parameter also it is possible to have multiple parameters in a route for example imagine you're building a service for powering a block so we could have a route like this posts here month so we have two parameters and with this we can get all the posts for the given month and the given here now we can read these parameters just like before so requested params that year or a month for this demo let me show you this requested params object so let's delete this save back in the browser now let's head over to API posts 2018 and one so this is our request params object we have two properties year and month and their name based on a route parameters we express we can also get Kariya string parameters these are parameters that we add in the URL after question mark for example we can get all the posts in January 2018 and sort them by their name so we add a question mark sort by set this to name this is a query string parameter we use query string parameters to provide additional data to our back-end services so we use route parameters for essential or required values whereas we use query string parameters for anything that is optional now let me show you how to read query parameters so I can view scope instead of requested params we use request dot query save back in Chrome and this is what we get so query parameters are stored in an object with a bunch of key value pairs hi guys thank you for watching my Noah tutorial I wanted to let you know that this tutorial is the first hour of my complete note course where you will learn how to build a real restful api using node Express and MongoDB all of that recorded with the latest version of node and modern JavaScript so you will learn new and modern ways of building applications with node unlike other courses that only show you simple the only examples like how to build a to-do app we're gonna work on a real-world project a restful api for a video rental application if you have taken any of my courses you know i don't waste your time by explaining the obvious like what a code editor or command prompt is we're gonna get straight to the business and as part of this i'll be touching on various important topics that you need to understand really well including working with node package manager or npm asynchronous javascript including callbacks promises async and await implementing crud operations data validations authentication and authorization using JSON web tokens including role management handling and login errors unit and integration testing test-driven development so you will see I will build a feature from A to Z using test-driven development or TDD and finally we'll deploy this application to the cloud throughout the course I will share with you lots of clean coding and refactoring techniques security best practices useful libraries to use as part of your development common mistakes that many note developers make and much much more the course is currently 14 hours long and I'm planning to add more content to it in the future you can watch this course as many times as you want and if you watch it to the end you will get a certificate of completion that we can add to your resume so if you're serious about adding no to your resume I highly encourage you to enroll in the course and don't waste your time jumping from one tutorial to another so click on the link in the video description to enrol I hope to see you in the course alright now let's implement a new endpoint to get a single course from the server so first of all let's change this back to courses and add the ID parameter here okay now on the top let's define an array called courses so constant courses we set this to an array and in this array we're going to have three course objects so each object should have a couple of properties ID and name and of course we can have more but for simplicity I'm just gonna stick to two properties here okay now let's duplicate this line and change the IDs as well as the name two and three so we have two endpoints want to get all the courses and the other two get a single course right in the first one we're gonna return our courses are a-okay right in the second one we should write some logic to look for the course with the given ID so let me delete this first we're gonna call courses that find this is a method that is available on every array in JavaScript as an argument to this method we need to pass a function this function will be used to find a course that matches a given criteria so we use the arrow function syntax C goes to and here we write some logic that returns a boolean value this boolean value determines if this course is the one we're looking for or not so see that ID should equal request that params dot ID however this requested prams that ID returns a string so in order for this comparison to work properly we need to parse this string into an integer so we call parse int which is one of the global functions available in JavaScript and then get the result and store it and a constant called course now you might be asking why I didn't use var here well that would be perfectly fine and that's how most JavaScript code out there is written but going forward it's best to drop var and either use let or Const we use let if you want to define a variable that we can reset later and we use Const if you want to define a constant in this case I don't want to reset the course later in this function but again that's perfectly fine to use let here as well it's just personal preference so we get the course object now if this course doesn't have a value in other words if we don't find a course for the given ID by convention we should return a response with the HTTP status code of 404 that means object not found so this is one of the conventions of restful api so if the client asks for a resource but that resource does not exist on the server we should return a response with the status code of 404 so here we call response dot status 404 and optionally we can send a message to the client as well so send the course with the given ID was not found okay now otherwise if we do have a course with that ID we're simply going to return that to the client so response that's and course now let's test this so back in the browser let's head over to slash API slash courses slash one so we have a course with the ID one and that's why we get this JSON object in the response however if I change this to ten we can this message the course with the given ID was not found and to ensure that the status code of this response is 404 we can open up Chrome developer tools so right click here go to inspect and then on the network tab make sure you don't have a filter here so select all and then refresh the page by pressing ctrl R on Windows or command R on Mac so here's a request that we sent to the server you can see the status is 404 which means not found so far we have created two routes that respond to HTTP GET requests and we use this route to get all the courses as well as a single course in this lecture I'm going to teach you how to respond to HTTP POST requests so we use an HTTP POST request to create a new course so app that post instead of the get method we use the post method now similar to the get method we need to specify a path so that should be a slash API slash courses because we're going to post to the collection of courses that's why we use the plural name here then we add our route handler so request and response goes to code block now I'm going to add some line break here so I can easily see this video all right so in this route handler we need to read the course object that should be in the body of the request use these properties to create a new course object and then add that course object to our courses array so let's create a new course object constant course again I'm using a constant here because we're not going to reset this course object later so let's set this to a new object now here because we are not working with a database we need to manually assign an ID so ID so we get the number of elements in our courses array so courses dot length and simply add one to it in the future when we work with the database the ID will be assigned by the database next is the name property now we need to read this from the body of the request so request that body that name so here I'm assuming that in the request body we have an object and that object has a name property now in order for this line to work we need to enable parsing of JSON objects in the body of the request because by default this feature is not enabled in express so on the top after we get the app object we need to call app that use and here we call Express dot JSON now this may look a little bit strange or unfamiliar to you but don't worry later in this section we're going to explore this in detail basically what we're doing here is adding a piece of middleware so when we call Express the JSON meta this method returns a piece of middleware and then we call app dot use to use that middleware in the request processing pipeline again we're going to explore that in detail later in the section so back to our new route handler you have a course object next we push it in our array so courses dot push course and finally by convention when we post an object to the server when the server creates a new object or a new resource you should return that object in the body of the response so response that's and course the reason for this is because we are assigning this ID on the server so we need to return this course object to the client because chances are the client needs to know the idea of this new object or this new resource so this is how we handle HTTP POST requests in the next lecture I'm going to show you how to test this endpoint all right to call HTTP services we use a Chrome extension called postman so if you have an installed postman before search for Chrome postman here is postman simply add it to Chrome ok done now you can open this from the apps menu here postman I hear it's asking you to sign up for an account but you don't have to do this there's a link here take me straight to the app alright now on this page we can create a new HTTP request so from this drop-down list we set the type to a post request you put the URL here in this case that's HTTP localhost on my machine I'm using port 3000 to host this application API slash courses now we need to set the body of this request from this list select raw and then JSON so with this we can put a JSON object in the body of the request so let's add an object here and give it a name property so name we set this to new course and then finally send okay if you scroll down you can see the status of the request is 200 which means the request was handled successfully and here's the body of the response so IDs for because now we have four courses in our array and this is the same name that we send to the server so this is how we test HTTP services is in postman now in this implementation we have assumed that there is an object with the name property in the body of the request what if the client forgets to send this property or sends an invalid name perhaps a name that is too short that's where input validation comes into the picture and that's the topic for the next lecture in this lecture I'm going to show you how to do input validation so as a security best practice you should never ever ever trust what the client sends you you should always validate the input so in this particular example because we're dealing with a simple object with only one property that is named we can write some validation logic like this so if requests the body that name doesn't exist or requests that body the name that length is less than 3 then we're gonna return an error to the client the restful convention is to return a response with the HTTP status code or 400 that means bad requests so to do this recall response that status 400 and then we can send an error message in this case we can write a generic error message like name is required and should be minimum three characters in your implementation you may want to differentiate the errors for example if the client didn't send the name property perhaps you would just respond with name is required or if they did send the name but the name was not long enough you could send a different error message and then finally we returned here because we don't want the rest of this function to be executed so this is the basic idea however in a real world application it's more likely that you'll be working with a complex object something more complex than this course object here you don't want to write a complex validation logic like this at the beginning of your route handler so let me introduce you to a new package that makes it really easy for you to validate the input so on Google if you search for NPM joy with I look here is the first link so here you can see joy has been downloaded over to 150,000 times or the past day and over three million times over the past month it's a very popular package also here on this page you can see some sample code and link to your official documentation now let me show you how to replace this validation logic with joy so first back in terminal let's install joy so you can see it at the time of recording this video the latest version is version 13 point 1.0 if you want to make sure that you have the exact same experience as what I'm going to show you in this video then install this exact version so npm install joy at thirteen point one point zero okay now back in the code on the top we need to load this module so require joy get the result and store it in a constant called joy with a capital J because what is returned from this module is a class and as I told you before in JavaScript we use Pascal naming convention to name our classes so the first letter of every word should be uppercase also as a best practice with all your required calls on top of the file this way you can easily see what are the dependencies of this module so this module index module is dependent upon two modules one is joy the other is Express okay so we have this joy class now packing our route handler now with joy first we need to define a schema schema defines the shape of our objects what properties do we have in that object what is the type of each property do we have an email do we have a string what are the minimum or maximum number of characters do we have a number what range should that number be so this is the job of a schema so here first I'm going to define a schema constant schema we set it to an object this is the shape of our course object so here we want to have a name property and we said this to joy dot string so we're telling joyed that this is a string and it should have minimum three characters and it should be required so it has a very fluent API again you can look at the documentation to see all the methods that are available to you so here's our a schema now we call joy that validate and we give it request that body as well as our schema now this validate method returns an object let's store that in a constant called result for this demo I'm gonna log this result on the console so before we go any further let's save this go back to the postman let's create another course now back in the terminal so this is a result object it has two properties error and value only one of these can have a value so in this case because we sent a valid course object we have that object here as the value of the value property and you can see error is not if we send an invalid object value will be null and error will be set let me show you so I can postman let's remove the name property send now back in the terminal okay look so here's the result object this is the error property it's set to an object that has validation error child name fails because name is required so back to a route handler instead of this manual validation logic we can check the value of result that error property so if result that error then we're gonna send a response with status code of 400 and in the body of the response for now we can simply add result an error okay and we don't need this constant along anymore save now back in postman one more time I'm gonna send this empty object now look at the response so this is what we get an object with these properties is joy name details which is an array of error messages so here's the first message name is required now this object is too complex to send to the client perhaps you want to simplify this so back in the code one simple solution is to go to the details array get the first element and then access the message property or instead of using the first element you may want to access all elements in this array get their message property and concatenate them that's entirely up to you so save one more time let's send an invalid request and now we get name is required if we go to our request and add the name property but set it to a string that is only 1 character now we get a different error name length must be at least 3 characters long so you can see joy makes it really easy to validate the input and return proper error messages to the client all right now let's see how we can update a course so let's add a new route handler app we use the put method for updating resources now the path should be slash API slash courses and here we need a route parameter because we're dealing with your specific course so ID now our route handler function request son response goes to a code block alright now here's the logic we need to implement first we need to look up this course with this given ID so look up the course if the course doesn't exist if not existing we need to return 404 that means resource not found otherwise we need to validate the course make sure it's in good shape if invalid we need to return a 400 error which means that request and if you get here that means everything is good so you update the course and return the updated course to the client this is the logic we need to implement so we already have some code that we can reuse here so I'm not going to type everything by hand I'm gonna copy some code from our other route handlers so first we want to look up the course and if it doesn't exist you want to return a 404 error for that I'm gonna go to this other rat handler where we get a single course this is the logic we're interested in so we look up the course and if it doesn't exist we return a 404 error so copy these two lines we're done with the first part the second part is all about validation for that I'm gonna go to our post endpoint so here we need to copy the schema as well as this line for validating the request body using joy and there is a problem with this approach the problem is in this case we have a very simple schema what if you are dealing with a complex object with quite a few properties then or validation logic would be duplicated in two different round handlers so let's just copy the code for now and then we'll come back and refactor it to make it better so copy these few lines and paste it here so we're validating and if it's invalid we need to return a 400 error so I forgot to copy that line here if you have an error in the result we're gonna return it's 400 error okay so let's copy that as well so this is our second part we have this schema we validate and if you have an error we return a 400 error we're done with the second part now the third part so at this point we have a course object we can update its properties so of course that name we said that to request the body the name and of course if we have other properties we'll set them here as well so we're done with opting in the course and finally we need to return the updated course to the client so response that's and course this is how we handle an HTTP put request now I told you that we have duplicated this validation logic so I'm going to extract these few lines into a separate function that we can reuse both in this route handler for handling our HTTP put requests as well as the other one we wrote in the last lecture for creating a course so let's define a function here and call it validate course we give it a course object now in this function we should have the schema as well as this line for validating the course so cut these few lines place it here now instead of validating requested body you're gonna validate the argument that is passed to this method so that would be the course object now finally we can simply return this result to the caller there is no need to define a constant so with this new implementation we have all the validation logic in one place now we can reuse this so here is our put method we define a constant call result and study to validate course and as an argument we pass request dot body now we can make this code a little bit cleaner and shorter by using object destructuring feature and modern JavaScript so look here we get this result object and we're accessing result that error property in two different places since all we are interested in is this error property we can get this using object destructuring so let me duplicate this line and show you how object restructuring works with object is structuring when declaring a variable or a constant we add curly braces and then here we add the property of the target object so in this case the target object that is returned from our validate course method has two properties error and value in this case we just want the error property so we put that between curly braces so this is equivalent to getting result that error one instead of using this notation we use this notation okay and with this we don't have to repeat result that error in two different places we can simply use error okay so this is object destructuring now we don't need this first line anymore and finally before we finish this lecture we need to make one more change in this code so we need to use this new way of validating a course in the route handler for handling our HTTP POST requests so copy this is our handler for creating a new course now we don't need to use this schema here we moved all that logic to our validate course function so all these few lines here for validating the request body and sending the 400 error I'm going to delete this and paste the code that we copied from the other method so we call validate course use object D structure and syntax and if you have an error you return the 400 response to the client now finally let's test our new endpoint for updating a course so back in postman we need to change the type of this HTTP request to put change the URL and add a valid course ID like one here we have a pilot course object with name set to new course so send and we get a 200 response which is successful and here is the updated course so if you open any new tab and send an HTTP GET request to localhost / api / courses now you should see the list of our courses so our first course it's name is up data perfect now let's test the other scenarios what if you send an invalid ID so 10 send the course with the given ID was not found and you can see the response is 404 which means not found and finally what if you send a valid course ID but an invalid course object so I'm gonna remove the name property send now you can see we have a bad request for 400 error and here's error message name is required next I'm gonna show you how to handle HTTP delete requests so out of all the crud operations you have implemented create read and update so in this lecture I'm gonna show you how to respond to HTTP delete requests it's very simple and similar to what we have done so far so here's our app object we call the delete method give it a pass that is slash API slash courses and of course we need a parameter because we're working with a specific course then a raft Handler request our response goes to the code block now here first we need to look up the course the course would be given ID if it doesn't exist then we need to return 404 otherwise we're going to delete it and by convention return the same course the course that was deleted so again I'm gonna borrow some code from our other grant handlers to look up the course and return a 404 error I'm gonna go back for ramp handler for the HTTP put request so these first two lines is for looking up the course and returning a 404 error so copy these two lines back here that is our first part done now to delete a course first we need to find the index of this course in our courses array so courses dot index of course we get the index store it in a constant and then we can use this splice method to remove an object from our courses array so courses dot splice we go to this index and remove one object so this is the delete part and finally we need to return the response to the client so response let's send this course object now let's test this so back in postman let's change put to delete first I want to send an invalid course ID like ten send so we get a 404 error not found with this message perfect now let's delete the first course course with the ID one send so we get the same course object in the response and if we go to our second tab where we have the list of our courses so look we have an HTTP GET request to the send point let's send this one more time okay now look we don't have our first course anymore we only have courses with ID two and three all right before we go any further I realize we have a bug or actually three bugs in this code so look at the handler or responding to put requests to this endpoint if we don't have a course with the given ID we return the 404 error to the client but at this point we should exit this route handler otherwise the rest of this code will be executed so the proper way to implement this round handler is like this so if you don't have this course we return the response and then exit the function or a shorter way to write the same code is to put the return here and then we don't need the code block so we can put everything in one line okay now to make this code cleaner let's use the same technique in case we have an invalid request so we simply return and then we don't need the code lock anymore that's much more elegant you have the same issue in the handler for delete requests so if you don't have a course here we should return immediately the same is true when getting a single course so if we don't have a course with the given ID we return the 404 error and also return from this function immediately now finally let's have a look at the handler for HTTP POST requests here it is again I'm gonna use the same technique to clean up this code so if you have an error we simply return and get rid of the extra noise in the code that's much better all right now it's time for an exercise so from this lecturer we're gonna start building the back-end services for our VIP little acacia as I told you before Whitley is an imaginary service for renting out movies so throughout this course we're going to build the backend of Whitley bit by bit your first task is to create a service from managing the list of genres so each movie as a genre like action horror whatever we should have an endpoint for getting the list of all genres because somewhere in our client applications perhaps we have a drop-down list for the user to select a genre so we need an endpoint to get all the genres we should also be able to create a new genre as well as update or delete an existing one so before going any further I want you to put what you have learned so far in practice so even if you're an experienced developer don't say no mosh I know how to do this this is so easy I know it's easy but what matters now is that I want you to get used to this theme tax so go ahead start a new project from scratch call it bitly and build this HTTP service for managing the list of genres you can see my solution attached to this lecture
Info
Channel: Programming with Mosh
Views: 1,106,688
Rating: 4.9432931 out of 5
Keywords: rest api, api, rest api tutorial, node rest api, nodejs json api, node js api, node js rest api, rest api tutorial for beginners, express tutorial node js, node js tutorial, nodejs tutorial, express tutorial, expressjs tutorial, express.js tutorial, code with mosh, programming with mosh, programming, web development, server side, mean stack, express js
Id: pKd0Rpw7O48
Channel Id: undefined
Length: 58min 39sec (3519 seconds)
Published: Thu Mar 08 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.