Building a Simple HTTP API with Express.js

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everybody today I want to talk about building really simple HTTP api's using JavaScript quick overview before we start I'm gonna describe what we're gonna build we'll take a look at how we can understand URLs diagram to better understand our API and then we're going to get into coding and actually building the API awesome so today what we're gonna make is a coin flip API using node and Express and basically what's gonna happen is we're going to send a request to flip a coin once or more and then we'll get a response back based on if it's heads tails or how many times it was either one all right I thought out the way let's take a quick look at how URLs work we use URLs on a daily basis I'm sure and there's four main parts to it so the first part is the protocol which is in red and this URL here is just me searching for the weather on Google and you know protocols HTTP host names google.com in blue and then the slash after the host name is basically the endpoint or the resource and you know there can be multiple slashes but in this case we're just accessing the search resource of Google and then separated from the endpoint is a question mark and after the question mark becomes parameters which are key value pairs separated by an equal sign so in this case the parameters that we are sending to the search endpoint is Q and Q equals weather now let's just take a quick live demo and we will go ahead and do some of our own Google searches so if I type in dog right and you know getting it will get an answer from Google right let's take a quick look at the URL here at the very top we have protocol obviously HTTP google search and then here comes the question mark and then we have dog and some other stuff on the right side which looks kind of crazy another thing that's very important to know is that if you want to send multiple parameters to a URL in point search in this case each parameter is separated by this ampersand so you can see Q dog Oh Q dog I'm not sure what these are you know we don't work at Google I'm assuming and we can't get a somewhat of a look at what we're sending now if I get rid of all these right let me change my query to water I know you'll see I never entered anything in the search box but it changed because we changed the parameter here to the URL um what happens if we do like this if we do if we misspell water like that you can see it corrected it to water and this endpoint looks crazy are these parameters I should say let's take a look at another quick examples go to youtube and if I click on any video here we'll see that this URL is gonna change based on what I click on so I'm just gonna go ahead and click on this like giant playing video and um we can see right here that um the endpoint became watch and then separated by a question mark is just one thing V equals something and one more thing to note is that you can also add another parameter in here which we will write now if you do a percent T equals and then the let's say 30 this parameter right here what happens is it basically skips to 30 seconds and it interpreted this as another parameter to the endpoint which is pretty cool so you can actually modify you know the content on the web page just by messing around up here awesome now that that's out the way let's take a look at the quick diagram of what we're gonna build for this coin flip API so we're going to make two endpoints the first ones flip coin and then it should just respond with like a heads or tails simple string response and then we'll make another endpoint which is pretty much the plural flip coins and separated by this question mark is a parameter and we'll just call it x will interpret the times on our API and then we will respond with JSON instead of just a string value just so we can be more official some other examples of HTTP API is include our open weather map so let's take a quick look at how they work open weather map let's take a look at their API Doc's go here then we can go down to examples zip code and you can see that for example making this request you know for slash data a 2.5 whether here comes the question mark zip is that and then it will respond with JSON and JSON stands for JavaScript object notation it's just a way of arranging data makes it pretty easy to interpret when we're getting response from the API alright that done let's go ahead and start building this cool I've opened my terminal and I'm in my home directory if I do PWD just shows where I'm at you can make it folder wherever you want to build this thing but I'm gonna go ahead and just type mkdir make directory and I'm going to call it coin flip API now after you've done with this I'm going to just open it in vs code and I can just type code coin flip API so you can go about however you want to do this just make a folder and then open up open it up in vs code now that vs codes open I'm just gonna open a dedicated terminal within here let me close my terminal that I was using just now and I'm just gonna use the one in this window and now we're gonna install only one thing this time using NPM so NPM install also if you don't have any p.m. installed you can go to the node website and just install it there NPM annex install Express cool now while that's going should be pretty quick there's only one thing right nice and just generated node modules in package JSON package lock I should say and I'm gonna make one folder here and this is just gonna take gonna contain pretty much all of our API code just call it server J yes real easy here we go now we're ready and first I'm gonna do is I'm going to define a constant a book called Express and it's going to be equal to me just requiring the module that we just installed sending a string here express nice now I'm going to define a second variable called app cause app equals and then we're going to initialize the server it just returns pretty much an express object or you know and Express application instance I should say now if that done all of our requires and initializations are pretty much completed we can go ahead and build this API to make an endpoint like we mentioned before those forward slashes you do app dot get or you can use app post littler HTTP methods but a simply plate you can just do app kit we'll just put a slash for now and then after you do that it takes a callback so first you open up another set of parentheses let's just call this a request response and these two variables here that I've defined in their parentheses after quickly just put a arrow open brackets hit enter we'll make some space and basically these two variables here automatically get populated with request information so when someone sends a request to the API like we saw and then response information so you know we can modify this to modify response to the user and let me add a semicolon here now I'm going to do I'm not gonna do anything but just response dot send and then you open parenthesis I'm just gonna send back a string sing hello my work that's it so this we've created our first endpoint handler which is just going to be the slash and now I'm going to add one more thing with the app which is app dot listening and in here we can supply a port that we want to listen to so let's do five thousand and then another callback and this callback gets ran pretty whenever the app is ready to go and listening and I'm just gonna do a console log oh by the way if you type log in hit enter in vs coda automatically populates this for you which is pretty cool I'm going to say started server on port 5000 so this is the print statement right awesome got this and now I'm going to run the file with the terminal like node and then the filename which is just server jeaious cool so the console log obviously went and it's listening on port 5,000 now let's open this up in a window I'm just gonna use incognito why not and um in order to access this server it's not unlike you know a certain website like w-w-w-whoa you just do localhost colon and then the port number we did 5,000 right you can see that we got a quick response really easy locals 5,000 and if you had a forward slash it's the same thing because we've only added a handler for this endpoint just a slash and we're going to define another endpoint called flip coin flip - coin so just another app dot get to find the endpoints towards a forward slash flip coin and then here's our callback function as mentioned before the request parameter is automatically populated with the request from the client or you know whoever's using your API and the response is going to be just whatever we want to respond with and now let's be a little bit different here we can you know just find the logic for flipping the coin right now but I just wanted to show you how Express handles sending parameters in the URL so if you do response dot send and then in these parentheses here instead of just sending a string value I'm going to send something from the request parameter which is going to be a field that represents everything in the URL that is a parameter so you do request doc query and let's save that let's rerun it really fast here we go now if we go to the forward slash flip coin and no parameters no X no question mark it's going to be a blank object you know just some brackets no let's add something let's say hello equals yes now check that out it automatically populated the field hello the key to map to this value yes and we'll do another one let's say yeah color equals blue you can see that it matches the same order hello yes first then color blue now what I'm gonna do is I'm gonna add one more parameter just for fun just to show that this really works it's a song sandstorm no darude sandstorm uh-huh okay so here you go automatically populates based on whatever is going on over here and this makes building these API super easy as you can use the query field and then just extract whatever you need you know assuming that the client or whoever is using this API sent it over to you awesome so flip coin we did mention in the diagram that it's not going to take any parameters so let's just go ahead and define some logic here that's going to handle the you know the value of heads or tails so first I'm going to create a value called kind of to define those constants we're not going to change it let's do a Const you know and own number and JavaScript has a really cool library built in called math.random or just the math object and what this returns and it's going to return a random number between 0 and 1 so what we can do is just check if it's above 0.5 or below and then from there we can just determine heads or tails so we'll see let response equal let's just say nothing for now and we'll give it a value based on the output of random number so this is super basic stuff you know I'm gonna do an if-else like yourself random numbers less than 0.5 let's just let's just assign the value a minute don't call this response I'm messing up here cuz we've already defined a response variable so let's change that sorry about that let's just say coin let's say coin value if that makes more sense right alright yeah there's some really cool built-in functions here you can do a if you highlight this and then do come control D or command D if you're on Mac you can highlight both and then modify them at the same time pretty cool vs codes awesome so I'm gonna just give coin view value just a heads and then if that's good then we're gonna do the other condition where it could more than 0.5 and I'm just gonna close okay there it is okay now let's let's send coin value back boom should be good so we're no longer handling parameters here but we will when we do flip coins all right ready flip coin heads heads tails how about that pretty easy right pretty cool pretty cool I'm doing ctrl R to refresh by the way but you can just click and answer if you want to be a little slower so yeah it's working very nice and now let's define our last endpoint you can probably see right now that definitely making these HTTP API is in JavaScript is like super easy let's do flip coins count coins I don't know what that is haha alright requests damn you get that forced laughter ha ha gosh I should get some sleep huh okay you know the deal the usual now what we got here is just like above and we're going to take in one parameter do you remember how to access that could you request man do I even remember come on shout at the screen what was it was it request query was it request at params I don't remember but I hope it was request okay let's just do cost times is equal to request our query times like that because remember that when it does the object responds like we saw earlier it's going to do whatever you sent in the URL so for example if it's like Hello equals yes it would be request querida hello but since we're going to be sending in times we want to make sure that it's requests are queried at times and what I'm gonna do here is I'm also going to console.log times Oh quick and then let's do response dot send we're not gonna finish this quite yet but we're gonna just do response dot send I'm doing development because I want to just show what happens when you send the x parameter and when you don't because I think our API should be able to handle if we are you know using the right stuff or not so we're going to rerun this server of course and now let's go ahead and do flip coins under development response as usual but notice it says undefined right now because we didn't send anything yet so I'm gonna modify this to just say x equals 5 and I hit enter now if I go back you can see that now it's 5 so we really should be handling if the user is sending x or not and that can be done with a very very simple if statement we do if x and then to find interior else you saw that I use the shortcut earlier to do the if-else but I typed it out here and I'm just gonna do response to us and that's just like hey you need to send times and then here we'll just put response to us and let me just paste it and then I'm just gonna say under development for now again I don't know what I really should have deleted that line good all right [Music] let's do this so it's just assigning development I forgot the value of course the exclamation mark now if I don't send it I check it out we have some cool handling with our API here which is awesome now it's assuming that x let's say let's not another conditioner so let's say if x and x is greater than zero because what if they send a negative value you know that be kind of goofy messing us up over here so um let's let's just we test it again let's just make sure that we're handling undefined and negative or non positive values so flip coins right that's normal I'm gonna modify this again I'm gonna so x is equal to zero you can see that the output is still upset now if I do x is 10 very nice you're handling this very effectively now we're pretty much just gonna do the same thing here I'm gonna define a very simple for loop you know the deal supposed to four let I equals 0 is less than come on man this is like baby baby stuff eyes less than x and then we will just increment I by one for each for loop iteration now I'm gonna open this for loop and we're pretty much going to take very similar logic from above but now since we're doing it in multiple you know number of times one or more we're going to keep track of each heads or tails value so first let's just declare two variables so just like kids sorry where's the slit heads equal to zero and then we'll say let tails as well equal zero and these variables are just gonna keep track of how many times it was heads or tails and then in the for loop body I'm going to define constant variable by random number very similar to before I just make that math dot random now we're gonna take the similar if logic I'm gonna reuse that if else shortcut but if you don't have vs code you can always just you know write out yourself the condition I'm going to check is if random number is less than 0.5 right and if it is less than 0.5 we're going to just increment heads by one you can use the plus + shortcut there and then if it isn't we will increment tails by one very cool now but doing this we need to recede to send back a response to you know the client or whoever is calling our API instead of just doing response not sent I'm going to change this to do response that JSON as we're going to return you know JavaScript object notation as we saw with that weather API so let's just go back through real quick hoping the weather show a quick example of like a JSON response from an API that's used you know in the real world go ahead docs my favorite is if I just look up Isaak code so here's an example a PI response we can see like it starts the brackets just like mentioned before now let's go ahead and do it on our own here so I'm gonna open this up with brackets and open weather map as you can see I was like something like a weather field chord you know bass mean all this stuff we're gonna just do two fields which is heads this is the first fields call in and we're going to assign the heads field to the heads variable and then we're gonna do the same thing with tails just assign it to the tails variable now this looks pretty redundant and you might be thinking is art better way to write this and you can imply this kind of you know written out heads calling heads by just doing this if the variable name is the same as the field name you can do this and you'll get the same result which is pretty cool so let's go ahead and change the tails alright just add a space in front and at the end you know make it look a little prettier so there you go here is our finished flip coins API why don't we take a quick look and see what happens so I'm going to rerun node and then back in our cool so times we sent in five we got four tails in one heads let's do our x is 50 there you go 24:26 I'll refresh the page with the ctrl R I'm pretty good pretty biased towards tail as you can see then I went to heads so I guess it is pretty you know it's pretty reliably random around 25 25 right 50-50 chance say we have 500 now in doubt you have 500 coins I need to flip all at once so you can use the same pair that you've just built to you know simulated pretty cool all right with that done let's take a quick look back at our diagram of what we built so we have on a flip coin in point right and we know that works let me just split the windows so here's our diagram we will just go to local as 5014 right heads heads tails you can see that I'm refreshing it on the right and it's behaving very similar to what you've expected and then I'm gonna go ahead and do the flip coins API once real quick just to prove that you know we got there remember the question mark and then x equal let's do like 1000 why not cool pretty close you know 500 a little over 500 a little under 500 I wouldn't if we get a 500 500 that'd be pretty cool nice so with that done why don't we call on this API with some JavaScript code on the other side meaning that we're going to write some code here that's going to use HTTP to send a request and get a response back and yeah we'll just see this API in action will invoke it with other code instead of manually with this URL so we're gonna hop back in the vs code window and I'm gonna make a new file called clients jeaious and just before I start writing out this client J's file is gonna be about five lines of code I'm gonna do npm install we're gonna install a quick other dependency called node bench and there's a go pretty fast okay telling me to upgrade my npm but i don't do that right now nice so what we're gonna do is we're going to import a function called fetch and using the require function built into node or it's gonna do a choir node fetch well and what you can do with this fetch function is you can make HTTP requests so really anywhere it doesn't have to be locally to the internet wherever you want and um you know on our server right it's running on localhost 5000 so we can pretty much make a call to that end point you know URL so we start with HTTP of course you know the usual protocol localhost call in five thousand forward slash flip i'm gonna do flip coins and i'll tell you why in a moment and then let's just do x is 40 all right now how do we extract the value from this call might be wondering i'm gonna make a new line right under it and i'm gonna do dot then and basically what's gonna happen here is when we make a call you know using HTTP we need to wait for a response and by using this dot then this will wait for a response back from our api and then we can use this callback function res you know an arrow and then a body and this parameter will be automatically populated by whatever the server responds with and we could print it out but if you try to print this out and you can if you on your own if you'd like to it does come out with a bunch of gibberish like all this HTTP you know response info and if we only care about the body you know the body the response which contains the coin data we can just return res JSON like this and then residence on also takes what's called a it's an asynchronous function you can think of it as but simply put you're gonna need to use another back then so it's kind of chained like this and then we will see I'll just define this as data you could you know rename it as res if you want and then let's just console.log using the shortcut log on vs code and then I'm just gonna print out data I'm gonna give her this line nice so what's happening here is client is using the fetch function and we bring back the diagram you could present the clients over here and it's using fetch to you know go to flip coins and then respond with JSON and I was gonna mention why reason the plural flip coin instead of flip coin and this is because flip coins write it returns a JSON response if it's valid and if it didn't return a JSON response for example like a string here or up top you know this also returns a string value wouldn't work we wouldn't be able to parses as JSON right so yeah let's go ahead and run this and to it up it's a load client oh before I run this also in a separate terminal you can use this function or this button here to split it but I'm just gonna run server make sure this guy is running and then now we're gonna go ahead and call it boom there you go so pretty cool right we are we wrote some client code and the clients calling on the server right let me just change this to like 400 I'm gonna clear this nice how about that so it's pretty cool you can pretend that you know the client can represent like a web page you click a button you know the buttons gonna invoke fetch right to flip a coin and then servers you know not directly connected to the client it's running on its own and we use fetch the bridge the gap between the two like we saw pretty cool well with that being said I hope you learn something I had a lot of fun and I will see you next time
Info
Channel: evan ugarte
Views: 199
Rating: undefined out of 5
Keywords: express.js, node, express.js tutorial, easy, node.js tutorial, node.js, rest api, node rest, express node
Id: H4c6woZbPKo
Channel Id: undefined
Length: 28min 17sec (1697 seconds)
Published: Tue Jun 02 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.