Restful API with NodeJS, Express & Typescript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] what's going on everybody thanks for tuning back in this tutorial covers a small project i made inside of github which is a basic boilerplate of how to use node.js in express but with typescript actually mixed into it i get a lot of questions on how to actually create one of these so i thought i'd make a boilerplate available to you guys inside of github and make a little video to explain how i did it if you don't want to watch the video by all means just go to github for the repository and have fun but if you want to see how i created it feel free to watch this video alright guys let's get started first things first let's open up visual studio code in the folder of your choosing and once it's open we're going to open up our terminal and we're going to type in npm init which starts the project for us i'm just going to name it api skip the version skip the description make my entry point source slash server.ts because we're going to be using typescript skip all this stuff and just type in yes and now we have our package.json file the next thing we're going to do is do an npm install dash g typescript nodemon ts node and prettier why we're doing the dash g is to install these packages globally that way they're available to us throughout any npm project the other reason we're doing it globally is because prettier and typescript as well as nodemon all allow us to run them separately by themselves against certain files so we're going to install those now once that's done the next step that we're going to take is we're going to make sure that we have the prettier extension installed inside of our visual studio code that way it automatically formats the code for you in some instances if you have it set properly and to know that it's using prettier so next let's do a tsc dash dash init which sets up our directory for typescript we're going to open up this ts config json file here and we're going to uncomment the out directory and make this period forward slash build this is going to be the directory once we compile our typescript into normal javascript next we're going to change this test function here to just the build function and we're going to make this command rm-rf our build directory um we're going to type the and and to run another command the command we're going to be running is prettier dash dash right and it's gonna be our source folder and then we're gonna add two more ampersands and type tse which allows us to compile the project into javascript from typescript the reason that we're putting this here is so when you run mpm run build it automatically gets rid of the old build folder cleans up the code for you if visual studio code hasn't done that already and then compiles it into typescript so our next step is going to be npm install and now we're going to put in some of our packages we're going to do express body parser and dot m the reason we're picking these is for some very specific reasons express is going to be the framework that provides us with everything we need to build an api dot m allows us to access environment variables if you choose to do so in whatever server environment you're running your api in and body parser allows us to easily figure out what kind of data is being sent through our http requests and parses it for us so we're going to install those and now the next step is to install our type definitions what these are is extra packages that sit on top of our packages express.m and body parser that have typescript definitions so that the typescript compiler and our linting understands what we're trying to do so we're going to type in npm install dash dash save dev we're going to do at types express at types body parser and at types dot m and install those now the next thing we're gonna do is set up our prettier configuration and we do that by creating a dot prettier rc file in our main directory now i'm just going to copy and paste this from an older project and let you guys look at the documentation for prettier to find out exactly what all these settings mean but basically what these do is allow us to clean up our code automatically or by running that prettier command in our npm build command and now that we've done that we're going to make a folder called dot vs code and create a file called settings.json and i'm also going to copy and paste this in here as well again you can get this from the github repository what this file is going to allow us to do is to automatically tell visual studio code how to format our project for us and to tell it to automatically pick up the prettier extension now that we're done setting up our configuration let's go ahead and start programming our api we're going to go ahead and create a source folder and inside of it a config folder i always like to begin with our logging so let's create a logging.ts file and we're going to make our own custom logger and start out with a function called constant gettimestamp that's going to return a type string and we're going to have it return a new date object dot 2 iso string what this does is basically gives us the current date in a nice human readable format once we've done that we can go ahead and create a const info function inside of this we are going to be having a namespace that is of type string a message of type string and then an object of type any what the object of type any is for is in case we want to actually pass through an object and take a look at it in its json format now that we've done that we're going to go inside and type if object to see if we have an object being passed or not then we're going to be doing a logging.info actually i'm sorry that should be a console. we'll just do console.log for now and we're going to open it up with the tildes inside of the console.log i'm going to put a couple brackets here and we're going to start to format our message let's go ahead and put a reference to the function gettimestamp right here next we can put in our info metric so that we know this is an info log next we can put in uh the namespace the reason that we're putting a namespace in is so you can quickly determine where this logging function was called because they're all going to be referencing the logging function from this file and then finally we could put our message inside of it and then at the very end let's go ahead and put our object that is of course if the object is there console.log will log it for us at the end now we can put our else statement copy this function over and just get rid of the object at the end so that now whenever we call this function if we don't have an object it'll just default to the second console log that you see here so let's copy this function paste it a couple times we're gonna paste it three times and we're gonna create uh three more functions that copy this we're going to start with our warren function change the console log to a console warren change the capital info to a capital one and we're going to do the same thing for error and debug once we're done creating our functions we're going to type export default and we can just do an object here and we're gonna just export each of the functions so we can just do info warn error and debug this notation is unique to javascript where you don't actually have to declare a key and then a value if your key and value are the same same name so if i'm just exporting info it will know to export a function called info there's one more thing that you're going to notice when you are copy and pasting these logging functions and that's prettier and visual studio code working together will automatically format them for you so whatever you have your prettier config set to and your settings.json set to it's going to be shown directly affected here every time you copy and paste or save your file next we're going to create a file inside of our config folder called config.ts and we're going to start off by importing dot m from dot m this is to import environment variables uh we're going to call dot m dot config which actually loads the environment variables for you now we're going to make a const server underscore report and we're going to have this equal to process dot m dot server underscore port with a default value of one three three seven so if you just pause the video and take a look here for a second what this is doing is first it's checking to see if process.m dot server port exists and if it doesn't assign it the default value of one three three seven we're gonna just copy and paste that and change this one to hostname we're gonna do the same thing for the variable over here and just change the hostname to localhost the next thing we're going to do is create a constant server object and inside of it we're going to define our port and hostname as the constants we defined above last but not least we're going to create a constant config object and assign it assign a server key to the server content we created above and then we're going to export default config what this does is basically allow you to access all of the variables we just defined so when you're inside of another file you can type in something like config.server.port to get that value it should be noted that the dot m library initially tries to load your environment variables from a dot m file you should take a look at dot m's documentation to figure out how exactly you want to configure it for your project now we're going to go ahead and create our server.ts file inside of our source folder this file is going to be the meat of our of our api and it's going to link everything together so we're going to divide this up into sections starting with the imports so let's go ahead and import http from http import express from express import body parser from body parser import logging from our config.logging file and import config from our config config file next we're going to declare our namespace as constant namespace is equal to server and we're going to declare our router equaling the express function our router is going to be what defines our api's behavior and our namespace is going to be what we use to determine where our logs are coming from the next section of our server file that we're going to define is our logging so what we're going to do is we're going to inject into our router a piece of what's called middleware and all middleware is going to have the request object response object and next function available to it and what middleware is is basically it's a function that allows you to either modify the request that's being sent in or to read it or to do something with the data that's being passed around and either end it right there and return it to the user or continue on to another piece of middleware what we're going to do is we're going to use our logging.info function we're going to first inject our namespace so that when it logs it logs with the namespace of server then we're going to add two tildes and inside of it we're going to be adding three variables a method a url and an ip the method can be accessed from the request.method the url from request.url and the ipfromrequest.com address if it is defined if it's not defined and you print it here don't worry all that's going to show up is an empty space once we've created this let's copy it now we're going to access the response through our middleware middleware so we're going to type in response.on and we're going to put finish inside of the quotation marks what we're going to do here is basically say that any this is basically a listener for any time that the response is finished fire off this function and inside of it we're just going to copy and paste the logging that we just had and simply add the status code to it by accessing it from the response dot status code it should be noted that this response dot status code is going to be the status that we return depending on the route that the user picks so after we're done logging the next thing we want to do is parse the body of the request so this is where we're going to inject our body parser so what we're going to do is we're going to type router use and on the inside we're going to do body parser dot url encoded and in brackets we're going to insert an object with the key extended equal to false and after that we're going to do router dot use body parser dot json as a function what these two injections do is first allows us to send nested json to our api although we're not doing anything with that in this tutorial it's going to be something that you're probably going to be using in the future so it's a good time to set it now and the bodyparser.json allows us to basically not have to call json.parse or use json.stringify on the react side it basically takes care of all of that for you the next thing we're going to do is define the rules of our api rules such as what kind of methods are allowed such as get patch delete or post where our requests can come from and what kind of headers are allowed so let's open up a new piece of middleware and we're going to add the following things in here first we're going to start with our response dot header and we're going to put inside of it inside the first quotes we're going to put access control allow origin with dashes in between and we're going to go comma and in the next set of brackets we're just going to put a star what that means is for now our request can come from anywhere when you're creating a production api do not have this make sure you have your ips and routes predefined the next is going to be our response.header and in this one similarly we're going to put access control allow headers and the headers we're going to put in are the following origin comma x dash requested dash with content dash type accept and authorization once we're finished with this next thing we can do is put a little if statement and put if our request dot method is equal to options return a header that shows us all of the options we're allowed to put as you see me type here and then simply type in return response dot status 200 dot json with an empty object this just returns a response of 200 which means that the method was accepted and it lets you know what kind of methods you're allowed to use inside of this api this probably won't get called as if you're programming it you're going to know what's going on that being said it's always good to have this so so far the request is going to bounce off our logging it's going to bounce off the body parser and then it's going to come through here all of them acting as pieces of middleware the next thing that we're going to define is our routes so we're going to put a little placeholder here for our routes because we actually haven't created them yet and we're going to move on to error handling so what that is is that if our api gets by all of our defined routes that means that the user or program has entered a route that doesn't actually exist so let's go ahead and create a piece of middleware define a constant error we're just going to type in new error not found and then we're going to return a response dot status of 404 you can look up the response codes you need to use online we're going to add a json object and it's going to have a message key with the error message that we defined above so let's go ahead and define our server now now that we have everything else pretty much defined we're going to create a section for it down here create the server and we're going to create an object and we're going to call it http server we're going to make this equal to the http.createserver method and we're going to inject our router into it our router contains all our predefined routes and error handling and middleware and then we're going to call our http server.listen we're going to pass in our config.server.port that we created in our config file and then we're going to add a function callback and add a little logging statement saying hey you actually turned on your server so let's put in the namespace and inside of the tildes let's go ahead and drop in server running on then we can inject our config.server.hostname we'll put a colon and then we'll do our config.server.port so it logs the message for us properly and let's finish that up here now if we go inside our terminal we can type nodemon source server ts it'll start the server for us and let's go ahead and open postmon or you can use the web browser and try and hit our api and see what happens now you'll notice that i sent the request but nothing's happening and if you were if you caught on before if you've uh worked with node.js in express before you'll notice that i forgot to actually add the next functions to the middleware that i defined before so the middleware that involves the logging the and the rules of the api both need the next function or the request won't get passed through so let's go ahead and throw those in now that these methods are in let's go back to postmon and let's try and run this again and now you'll see that it works we get our little not found message which means that the api is currently working properly so we can go ahead and cancel out of nodemon now this brings us to our final step let's create two new folders inside of our source folder one called controllers and one called routes the controllers are going to hold the functions for our api and the routes are what gonna define the literal pathing or routes to get to those functions using the api so let's create a file inside of our controllers folder called sample.ts inside of that file let's go ahead and import we're going to put some braces here from express and inside of those braces we're going to want three things we're going to want the request interface the response interface and the next function that way when we define our middleware in this file it will already have the types associated with it so let's create a const sample health check and inside we're going to define the middleware as we did before but this time we're actually going to have to assign the interfaces to it so you're going to have to go ahead and put a colon with the appropriate object after each object as you're seeing here so in the end it looks like this with the request being assigned to the req the response being assigned to the res and the next function being assigned to the next variable now at the top of the file let's go ahead and define our namespace for our sample controller and we can name it just that sample controller this is going to be used for the logging so inside of our function let's call logging.info you'll see that it automatically imports because i'm using visual studio code let's go ahead and put our namespace variable inside of it let's have a message saying samplehealthcheckroot called so the purpose of this route is simply to see if the api is working or not or just the sample for you guys on the inside let's do a return uh response dot status 200 and have a json with a message just containing the word pong obviously because when we define our root the root's going to be called ping now that we've created this function at the end of the file we need to export it so let's just export open up an object put the sample health check in and close it off now let's go ahead and create our sample route file so another sample.ts file in the routes folder inside of this one we're going to be importing express from express as we did inside of the server file here we're going to define our router as express dot router as a function next we're going to add a router.get defining that this is actually a get request give it the path forward slash ping and we're going to type controller dot we're going to import the controller from the controller folder and you'll notice that the controller is underlined that's because we don't actually have a default export so let's go back to the file and export it properly just put the word default right here now we can access it as an object and access the sample health check function last but not least we just need to export the router how we do that here is just type export equals router now that our router is defined we're going to go back to our server.ts file we're going to import our sample routes from our routes sample file and we're going to scroll down to where we put the placeholder before and we're going to type router.use give the routes a a prefix so we can do something like sample that way when we call it it will actually have the forward slash sample before the ping we're going to add the sample routes variable here and then we're going to turn on our server once the server's on we're going to go back to nodemon add the sample slash ping and we get our message pong finally we can cancel out of nodemon and if you want you can run npm run build and what you're going to see is the prettier function run and a build folder appear after typescript compiles our project so if you take a look inside the build folder you're going to see that it's all normal javascript that means that you have a build ready to go ready to deploy somewhere all right guys that's it thanks so much for tuning back in i hope you enjoyed the video and have fun in the repository take it easy guys [Music] you
Info
Channel: The Nerdy Canuck
Views: 24,444
Rating: 4.8992124 out of 5
Keywords: coding for beginners, coding, typescript, javascript, nodejs, tutorial, programming, cool programming, github, gitlab, react, react-native, qrcode, scan, restful, api, backend, server, http, https, c++, c#, js, java, html, pug
Id: vyz47fUXcxU
Channel Id: undefined
Length: 24min 7sec (1447 seconds)
Published: Thu Nov 05 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.