REST API - Explanation + Full Node.js Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome in this video we're going to learn one of the most commonly used apis in the world of web services the rest API but before understanding what is rest we need to understand what is an API API stands for application programming interface it's a set of routines and requests that enable communication and data exchange between different applications and services in short term it's a way for two computers to talk to each other there are different kind of apis out there but the most popular API used these days by most web and mobile applications is the rest API so what is rest rest stands for a representational stat transfer it's a set of rules and patterns that Define how applications or devices can connect and communicate with each other an API that follows all these set of rules and patterns it's called a restful API some real life examples that use rest are Google Maps stripe PayPal sang grid YouTube and too and many others let's understand the basics of rest rest apis use Uris to address resources rest uis should refer to a resource by noun and not by verb an API to get all products should be product and not get all product a client should interact with a resource by making a request to the endpoint for the resource over HTTP protocol the URI is preced by an HTTP verb or method which tells the server what to do with the resource the most used HTTP verbs are post to create a new resource get to read a resource put to update a resource and delete as the name already says to delete a resource if we combine the initials of these four operations we get a famous acronym called crud there are other HTTP verbs that can be used as well like patch options and head request can have a request body that contains a payload of data usually in XML or Json format the server receiv receives the request process it and formats the result into a response responses contain an HTTP status code informing the client what happened to the request the most used HTTP status codes are the 200s which indicates that the request was successful the 400s which indicates an error caused by the client and the 500s which indicates an error calls on the server to request for a specific resource a parameter can be added on the endpoint URL the server will process the request parameter and send a specific resource on the response body some API endpoints may take a lot of time to respond do it to different reasons one of the ways to improve the API performance is to implement caching it allows the client to reuse previously fetchet data another reason why some API end points may take some time is due to the huge amount of data to process to fix this problem the API should Implement pagination pagination is a process used to divide a large data set into smaller chunks to request for a specific page for example a query parameter can be added on the endpoint URL query parameters or query string is defined as a question mark followed by the parameters and their values the client can pass multiple query parameters in the URL which can be separate by an m%c qu parameters can also be used for sorting and filtering data all calls to the rest API should be stateless this means that every interaction is independent and each request and response must provide all the information required to complete the interaction rest apis do not require any surver site sessions servers are not allowed to store any data related to client requests lastly versioning of an API is very important API versioning is the practice of managing changes to an API and ensuring that these changes are made without disrupting clients there are many ways to version an API the most straightforward is to prefix the version before the resource on the URI in summary rest apis are popular and widely used architectur style for building web services and apis they're simple scalable and flexible and can be used to build a wide range of applications and systems let's build a rest API using node.js and express I'll I'll be using vs code for the tutorial but feel free to use any code editor you like and I have a empty folder here on vs code open and it's called rest API with no JS and we're going to start by creating our project so I'm just going to open the terminal here on the top and the comment to create a new node project is npm in it hit enter it's going to ask a few questions here uh you can just hit enter for everything and later we can change all this information information if we need to is this okay yes okay so as you can see here it created a new package Json file containing all the information from our project next we need to install the express dependency so I'm going to clear the terminal npm install Express Express is a framework that will help us with the route and manipulate requests and responses okay so Express is install under the dependencies object and as you can see here on the package Json as well we have a main field with the index.js file so we need to create that file here on the root so new file index.js okay this is going to be our main file let me close some things here the terminal and the package Json as well okay so here on the top U I'm going to start by importing Express so cost Express equals to require Express okay next we need to initialize Express so I'm going to create a new constant here call app cost app equals to express function okay uh next Express needs to listen in a specific Port so our server can be started so I'm just going to type here app. listen and the first parameter is going to be the port number so I'm just going to use uh 3,000 here okay and the next parameter is going to be a call back if everything is working I'm just going to type a message on the console so console.log and inside server started on Port 3000 okay now let's test all this so I'm going to open the terminal again I'm going to clear here first and I'm going to type node index.js okay server started on Port 3000 so our server is working let me stop the terminal here okay now let's create a Home Route a basic route and it's going to be a get route so right below the express initialization I'm going to type app.get okay and the name of the route is just going to be a slash so that means it's going to be a Home Route okay and next we'll receive two parameters here the request and the response okay all right so the request is everything that the clients uh sent to us okay and we need to send a response back to the client okay so let's do that right now so let's send a response back so response. send and inside I'm just going to type uh testing here okay just so we can test okay uh back on the terminal node index.js okay server started on part 3000 now I'm going to open the browser here and I'm going to type Local Host uh column 3000 hit enter and as you can see okay we send the testing response so our route is working everything is working let me stop the terminal so every time we change something in the code we have to save uh stop the terminal and run again node index.js so let's install a library that will handle this for us okay it's called noon so npm install nod modon and this is going to be a Dev dependency so I'm going to put dash dash here save Dash again Dev so this flag here indicates that nodemon will be a development dependency so if we check the package Json as you can see here on the dev dependencies we have nodemon and on the dependencies we have Express so if we put this in production only the dependencies will be installed not the the da dependencies okay this one is only used for development all right so let's test nodon but first we need to change here on the script section okay we have a script here test but we're not going to use this so I'm just going to delete it and I'm going to create a new script here and it's going to be named start and it's going to receive the node modon command so instead of running node index.js we're going to run nodemon index .js okay save it and now let's start this comment here so I'm going to clear the terminal and to run this script uh start we need to type npm start hit enter okay now nodemon will monitor changes on our project Let's test nodemon to see if it's working here on the index.js I'm going to change the response text here to hello world okay now once I save this file node modon will restart the server for us okay perfect as you can see here on the terminal nmon restart the server now let's test this on the browser uh I'm just going to refresh the Local Host 3000 and there it is Hello World okay so now we don't need to worry to stop the server and restart it again okay noon is already taken care for us we can even close the terminal here okay so we created our server and a basic home route and everything is working for this tutorial we're not going to use any database so we'll be manipulating some data directly on memory so here after the express initialization let's create an array of products that we'll be using to simulate a table in case of a SQL database or a collection in case of a nosql database and inside this array we're going to create an object with some details here like name and this one is going to be a laptop and we're going to put the price which is going to be 400 okay and we're going to have a quantity as well like in stock so this one is going to be four and let me add a different field here a Boolean field so active if this product we're still selling it and it's going to be true okay so we have our first object here with different kind of fields like a string a number integer and a bullion okay let me copy this so we can add another one so I'm going to put a comma here and paste and now this is going to be a keyboard okay and the price is going to be 29. 99 okay quantity we have 10 of these and is also active Okay uh this is good so we can start testing and let's say if a client request to read all this product so we need to send as a response this array of products for that let's create another G Route here so app.get and the name of this route will be the resource that the client requested so in this case slash product and it's going to receive the same parameters as the other route so request and the response and inside this route we need to send the products array as a response so response dot but this time instead of sending a text response we're going to send a Jason response so dot Json and inside we're going to put the products array with the two products that we have perfect so that's all we need on this route Let's test on the browser so Local Host column 3000 / product hit enter and there we go as you can see we sent the array as a Jon response so our new route is working but what if the client wants to add a new product to the array so back on vsod let's create a new route to create a new product here on the array okay so below the uh last route that we create the G products we're going to create a post route so app. poost so we use the post method when we want to create a new resource and the name of this route is going to be the same slash products okay the same as the git so the G Route is to read products and the post route is to create a product as you can see I put products in plural but we can also put in singular it's really up to you the name convention just make sure if you're using singular to make all routes in singular like this I'll put everything back to plural but it's a personal choice okay so the post route will receive the request and the response as well and this time the client will send to us a request with a body inside containing the product's information okay so let's log this request object that we have here so console.log uh requestbody let's also send a response so the request doesn't hang without a response okay so response do send and inside I'm just going to put a sample text here okay let's test this new post route but we can't test on the browser anymore because browsers only handle get requests so from now uh I'll be using Postman to test the requests uh Postman is a HTTP client so we can test uh HTTP requests with different methods there are other softwares you can use for client requests so feel free to use whichever you prefer here on Postman I'll click on the plus sign on the top to open a new tab and this will open a new request so as you can see here we have the URL field and the method field with a list of all the methods we can use here okay so let's just test here on Postman the get products that we already have so HTTP Local Host 3000 SL products okay we can click on send and there it is uh here in Postman we have a better form matter response as you can see here but let's test the new post route so I'm just going to copy the URL that we already have create a new tab and I'm going to paste the URL here and I'm going to change the method here to post okay and to send a body on the request we can click on the body tab here on Postman and we can send different kinds of body to the request but we want to send a raw Json body so we can click on the raw option and on the drop- down here we can select Jason oh okay perfect so now we just need to type adjon body here okay so I'm going to open an object and the fields must be inside double coat so the first field will be the name and this one is going to be a monitor 27 in okay since this is a string it should be in double Cotes as well okay the next field is going to be the price and this one it's a number a float so I'm going to put here 300 okay and the next field is the quantity and it's an integer field and I'm going to put two here and the last field is the active bullion field and I'm going to put true okay uh so if we click on send we're going to get the okay response here so everything is working now let's check on the logs what we have on the request and we got undefined uh that's because we need to tell Express that we receive requests as a Json format from the client okay so we need to add an extra configuration here it's actually a middleware on Express so after the express initialization I'm going to type app.use and inside Express do Json so that's it now Express is configured to receive request body as a Json format Let's test this again on Postman so I'm just going to click on send we got okay as a response and back on vs code there it is we got the Json request body from the client and now we can manipulate this data inside the post route perfect uh let me just close the terminal here and inside the post route we need to get the product array and insert the data sented from the client so below the console log I'm going to get the product array dot push to add a new object and inside I'm going to put the requestbody that's it now we need to send a better response to the client uh as you can see here on Postman the status send on the response by default is 200 okay but a better practice when the request creates a new resource is to send the 2011 status code which means created so let's change this response here on the route so to change the status code is do status and this time we're going to send 200 1 perfect and we also want to send a Jason response here with a message saying that the resource was created successfully so inside the Json method I'll add an object with a message saying product created successfully okay great uh let's test all these changes on Postman to see if the product is being created so I'm not going to change anything here I'm just going to click directly on send and that's it we got the 2011 created status code and the message saying product created success and let's call the get products uh endpoint now to see if the product was created so we have two products click on send and there it is we have the new product created inside the array with all the details that the client send on the request perfect Let's test this route again and we're going to create a new product so I'm going to open the post request here and I'm just going to change the details that we have here so for the name I'll add here uh computer for example and the price for this one it's going to be 700 the quantity we have just one I'm going to leave the active here as true but I'm going to insert a new field here so let's say the branch field okay and I'm just going to put here U ABC for example and let's click on send to test this okay so we got a successful message the 2011 and let's test the get products now I'm going to span this a little and let's click on send perfect so the new product was created but this new field here is created as well and the other products doesn't have this field so we might need to add some validation here to make sure to include only the fields that we need so let's do that back on vs code uh inside the post route uh I'm just going to delete this console log here and I'm going to create a new cost here and this is going to be an object that will have only the fields from the request. body that we actually need okay so in this case uh it's going to be the name the price the quantity and the active Okay so we're extracting these fields from the request. body now here on the products. p push instead of sending the request. body we need to send an object here with these fields separate so the name is going to be the name that we have on the top here and the next one is going to be the price equals the price and the third one is going to be the quantity equals to quantity and the last one it's the active which is going to be equals to active Okay so we're building the object directly inside push method but as you can see the name of the fields is the same name as the values so we can just add it once like this okay perfect so it's a lot more cleaner like this let's test this again to make sure only these four Fields will be included on the product details so on Postman let me call again the get products endpoint and it's only going to return two products because every time nodemon restarts the server every data that we had in memory is going to be be deleted so let's test the post end point again I'm just going to leave the same data here with the new field as well so let's click on send okay we got a success message 2011 and let's test the get in Point again so click on send and there it is the new product is here with only the four fields that we validate so the new field is not going to be there because we're actually handling this on the post route okay we're validating only these four Fields perfect so so everything's working let's do one more test here so what I'm going to do is I'm going to delete the name field okay and the new field as well okay so if I click on send okay we got a success message but if we call the get in Point again so let me open the tab and click on send the new product was created but without the name field and let's say that we need at least this field to be required so we need to add another validation inside our post route so let's do that back on vs code below the fields extraction here I'm going to add an if statement checking if the name is not on the request body so if and I'm going to put the exclamation sign here which means not so if name is not there we need to return a response for the client informing that the name is required so return and response. status and the status code we're going to send is 422 which means means unprocessable entity and indicates that the request contains invalid data so 422 and we're also going to send a Json response with a message as well so inside the object here I'm going to put message and the message will be name is required perfect so we had the return method here before the response uh that means that the rest of the code we have after this if statement won't be executed so Let's test again on Postman and I'm just going to call the get products endpoint so we have the two products here and let's include this new product without the name field click on send and here's the response we got the 422 on processable entity and the message saying that the name is required perfect so our validation is working and we did a quite a few changes here on the post route so we're actually adding only the fields that we need uh we're adding the validation to make sure the name is there and sending the correct response with the status code and the message perfect now we have the get product end point that we were testing here which returns all products but what if the client needs only one product let's say the client request to read data only for the laptop for example so we need to create a new field in this product that's going to be unique like an ID so let's do that every time we create a new product here on on the post route we're going to create a new field which is going to be a unique ID for the new product and to help us creating this ID we're going to require a new module on the top and this is a buil-in module that already comes with node so we don't need to install this module and it's called crypto so cost crypto equals to require crypto so crypto performs data encryption and decryption and it also has a function to generate a uu ID so that's the one that we're going to use so here before the products push we're going to create a new con here called ID so con ID and this is going to be equals to crypto Dot and there's a function here called random uu ID which returns a unique string every time we call this function now we need to add this new ID con inside the product uh object so here inside the P the object I'm just going to put ID ID equals to ID since it's the same name the key and the value we just need one ID here just like the other fields and let's send this unique ID on the response as well so inside the object here uh after the message I'm going to insert the ID so comma ID equals to ID but since the key is the same as the value so we just leave ID here perfect so let's test all this to make sure the ID is being created so on postman on the post endpoint I'm just going to insert the name here so name and this is going to be a computer okay so we have all the details here so I'm just going to click on send and there it is we got the 2011 with the message and the unique ID as you can see this weird string here so let's test this on the get product endpoint so send and perfect here's the new product with the new new unique ID field okay but as you can see the other products doesn't have this ID so we definitely need to add this new unique ID on this product as well so I'm going to copy this entire response here and I'll paste inside the product array inside our code okay and now I'm just going to copy this ID field from the last product we inserted and I'm going to paste inside both products here uh I'll just change the last letter or both of them so we can have unique IDE is here okay perfect let's check on Postman I'll call the get products endpoint and perfect so all products now have this uh unique ID field here so this is the field that we're going to use to get a specific product from the array and send it to the client as a response we just want to send an object with the product details like this one for example okay so back on vs code we need to create a new get route so right below the post route that we have I'm just going to type here app.get and the name of this route is also going to be slash products but this time the client will send us a parameter which is going to be the unique ID so we need to name that parameter here and to insert parameters we have to insert a column and the name of the parameter in this case it's going to be ID so slash product slash ID parameter and this also is going to receive a request and a response and inside the route let write the request parameter on the console so console log and to get the parameter from the request let's get the request object and we have a property here called Pam okay perfect let's just send a response to the client so response. send and I'm just going to send okay all right so let's just test this new endpoint on Postman and send this parameter to the server so I'm just going to copy the URL here for the get product products and I'm going to create another request using G as well and I'm just going to add a parameter here just a random number click on send okay we got the response now let's check on the terminal what we have on the console perfect so we have an object here with all the parameters that we send but we just send one which is the ID okay so everything is working now we can use this parameter to grab a product from the products array and send back to the client so inside the route I'm just going to delete this console log and I'm going to create a new const called Product so const product is going to be equals to the products array and to get a specific product here I'm going to use the find method okay and inside this fine method we have a call back which is going to return a product for us so I'm just going to put product here and inside the call back function we're going to check for each product on the array if the ID is equal to the request do params do ID okay so if the ID sended on the request parameter matches any of the IDS on the products array then the fine method will return us the object related to that ID now for the response I'm just going to copy the response that we have on the get products route so I'm just going to copy this one and I'm going to paste it on the new get route that we created now we need to send the consr on the response okay just like this perfect now I'm going to add the status code for all successful responses that doesn't have a status code uh although the default is 200 but let's keep the code organized and implicit add the status code for all of them okay so I'm just going to change in all the get uh requests that we have Okay so let's test the changes for the git specific product route so back on Postman I'm going to open the git products tab here and I'm going to copy the ID of one of the products that we have so I'll copy the computer product ID here now I'll just paste the copied ID as a parameter on the get specific product endpoint okay just like this now let's click on send perfect here's the response 200 okay and here's the computer product object so everything is working now let's test with a different product so I'm just going to get the laptop ID and I'm going to paste here as a parameter Okay click on send and here it is the laptop object now what if the client send an ID that doesn't exist let me change the last letter here on the ID okay so this product doesn't exist this ID here so let's click on send okay we got a success response 200 okay but the response body is empty as expect of course because this product doesn't exist so we need to add a validation here on the route to check if the product is returned by theine Method so I'm going to add an if statement here before the response exclamation sign product so if the product is not there it doesn't exist so we're going to return uh response with the status code now we have a couple of options here so let's start with the 204 which means no content it is a success response but there is no product matching the parameter okay and do send with nothing inside so let's test this on Postman again to see what kind of response we get click on send and there it is 204 no content as the status code now if we still try to send something here as a response to the client so I'll just write a test here and if we click on send we're still not going to get a response body because the 204 status code won't allow to send any response body since it means no content another response we can send to the client so let me just comment this one so return response status code uh we can send the 404 as well which means not found okay and let's send a Json message here so inside the object message and I'm just going to put uh product not found okay so let's test this again uh on Postman I'm just going to click on send and here it is 404 and the message okay so we can use the 404 as well no problem but usually 404 refers to our URL that doesn't exist okay an endpoint that wasn't found so for example let me copy the get product endpoint here okay and I'm going to open another tab to make another request but instead of products I'm going to put users okay this endpoint doesn't exist on our API so if we click on send uh we got this status code AS 404 as well no content so in this kind of situation uh when a resource is not found we can use 204 or 404 it's really up to your API needs okay so let me close this new request that we just made here okay perfect so here on our out I'll just leave the 404 as a default status code response in case if a resource was not found okay perfect so our get specific product route is working and what if a client wants to update details from a specific resource or a specific product till now we can only create or read products but not update a specific product so we need to create a new route to update a product okay so below our last route we created let's create a new one so app Dot and the method that we use to update a resource is the put method and the name of this route is also going to be slash products and just like the get specific route we're going to update a specific product so we're going to pass the ID parameter here as well okay so here in the end I'm going to put slash column ID parameter okay and just like the other routes we're always going to have a Quest and a response parameter here okay so inside this route we need to find the product that matches with the ID parameter just like on the get specific product route so I'll just copy the entire code of the get specific product route not the response though and add it here inside the put route okay so let me delete this commented response here because the default is going to be 404 if a resource wasn't found okay next the client will send a request body with the product details it will like to update so just like on the post products route the client send the same details so I'll just copy this piece of code where we are extracting the valid fields from the request body and I'll paste on the put route right after the product validation okay so now we need to check for each of the values on the request if they are present on the body if they are present then we need to get the specific product and update that specific field so let's start with the name if name is Define if it exists on the request body and then we're going to get the product dotame equals to the new name simple as that so we need to do for the rest of the fields here let me copy this one this if statement and paste it here before the first if so this one is going to be the price if it is there we're going todate the product price okay now we're going to do the same for the quantity so I'm just going to copy this one and okay so let me copy the quantity here paste it over here okay and the same for the active Okay copy copy the active field here if it is there we're going to update the product active okay perfect so we're checking if the product exists based on the par ameter if not we're sending a 404 code with a message otherwise we're getting the fields from the request body checking and updating each one of them okay perfect all we need to do now is send a response back to the client so response dot status and this one is going to be 200 as well and we're going to S an ad Jason response with a message inside so object message and I'm just going to put product updated successfully okay great so let's test this new in point on Postman and the first thing I'm going to do is open the get products tab right here and let's update one of these products here so let's update the keyboard quantity right now it's 10 so I'm going to copy the keyboard ID and I'm going to open a new request tab here on the top so we can the put end point okay so this one is going to be HTTP 3,000 products and the parameter here is going to be the keyboard ID and we need to change the method here from get to put okay now we need to send a body to the request so I'll click on the raw option and select the Json type now here on the body I'll create an object with the quantity field so let's check again the keybo board has 10 units so let's update this to 20 okay let's click on send and we got a status 200 okay with the success message now let's check on the get product endpoint so we had 10 keyboards I'll click on send and now we have 20 units great so the update products endpoint is working let's check on the get specific product endpoint so I'll just paste the keyboard ID here as a parameter click on send and perfect we got the correct details that we just updated let's update a different product so I'll copy the computer ID here and on the put end point tab uh I'll paste the computer ID here as a parameter and let's update a different field now the active field from True to false Okay click on send and okay we got the success message now now let's check this product here on the git specific product endpoint I'll paste the computer ID here click on send and okay uh we got the correct product but the active field didn't update it's still true here so let's write on the console what are we receiving on the request body for the active field so console. log active Okay so let's call the put end point again to check what are we receiving here back on postman on on the put end point tab I'll just click on send okay so we send the active as false again now let's check on vs code I'll open the terminal here okay so we got false on the console which means that we are receiving the correct value on the request body but the problem is actually on this if statement here so the active field here is false so JavaScript is reading this as if false because it's a Boolean field so what's inside this if statement will never be executed only if active is true then the if statement will be executed and the product will be updated so instead of checking if the active field exists like this uh we're going to change this condition so I'll add quotes on the active field to read the name of the field and not the value and we're going to use an operator here called n so if active in requestbody and then the if is going to be executed and product will be updated okay so let's test this on Postman again I'm not going to change anything I'm just going to click on send okay we got a 200 okay now let's check here on the get specific product endpoint okay now the active is false here and the validation is working okay so let's change this back to true just to make sure it's working click on send now back on the get specific product I'm just going to click on send and there we go okay so now the put and point is working perfectly great so this condition is working and we can get rid of this console log here okay so our API is getting some shape here uh we have an endo to get our product to create a new product to get a specific product and to update a specific product as well great so to complete a crude application all we need now is an endpoint to delete a product so let's create this new endpoint right below the put endpoint so app.get and we're going to use the delete method here to delete a specific resource and the name of this route is going to be slash products and the client will send the ID parameter as well just like the get specific product and update uh product so we are already familiar with this and we're going to have the request and the response parameter here okay so inside this route uh instead of finding a product like we were using before we need to find the index of that product so in the products array each of these products here have an index that starts with zero the laptop index is zero the keyboard index is one and the computer index is two okay so back on the delete route I'm going to create a new con here called Product index so const product index and this is going to be equals to products array and instead of using the fine function we're going to use the fine index function and inside this function is going to be the same as the fine function so we have a product and a call back here so we're going to search for the product ID and it should be equals to the request. params do ID just like we were using before so let's write on the console log this product index here okay so on the next line I'll just put console. log and inside product index okay now let's just send a response here to the client so response do send Okay so let's test this new endpoint here on Postman and what I'm going to do is I'm going to open a new tab here and the URL is going to be the same HTTP Local Host 3000 products and the method here is going to be delete okay and on the get product endpoint let me open the tab here and let me copy an ID here of one of these products so let's get the laptop ID okay copy and on the delete end point I'll just put here as a parameter we can click on send okay we got 200 okay back on on vco let me open the terminal and here it is zero is the index of the laptop Let's test with another ID here let's test with the computer it should return to so let me paste here as a parameter click on send all right and there it is the find index function is working perfectly now let's try with an ID that doesn't exist so back on Postman I'm just going to change the last letter here okay click on send and we still got the okay but we got minus one on the logs here so whenever def find index function cannot find an index it's going to return minus one okay so let's add that validation on the delete route let me just get rid of this console log here and we're going to check if the product index equals to minus one then we're going to return the same response from the other routes that we were you're using so I'm just going to copy here from the put route the 404 response with the message okay and I'm going to paste right inside the zip statement here okay so if the index is not found we're going to return 404 with the Json message that we were using before now if the index is found we need to delete that index related to the product from the array so product and we're going to use a function here on JavaScript that is called splice to delete a specific index from the array splice receives two parameters the first one is the index in this case the product index and the second parameter is how many items we want to delete after the index that we've inut so the first parameter is going to be the product index and the second parameter is just one cuz we just want to delete one product here okay now let's send a better response to the client so instead of just a text I'm going to put here the status code so dot status and we can send 204 no content here which means that the request was successful the resource was deleted successfully but for the other endpoints uh we are returning 200 okay with a Json message so let me change this to 200 and let me put Jason here inside the object I'll just put a message saying product deleted successfully okay this way we send the responses in the same pattern just like the put end point and the post end point okay perfect so everything here is done uh and we're ready to test this new delete end point so let's go back to postman and I'm going to open the get products tab here on the top and let's select uh a product here to delete so let's get the the keyboard okay I'm going to copy the keyboard ID so we can delete this product and on the delete end point I'm just going to paste here the keyboard ID Okay click on send perfect we got the 200 status okay the message and now if we check on the get all products endpoint there it is we don't have the keyboard product here anymore so the delete endpoint is working perfectly okay let's try with another one let's try with the computer uh actually let's try with a product that doesn't exist okay so let me just change the last letter here click on send okay and we got the 404 product not found okay perfect so the validation is working as well and great so our API is complete we have a complete rest API here using a crude example so we have endpoints to create read update and delete a res Source in our case is the products resource so one last thing I would like to do before we wrap it up is to organize this code a little so we add all the routes inside the index.js file but imagine if we have other endpoints for other resources this index.js file is going to be huge and really hard to maintain uh ideally the index.js file is where we put our configurations like to start Express to connect to a database and to create our server uh we should separate all this routes here into a different file so let's do that now uh I'll start by creating a folder here on the root of our project and this folder is going to be route okay and inside this folder I'm going to create a new file called Product route. JS okay and inside this file uh we're going to copy all the routes that we have from the index.js file so let me scroll all the way to the bottom the delete route to the array over here okay let's copy and let's paste inside the products route. JS okay so let's organize this a little bit here uh above the array I'm going to add a Express Handler to manage the route which is called router and we can export this to use in different files okay okay so con router equals to require Express dot router function okay so we're calling the function directly here on the express in import okay now we need to get this const router here and replace all this app here inside this file so command F or control F to open the find dialogue so we're going to find four apps and we're going to replace with router Okay click on replace all and that's it so now we have the router. dopost dop put and delete all we need to do here on the bottom is export this router uh function so module. export equals to router now we can use all these routes here in another file we just need to import the crypto that we're using on post endpoint so I'm just going to copy the import here from the index.js file okay I'm going to cut from here and I'll paste right after the router okay perfect let me close this dialogue and let's save the products route. JS and in the index.js file let me copy again all this routes here from the delete to the first G uh actually to the product array okay we can get rid of all this here and now we need to tell Express that we have routes in a different file in this case the products route.jpg file after the express Json configuration we're going to add app.use and inside uh we're going to require the products route.jpg file is on the root of the project and we need to access the product route file from inside the routes folder to do so we're going to add dot slash to access all files and folders from inside the same directory of the index.js file we're going to select the routes folder and products rout file okay let's save the index.js file and let's test this on Postman to see if the routes are still working so let me open the get all products tab here and on the response we have two products but on the array we have three so if I click on send great so all the changes we did it's working perfectly so we separate all routes from the index.js file and we can get rid of this Home Route because we're not using okay so if you notice here uh all routes from this file it starts with Slash product okay and we can actually configure this uh inside the index.js file okay so everything that contains product here uh we're going to add inside this app.use okay so as a first parameter here I'm going to put slash products and comma and then the required products route file perfect so now we can get rid of all these slash products on the start of all these routes here so let me select the slash product which all routes starts with and let's open the find dialogue okay the SL products is already on the field and we we're going to replace with just a slash okay replace all perfect so we need to remove this extra slash here from the routes that has the ID parameter okay so the get specific route the put route and the delete route as well okay perfect so let's test some of these end points here to make sure it's working with this extra configuration we made here on the app.use on Postman let's call the get all products route okay perfect it's working now let's add a new product here on the post route and the name of this one is going to be I'm just going to put product test okay and the price is going to be 300 and the quantity we just leave as one and the active will be false for this one click on send okay here's the message with the ID 2011 now let's test on the get all product and perfect so here's the new product with all the details uh we added on the request okay the changes we made are working fine but we can still improve this code uh it's a good practice to separate the routes file from the logic inside this routes and we should create a file uh with functions that their names already gives us a hint of what that function does like for example get all products get product by ID create product update product and so on and we're going to call these functions from this separate file inside these routes okay uh we call these files controllers so here on the root of the project uh I'll create another folder called controllers and inside this folder I'll create a new file called products controller.js okay perfect so inside this file we're going to copy all the routes that we have here on the products route. JS okay so let me scroll here to the delete route to the array actually I'm I'm going to copy the crypto as well okay and we're going to paste inside this products controller okay great so let's make a few changes here uh we're not going to have this router. G router. poost anymore we're going to replace this uh with functions and we're just going to leave the code from inside the r we need to export these functions so we can use on the routes file to export the function I'll put here export Dot and the name of the function so the first one here will be get all products and this is going to be equals to the same code that we have here on the get all products route so inside this function I'm going to add the two parameters the request and the response and we're going to put the function here Arrow function and inside I'm just going to copy the response that we have from the route and place it over here inside the function perfect so now we can get rid of this git route here now we're going to do this same process for all the other routes so export Dot and the next one will be create product okay and I'm just going to copy here the whole thing that we have from this route including the request and response equals to and I'll paste it right here okay so we can get rid of this post route here and now for the specific product route so export and this one will be dotg product buy ID okay and it's going to be equals to the same code that we have here so I'm just going to copy paste it and that's it now we can delete this route and the same for the update product so export dot update product and it's going to be equals to the same code from inside the put route okay just copy and paste okay delete the route the put route and now export. delete product and it's going to be the same as the delete route okay copy everything and paste it right here and delete the route okay perfect so we have all the logic from all the routes separating functions inside this controller now we just need to mod ify the product route file deleting all the logic from inside the routes so I'll start by removing the crypto library and the products array as well okay so now we need to import the products controller.js file here on the top so C product controller equals to require now we need to go back one folder because we're inside the route folder so we need to access the control roller folder okay so for that I'm going to put here dot dot slash and we are accessing the root here so controllers and the products controller okay perfect now we need to replace for each route the logic inside with the functions from the controller file so here on the get all products route we're going to add the products controller. get all products now we're going to do the same for the Post route so I'm just going to select all the code inside the route out and replace with products controller. create product okay the same for the git specific product so products controller doget product by ID okay the same for the put route so select the code and products controller. update product and the last one for the delete route just going to select here and product controller delete product okay perfect uh let me organize this routes file here so I'll just remove these blank lines between the routes and let me group all the routes by Method here so I'll get the G product by ID route and I'll just cut and paste below the all products route great so we complete all changes for our rest API and the code looks a lot more organized and cleaner than before uh we set separate the route file from the logic and we add it on the controller file now let's test each of these routes to make sure they're working after all the changes we did back on Postman let's check the get all products route okay here are the three products we had in the array let's add a new one okay we have all the details here I'm just going to click on send perfect product create let's test again the ghetto product okay here's the new product uh let me copy C the new product ID and let's test the put route so I'm just going to paste here as a parameter and I'm going todate the name field and inside here I'm going to put adapter Okay click on send and we got a success response now I'm just going to copy the ID here on the parameter and let's test the get specific product so I'm going to paste the ID here click on send and here's the new product update with the name adapter okay perfect now let's delete this product here to make sure it's working so I just paste the ID here and click on send okay product deleted successfully let's test the ghetto product and the product's not here anymore so all routes are working after the changes we made awesome so let's say we need to create new routes for other resources uh we just need to create a new route file here inside the routes folder so for example users route .js we probably need to create a users controller as well and here on the index.js we need to add another app.use so let me copy the products route and change these products here to users and require the users route file okay so in this video we learned the basics of a rest API how to manipulate requests validate a request body and parameters uh send responses to the L with a status code and a Jason response as well we learn how to configure Express and organize routes and controller files uh I'll leave the get repo link for this project on the description below uh hope this video was helpful and thank you so much for watching so I'll see you in the next video
Info
Channel: manfra․io
Views: 4,230
Rating: undefined out of 5
Keywords: rest api, Rest api, REST, rest, REST API, rest api with node.js, Node.js, node.js, express, node.js with express, code, vscode, nodemon, manfra, manfra.io, javascript, Basic of rest api, request, response, http protocol, http status code, crud application, CRUD, crud with node.js, basics of rest api, github, mvc, postman
Id: 0pez9kbIoJQ
Channel Id: undefined
Length: 62min 44sec (3764 seconds)
Published: Thu Dec 14 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.