Adding More Routes to the API | Creating a REST API with Node.js

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome to another video in this series thus far in this series we had a look at what restful api zart and we started building one we only support one API endpoint one route one URL does fart and that's our route route and we support all HTTP words which cause we don't care about which one we got but we got a very basic restful api working now let's continue working on it in this video we'll add more routes to it so let's start improving this API and for that I'll start by improving the folder structure to make it easy to well to keep this project manageable I'll treat a new folder which will named API because all my API related stuff like the routes that the models will use when we work with data and so on should go in there so in that folder I'll treat a subfolder which I named routes and in there I will now add a product dot J's file which should handle my product related routes now how can we set up a route here for that I'll first of all again import express with require Express and by storing it in this constant Express now I will set up the Express router that's like a sub package G Express Framework ships with that gives us different capabilities to conveniently handle different routes reaching different endpoints with different HTTP words we enable it by simply using the Express packet we imported here and then calling router with a capital R as a function like this now we can start using that router to register different well routes now if we have a look at the API as we planned it we're at the products route here right now and I want you to register or at the products resource I should call it the URL is called a resource basically we're trying to access our products related resources and it will implement a get in a post route for that products URL then on the other hand means that if we send some other request like a patch request to slash products that it shouldn't reach this route so how do we do this on this router package we can add get we can call get get is a method that will handle incoming get requests the first argument is then the URL and that URL here should be slash products now to be precise it should be just slash because I want to load or ascend the request to this products file for incoming requests targeting anything with Slash products at the beginning of the URL so anything that reaches that foul will already be beyond at that point will already have slash products at the beginning so here I only need to parse the part after that now that clearly is confusing so let me show you how this setup works back in fjs i will import my product routes new constant product routes should require slash api / routes / products without ojs at the end now i want to make sure that requests are forwarded to this file if the URL they are targeting no matter which HTTP web just the URL is slash products for this I will work on this middleware where every request is funneled through and use a different format not this function with request response next but now the first argument is a filter essentially and I say slash product is my filter so only requests that start with this path EUR will then be handled by some handler I pass as a second argument and that will be my product routes so anything starting with slash products in the URL will be forwarded to this file and therefore in this file we must not use slash products again because that would essentially try to fit slash products slash products which we of course don't want to fit so we can just say slash here and this will essentially target URLs or requests aimed at slash product slash nothing in this case ok so I hope this is clear we're just using this setup so that we don't have to manage all the files in one file but can split them on a feature basis so this is the get method we now tell it which kind of sup route or sup URL we want to handle and the second argument that is a handler and that again is just a function where we have to request the response and this next function we already saw in the last video now we can handle get requests here and for now I again want to send a response where we set status code 200 jason and return a JSON object where i will set a message property and you could send a different one where I say handling requests get requests to slash products novel copy that setup and add a second route with the post method and this will now handle post requests to this path therefore here will output handling post requests to slash products and now I will simply say module exports router so that the router with the routes we configured is exported and can be used in other files like the app.js file where we import these routes and then we assign them here let's try this out let's now start the server again with node server j/s and let's go back to postman which we already used in the last video there I'll again send a post request to localhost 3000 and I get back an error now that makes sense because I was sending a post request to just localhost 3000 and I got no single method in my code that would handle such a request we forward all requests to slash products to our products routing file here and I got nothing else so error handling is something we can improve because right now I just get some HTML text some default error page basically and I was talking about HTML not being that useful to us so we probably also want to return JSON data in error cases but let's focus on error handling later let's for now make this work by targeting localhost 3000 slash products now if we send this we get back handling post requests to slash products and if I do the same for it get I get handling get requests to products if I choose some other method like put then I get an error again because we only support get and post now let's add routes for all the other things we set it up on these slide or we plan on that slide for products that were also requests to the individual products so I want to use a router again and I want to be able to get information about one single product so I said I have a get request and now keep in mind slash products already is at the start of the URL but thereafter I expect to get the ID encoded into the URL now I need a variable segment for that and with express we set us up with a colon and then any name of your choice that will be a name by which you later can extract it like product ID second argument again is this function with request response and next and then in here we can again return a response and maybe we even take a more complex code here and first of all we extract that product ID so ID could be request param this is an object with all the parents we have and there we will have a Product ID param because that is the name which shows here and if you chose a different name you have to extract it by that name down there let's now check if ID it's is let's say equal to special in this case I could return a response with status code 200 and a Jason data object where I say message you discovered the special ID and obviously this has absolutely zero purpose Albert and showing that we correctly read T parameter in all Africa cases I'll return response status Jason and dere let's say we also want to return the object with a message property and you could mix this up and maybe we do and also return the ID property here so ID could then be the ID we extract and store in this constant and for the other requests here or for the other IDs you passed an ID that could be what we return now let's try this out we should be able to now send a request to slash products slash some ID and depending on what we pass and I as an ID we either get back this response or this one so back to postman let's go to get because we added a gat route and let's add some ID or one two three whatever you want hit send and we get an error because whenever you change something on the server you need to restart it so cancel it with ctrl C and then rerun node server J s let's try again let's send this and I get you passed an ID awesome now let's replace one two three with special and now we discover two special ID and we also get back the ID showing us that extracting it did indeed work and we will also replace this code with more useful code throughout this series so we got this product ID extracted now we also wanted to support a patch in a delete route so I will just copy that route here with this ID in the URL and I will add a patch method here to support patch requests to that and in there I simply want to return rest status 200 Jason and there we could have a message where we say updated product and then I will add another route where I basically have the same but with the delete method to support delete requests where I say deleted product as a side note if you're wondering why I never return this there's no need to do so there is no code running after this we don't make it into this method here because we either have a patch or a delete or a get Enzo on request you only would need to add return here if you had some other code after this response where you potentially again send a response because sending two responses isn't a great idea now with these changes in place let's restart the server and let's try it out let's send a request a patch request and we get updated product if we send put it still fails because we don't support this but delete on the other hand does work and we get back deleted product so this all works and this is how we add our routes how we add more routes and how we can also work with routes that have an ID now we also had order related routes so let's add these two and I'll add them in a new file orders dot J s because I want to keep my files clean and focused I can copy the code from products jazz though put it in there but get rid of all the routes I just want to have the same imports and in the end export to router and then for orders if you recall that slide we wanted to support get and post calls so get to slash orders and I will load this file just as I load the products file so we will already ensure that we parsed it for slash orders at the beginning so we don't need it here hence there we also have a request a response and this next function which we haven't seen action yet because we never need it to forward a request we wanted to send a response so here I will also send a request response excuse me 200 status code and let's pass an object where we have to message orders were fetched and of course for the serious people update this to really return a list of orders now let me also create another route post to orders where we can say order was created and maybe we want to return status code 200 in one year which is the appropriate status code for saying everything was successful resource created hence for products for the post request we should also return 201 now that I think about it so make sure to update this too and back in orders I now also want to have routes for getting information about an individual order so I will copy this set up here place it here handle get requests to slash orders slash and now here comes to order ID and our dynamic path parameter hence the colon there I'll send back status code 200 and send back some order details possibly with the order our ID which we could get on the request parents object by accessing whichever name you chose here in the path and let's do very same for deleting an order there I will use the delete route here the delete method to handle the riddle eat request suitors ID and there I can say order delete it now again that's restart this server and let's try it out let's send a request a get request to slash orders and it fails why because creating the orders in that file is nice all these routes right but we don't forward requests to that file yet we do to products we do that in the app choice file with this line here we need to do the same for orders so I will duplicate this import here and name this order routes and I will go to slash IP I slash routes orders here and then I also will handle requests going to orders with my order routes so with the route setup in that file and now with this we can restart this server and try again sending a get request to slash orders and now we fetch them now let's try a post request which should also work and I see order was created here you also see the status code 201 here and now let's try order / some order ID can be a number can be a string let's try a get request order details and we also see the ID and let's try a delete request and we see order deleted and the ID so all these routes are working they're not doing super useful things yet but one thing we already got is a basic API not perfect not complete but we're getting there now let's enhance our setup and things like error handling and so on in the next video
Info
Channel: Academind
Views: 232,719
Rating: undefined out of 5
Keywords: node, nodejs, rest api, restful api, express, router, tutorial
Id: FV1Ugv1Temg
Channel Id: undefined
Length: 17min 4sec (1024 seconds)
Published: Fri Dec 01 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.