Planning & First Steps | Creating a REST API with Node.js

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome back to this series where we built a restful api with node.js in the last video we had a look at all the theory and that was important but now let's dive into the fun stuff and let's start building a restful api so let's have a look at what we'll build and then let's start with it so what are we going to build in this series our api will have a couple of resources i want to build the api that's realistic and that contains some things which are typical to restful apis for this we'll have a products resource so slash products is one route we can target and there i want to support get requests to get a list of all the products we have post requests to add new products i also want to be able to target the individual product by id and get information about that product patch that product so change it update it delete this product so that we can get rid of it and let's also implement our orders resource where we can place orders so where we for example could get a list of all the orders we have i also want to be able to post a new order so create a new order and i also want to be able to then access my individual order and just like for products get more information about it and not patch it let's say we shouldn't be able to edit our orders but we could delete so cancel them that is what i want to build we'll also add authentication to make sure that some of these routes of these endpoints are protected so that only logged in users can access them and therefore you will also learn how to log users and when building a restful api because we can't use sessions remember from the last videos so that won't work that is what we're going to build we're going to build it step by step we're going to start with it right now so let's start with building this restful api and for that i'll navigate or i navigate it already in the folder where i want to create this project make sure you do the same and then in the terminal here i'll just run make here for make directory to create a new directory and then the name of the project and you can of course also do this in the windows explorer or the finder manually you don't need to do that in the terminal i'll name it node rest shop something like that then with cd node rest shop i can navigate into it and now we have an empty folder now we first of all need to put this under control of npm nodes package manager because i will install a couple of dependencies and i will install them all through npm this dependency manager tool for that you need node.js and you will need this anyways since we're going to create a node restful api so having node makes a lot of sense you can get node.js from nodejs.org either download the latest version or if you're facing any issues with that download the long term stability version 8.9.1 at the point of time i'm recording this once you got this simply type npm init in this new project folder and this will now walk us through a little wizard here which allows us to initialize that so you can assign a package name version some description like a node.js restful api tutorial project build a simple shop api something like that entry point doesn't really matter for us here test command i'll leave that empty you can enter a git repository i won't do that for now can enter some keywords don't need to you don't need to and an offer here i'll put my name finally you can choose a license i'll confirm this default license and type yes with that we got this new file in there and i will now open this whole project in an editor now i will use visual studio code but you can also use a another editor sublime web store adam whatever you like so i opened the project we just created in this editor and there you see this package.json file that was created automatically through this npm init command and here you can always tweak these things you just confirmed in the terminal if you want to now open the terminal in this editor that's the built-in uh terminal into visual studio code it's the same as the default terminal on the operating system though and i now want to install a couple of dependencies we'll need we need node.js but we already got this on our system so what i will install here with npm install dash dash save save creates an entry in the package.json file is express because i will use express as a framework for nodejs to make building this api a bit easier and we'll add more packages throughout this video series but let's start with this one with express installed i'll add a new file to the project by clicking on this icon here or simply hitting command n and i'll name this file server.js here i will set up all the code to spin up my node.js server which as you probably know we do through code through javascript code so not like in php where we have a separate server software which then kind of is connected to our php script and stuff like that we create a server instead in javascript when using node.js now how do we create that server then we'll first of all import something from node.js and i'll store it in a constant name http const and let our next-gen javascript features which node.js in the later versions supports and i do import it with require http now if you worked a lot with single page applications or with front-end javascript development in general you might be used to the import something from something syntax now this syntax is not yet supported in node.js hence this old or still the only import syntax we have in node.js so this http package i'm importing here provides us some functionality we need for spinning up a server additionally i'll create a new constant port where i will assign a port at which my project should run and here i want to either get that port through an environment variable or i will hard code it in there now the environment variable would be process.nth.port and process.n simply accesses nodejs environment variables and this would be set for example on the server you deploy it on most hosting providers offer you the id opportunity or offer you tools to inject environment variables into your running project and then you would simply add this port environment variable if it's not set however we'll use 3000 as a default port thereafter i'll create my server and store it in a constant with this http package and then the create server command now to recreate server we need to pass a listener so a function which essentially is executed whenever we got a new request and which then in turn is responsible for returning the response i'll leave this empty for now but we'll add something soon with the setup we have here it wouldn't really work because we need to handle incoming requests thereafter i'll call server listen to really start the server and i'll pass the port as an argument so it starts listening on this port and then it will execute whichever listener or function we passed to create server that's the idea now this is a very simple server setup i'll now add a second file app.js and this file now is spinning up this express application which will make handling requests a bit easier for us so how does this now work there i will create a new constant named express and i will require express that's the package we just installed with npm install dash dash save i then will create a new constant app and just execute express like a function this will spin up a express application where we can use all kinds of utility methods and so on now i will add more and more functionality to this file for now what i will do is i will simply add app and then call a method on app and that method will just be use now use as a method sets up a so-called middleware so an incoming request has to go through app use and to whatever we pass to it now the thing we pass to it can have different formats it can simply be a function like an arrow function you can also use a normal one where you get the request the response and some special next function the third argument here is actually a function which you can execute to move the request to the next middleware in line and if you don't execute it the request will not go there and here what you could do is you could simply use response to send a response so you can here simply send a response and let's already send a json response by first of all setting a status code it's a method and takes the status code let's send 200 for everything okay and then the json method and this will send a json response so with the right headers set up and so on and there you can pass a javascript object will automatically be stringified for you because json data which is sent over the wire is in string format and there we could add a message property whatever you want and simply say it works now with that set up what we have to do at the end of the file is we add module exports and set the sql to app with that let's save this file and go back to the server.js file and there i will now import app with require and then i'll point to slash app this app file we just set up you can omit the file extension here by the way it will automatically look for js files now i pass app to create server and the express application qualifies as a request handler so with that we have a setup that should actually work and allow us to send a request a get request right now or any type of request actually to this back end and this middleware should make sure that we actually receive a response let's try it out and in the terminal in your project folder where you ran npm install you can now run node to start something with the node library and target server.js and this will execute it with node.js and keep this process running it doesn't finish so it's not stuck it should keep on running because you just started your server and now how can we see if it works well for now since we started this on our machine it runs on localhost and then at port 3000 because we don't have environment variables here so it takes three thousand let's try it out in the browser there if you enter localhost 3000 you should see a message it works and by the way you should also see this if you send some different kind of request like a post request now we can't easily simulate a post request for the browser like this but we can use a useful tool for this the tool i mean is called postman you can simply google for it and you should find getpostman.com it's a tool which helps you with developing apis it allows you to simulate all kinds of different requests you can download it for the different operating systems so i'm going to go with mac os here and then simply follow the instructions here install it enter the api endpoint and so on once you started it you're prompted to sign in but you can skip this and now you can create a new request so if you click here you can give this a name and a description you can all just exit here and now you're on this screen on this screen you can always create new requests by clicking this plus button here but then you can choose the different http words now we won't support all of them in this restful api and some of them are really rarely used but we'll have a look at get post patch and so on so let's try a post request and let's send it to localhost 3000 just like this click send and you should also see message it works and here you can also choose between the raw format so the request body as it looked like a formatted one and preview here also is nice if you for example would get back html that tries to preview it in a nicer way you can also have a look at the headers which were created by default like application json that was set up because we used this json method here on our backend and with that we created our first very basic restful api now it's not really useful it doesn't have different endpoints it's not adhering to all the constraints we set up but the base functionality here isn't that wrong now let's continue on this road and let's have a look how we can improve this and get closer to the api setup we sketched out earlier in this video
Info
Channel: Academind
Views: 323,913
Rating: undefined out of 5
Keywords: node, nodejs, rest, restful, rest api, tutorial
Id: blQ60skPzl0
Channel Id: undefined
Length: 14min 41sec (881 seconds)
Published: Wed Nov 29 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.