Fastify Crash Course | Node.js Framework

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hey guys welcome to my fastify crash course so fastify is as you can see on the website here it's a fast and low overhead web framework for node.js so it's comparable to express and it's it's very similar in that it's very minimalistic but there are some advantages that i really like about fastify one is the complete ecosystem of plug-ins that are offered so basically if you want you know let's say jason webb tokens there's a fastify jwt plug-in if you want to use mongodb as your database there's a mongodb plug-in next.js redis swagger which we're actually going to be using for our documentation for our api so there's just a ton of stuff here you also have community plug-ins and i really like that when you use express in in no way am i saying fastify is better than express or vice versa but when you use express you usually have just a whole bunch of different types of modules that you're using i really like the organization of fastify another advantage is speed and obviously that's implied in the name and this article here this is actually from 2019 so it is a bit old but uh he did some benchmarking and shows you the results of express versus fastify with different endpoints here and the conclusion was that fastify was around 20 percent faster than express in almost every request so that is another uh you know pro to using fastify is the the speed and efficiency of it so we're just going to kind of dive in we're going to build a crud api we're going to i'm going to show you the the very basic way to create routes and fetch some data we're just going to use a file for data for now and then we'll go ahead and build some controllers i'll show you how we can add different options for our routes for different responses and just show you some of the benefits of fastify so i'm gonna go ahead and open up vs code and i just have an empty folder called fastify api now i'm using an extension called rest client and we're going to be using this to make requests to different endpoints of our api now if you want to use postman or something different you can but this is what i'll be using and we won't have to leave visual studio code in order to make requests so first thing we'll do is let's open up a terminal i'm going to use my integrated terminal here and run npm init dash y which will just create a package.json file now as far as dependencies we want to install fastify so npm install fastify or yarn whatever you want to use and we also want a plugin we're going to be using called fastify dash swagger which will give us a really nice open api documentation for for our api and then i'm also using a module called uuid to generate random ids so we're going to install those and then as far as dev dependencies i'm just going to install nodemon so npm install dash uppercase d nodemon and that'll make it so you know it'll watch the server and we don't have to keep restarting it after every change and then in the scripts here i'm just going to add just a basic start script that'll run node and then our main file which i'm going to call server.js so just node server and then let's go ahead and create another one here that's going to run node mon and that's going to be our dev script so npm run dev okay we'll just change this main to server.js now let's close that up and let's create a new file called server.js and we're going to go ahead and bring in fastify here so we want to require it now you this variable here is what we're going to use to create all of our routes and stuff if you want to call this app or something different you can do that i'm going to keep it as fastify just because that's how it is in the docs and then here we can add a set of parentheses and then an object with some options and we're just going to set logger to true which will just give us some extra information down in the console now to start up our server we can call fastify.listen similar to you know app.listen with express it does return a promise so we are going to create a function here called start and make sure we make this asynchronous and then in here we'll have a try catch and inside the try let's await on fastify dot listen and then a port which i'm going to put i'm going to create a variable up here so call this port and i'm going to use port 5000 but feel free to use whatever you'd like and then down here in the catch we'll say fastify and then there's a log we can do log dot error and pass in that error if there is one and then we just want to exit the process with failure so process dot exit and pass in a one here and then we just simply want to start the server so we'll save that and i should be able to now do npm run dev okay and you'll see the stuff down here server listening on poor on the the url in the port the host name and that's because of this logger true if we set that to false it won't show this stuff here so to create a route let's just go ahead and do that we want to say fastify dot and then whatever the method well there's actually a couple ways we can do it we can do dot route and we can pass in some options but the shorthand is to just use the method so let's say get slash items and then we have a handler so this is again very similar to express so this is going to be uh request and then reply so reply is kind of the conver this is the convention for this but of course you could call it you know res or response and then in here all i'm going to do for now is take that reply object and i'm going to call dot send and i'll pass in just an object with let's say i don't know test and hello okay so creating a route is as simple as that now to test this route i'm going to be using my rest client that i have installed for vs code but again you can use postman or in this case you could even use your browser but to use the rest client we just create a file with an http extension so i'm going to call this test.http and in here let's say we want to make a get request to http localhost 5000 slash items and we just want to add http slash 1.1 okay and we can actually separate these i'm going to move this down a line and we can separate our requests with the triple number sign and we can also put a comment in here so let's just say get all items and obviously you know it's not returning items yet but that's what this route will do but let's send the request and you'll see we get back up here we get back a 200 response the content type is json the length the date and then we have the actual data that's returned which is just this test hello okay so now we can we can test all of our routes with this file here now i don't want to actually put well you know what let's we'll just keep it like this for now we'll do it in this file but we're going to move this to a separate routes file in a few minutes as far as data i'm just going to use a file a javascript file so let's create i'm going to create items.js okay capitali items.js and this is basically going to be our data we're not using a database in this case although i may add another video where we can use either postgres or or something like that with the fastify plugin and you guys can let me know if you want to do that so here let's just create an array call this items and we'll just have an object with an id with a string and then a name so we'll say item one and i'm just going to copy this down we'll have three different items here this will be two with the id of two and this will be three three and then let's just do module dot exports items all right so that's our data so i'm going to bring this into this file by just saying const items and set that to require and we want to require dot slash items okay and then down here i want to return those items so let's get rid of this object and just return items or send items so now if i go back to my test http we're going to go ahead and get those items back all right now let's create one more route in here and then we'll move it to a separate separate file i want to create a route that just gets a single item so what we can do is grab this paste that in there i'll just close that sidebar up for now so this i want to get a single item so it'll be items slash and then a param of id now we can get that id with request so this request object and then dot params with which is an object that has all the params so i'm going to use destructuring here to pull out the id from request.per and then obviously we're not working with a database we don't have any kind of orm like mongoose or something like that so we just kind of have to do this by hand just with javascript so let's use find we'll say const item and we'll set it to items and we'll just use dot find and that takes in an arrow function so for each item then we want to get where the item.id is equal to the id of the param and then we'll just return that okay so let's go ahead and save that i'm going to just make this this side a little smaller here and then we can make a request to this items slash id so i'm going to copy this whole thing right here and we'll say get a single item oops and this will be item slash and we'll get the first one so item slash one and then let's send and we should see the first item if i go two then we can see the second but i'll just keep that at one okay so we know that's working now you as you can imagine this can get quite messy if we leave this in server js so what we'll do is create a separate folder here called routes and inside routes will create items dot js so these will be all of our items routes now with fastify in using a separate file for routes we can actually register our routes as as a plugin so the way that we can do that is by using a function so we're going to say function and this is going to take in actually let's call this item routes and this is going to take in three things takes in fastify options and then a callback called done and you just want to make sure at the end of all this you call done and then you can put your routes in here so we'll go ahead and grab the two routes we created so we'll take these and we'll cut those out and we'll put those right in here and we also want the data so this doesn't need to be here anymore we'll take that we'll put that in our routes file above the function and since we're we're down a level it's going to be dot dot slash items okay and then we just want to make sure that we export item routes so down here at the bottom module dot exports item routes okay now since we wrap this in this function like this we should be able to just register just like we would when we use a plug-in we register it with fastify dot register and then in here we want to require dot what is it dot slash routes slash items okay so just doing that if we save and we go back to our http file and i send it should still work the same way so we can get all of them we can get a single item now another thing that we can do is validation with certain schemas for what we want to return from these routes all right let me just put a comment in here so this get we'll say get all items and this will get single items and this is going to get all cleaned up down here so any logic we have in these handlers are actually going to go in controllers in a little bit but i just want to show you how we can create options for these so up here above the item routes function let's say options for get all items so basically we can format what is to be returned or responded with from each of these routes so i'm going to create an object here i'm going to call it get items so plural ops for options i mean you can call it what you want but we're going to call it that and then in here we can add a schema so a schema object and we can actually format for each response which in this case is going to be a 200 response because reply dot send as long as nothing goes wrong that's going to be a 200. so i'm going to say for a 200 response for this particular route we're going to want this to be in an array in this case because we're getting multiple items so let's say type and set that to array and then for the we want to say for the items we want that to be a type of an object and then we can specify the properties that are to be returned so in our case we have what an id and a name so let's say id and we can actually type this so i'm going to say type string and then we'll copy that down and we also have a name which is also going to be a string so say name okay so we're kind of just formatting how the schema is for the response for this now this get items ops all we have to do to use this in one of our routes is put it as a second argument so this is the route to get all items i'm going to paste that in right here as a second argument so it's the end point the options and then the handler so i'm going to save that and this should still work just the same it gets you know fetches all three items but if i go up here so this is our schema right here if i were to comment out let's say the id and i make that request again notice how i'm not it's not giving me the id even though i returned it in my my code it's not going to allow that id to be to be shown okay because all i have in my properties here is the name also if i were to change this type to an integer and i make the requests now it does give give me the id but it's no longer a string it's an integer so it'll actually coerce it into that type but i want that to be a string so now when i send it's a string so i think that this is a really great feature of fastify is is the validation and the schema now we want to create options for all of our routes so i'm going to copy actually i'm not going to copy it because it's going to be a bit different because this route here returns not an array but an object so let's go down here and let's say const and we'll call it get item singular ops and let's say for this um so we want our schema so schema and then the response we want to say yeah for response 200 then we want not an array like we did here but just the object so i can actually copy this wait yeah items so type object so that the type and the properties if you have an array then you have an additional items because then you need to say well what is in that array but in this case it's just an object so it's going to be a type object with the same thing all right and then we'll add this down here to this route so this will be get item ops okay and that should still work it gets me item one if i were to comment out here let's comment out name this time so if i make that request again it only gives me the id because that's all i have in my schema all right now you'll notice that this type object and properties is the same as this type object and properties it's just this one is inside of an array and we're going to be using this in other routes as well so what we can do is create up here let's say item schema and let's say cons uppercase i item and we're going to set that equal to this type object and then our properties it'll be an object with those in there so now instead of repeating ourselves this type array items we can just replace this with item and then down here where we have the type type in properties we can just replace this with item all right and that should work the same way so that will give us all of our items this will get us a single item okay so just cleans it up a little bit now before we move on to you know being being able to add an item delete and update i want to clean this up a little more and create a controller functions so basically with these options in addition to the schema we can also add the handler here right now the handler is down here right it's this function so what we can do is just grab we want to keep that last parenthesis but i'm going to grab this and just cut it so that all we have in here is the endpoint and the options and let's go up to get items options right under the schema we can add the handler and set that to a function and just paste that in and we just want to get rid of the arrow here all right so if i save that that should still work the same way it gives me all the items except now the handler is up here in the options instead of putting it here which cleans this up a bit and we can do the same thing here where i take let's say from here to here cut that out and then in this get item options go under the schema handler and set that to function and then just get rid of the arrow and that should still work if we fetch the single item all right so we're just cleaning this up a bit before we add more routes and like i said the the final thing i want to do to kind of clean this up is create controller methods so i'm actually going to create a new folder here called controllers and in here we'll create items.js or you can call it item controller whatever you you'd like so for this this is where we're actually going to need our data now so we can grab it from here we can cut it from the actual route file put it in here and then let's create our first function which is going to be get items and this is going to take in request and reply and all we're going to do is same thing we did in the route we're going to reply dot send all of the items okay so that'll do that um then we'll do cons to get item and that's gonna take in request and reply oops a fat arrow and then let's take from the handler for the get the single item we just want the function body here and we're going to put that in there all right now we just want to export both of these so module dot exports and we're going to set this to an object with the get items and get item and then we can go into our routes and we can bring those in so let's say const we want to bring in get items and get item and that's going to be from uh where are we dot dot slash controllers slash items and then we can just simply replace this function here so this is to get all items so we want to replace that with get items from our controller and then this one here this function we're going to replace that with get item for the single item so now this is oh this is way cleaner than it was before and let's just test it out so we can get all of our items and we can get a single item okay so now we have basically the structure of everything before we move on to create the rest of our routes i want to implement the fastify swagger plug-in which will give us some really nice documentation for all of our routes so to do that we're going to go to server.js make sure that you installed fastify swagger you can see we have it right here so we want to register this because it is a plug-in whenever you install a plug-in you're going to register it much like we did our routes so let's say fastify register and we want to then pass in require we want to require fastify swagger and we want to add on to this a second argument of options and the first thing we want is expose route which we're going to set to true which will enable the documentation route and then for the route prefix we're going to set that to slash let's do slash docs you can make this whatever you like and then we can add swagger and in here an info object with a title and if you look at the docs you'll see all the different options but we're just going to say fastify api okay so we registered fastify swagger and we added some of these options and it should just work so if we go to the browser now and we go to http localhost port 5000 slash docs you're going to see your swagger documentation which is really nice it's nicely laid out and you can see our two routes you can even try it out so if we say try it out and execute it gives us back the request url the code um the body the response headers so really really cool and each route that we add will just automatically oops will automatically be added to this documentation here all right so let's continue on with our api so we have two routes right now right we have get all items get single items so let's go ahead and do add item so we're going to say fastify.post because this is going to be a post request to slash items and then we're going to have post let's say post item yeah post item ops which doesn't exist yet so we're going to go up here and add the options for that so i'm going to copy let's see we'll just copy this here and we'll paste that in and let's change this to post item ops and as far as what we want to return from this is going to be just an item just like this but i do want to change the response to a 201 and what we're doing here is just saying if it's a 201 then it's going to be an item we're going to set the 201 in our handler which i'm going to create now so we'll call this add item in our controller all right and we have to bring that in i know we didn't create it yet but we'll go up here and bring it in add item it's going to give us an error down here because that doesn't exist so let's go to our controller here and let's put this below get item so we want to do const add item and request oops request reply and let's see so in order to do this we're going to have to get data from the body basically when we make our request i want to send a name all we have is an id and a name the id will generate that automatically with that uuid module we installed um so first thing let's get the name from the body so just like with express you have request dot body and then dot name or whatever so i'm gonna actually just destructure and take the name from request.body that'll give us whatever name is sent and then let's construct the item which consists of an id now for the id i'm going to use the uuid module that i installed earlier so up here let's say const and we're going to take let's say require and it's called uuid and then we want to from that there's different versions we're using version 4 and we're going to rename that as uuid v4 so all we have to do now is call a function called this and that will create a unique id for us so down here oops i thought i copied it but down here we're just going to call uuid version 4 and then the name is going to just be the name we took from the body alright so that will construct the item now i'm going to add it to the items in our data or i should say in our state basically by taking items and setting it to an array spreading across the current items but then adding on the new item we just created and then finally to respond we're going to say reply but i want it to be a 201 so we can just do dot code and then there is the status code which is 201 and then dot send and we want to send that item okay so now let's go over to our test and we'll just copy this let's say this is going to add an item and it's going to be a post request to just slash items all right so let's go ahead and actually what's going on here i don't think i exported it from the controller no i didn't so add item all right good so now let's try to run that post request and cannot destructure name as it is null all right so i didn't actually send name so we want to add here a content type of application json and then we just want to add an object with json object with name and let's call this new item okay and then we'll go ahead and send assignment to constant variable let's see i think in my data i used const whereas uh items no i used let there i think i used in the controller yeah right here so you want to make sure that's let all right let's try that again send all right so what we get back is our new item the name is whatever we pass in here and then the id was generated with uuid and if i go up here to get all items you'll see it's added there now it's not going to stay there if i save if i go over to you know the routes file here and i save it it's going to restart the server and then that's cleared from memory so now if i get my items it'll just be the initial three in that in the state all right so keep them keep that in mind we're not persisting the data anywhere but we can still make our requests and you can see how it works so that is to add an item now one more thing i want to do is in the routes file in addition to let's say you want to go to our post item options in addition to formatting the response we can also add required fields to the data like right now if i make my post request without the name if i just if i do that and send the request it still creates it and just gives it an id i don't want that i want it to to have to have the name so in our route or i should say in the the option here post item options let me just close that sidebar up we can in addition to response in the schema we can also add a an object for body make sure you put a comma here and for this let's say this is going to be type of object that we send in the body and then we can add required which is an array of required fields so we want to add name and then we can also add properties and we can say for the properties we just have a name and that will be type of string all right so now if i go back to my test here and i try to send this without a name i get back an object with a status code of 400 a bad request and it says body should have required property name so you can add you can have these required fields for your for your body all right so now that that's done let's do the delete so i'm going to add another route down here actually just copy this so let's say delete item and this is going to be a delete request so delete and we do need to pass in the id here so let's say item slash the id and we'll call this for the options delete item ops and then let's go up here and as far as the what we're getting back from the delete it's going to be a message that just says it's deleted so what i'll do is i guess i'll just copy it doesn't really matter i'll copy this and we'll go under the post item options and this is going to be delete item options and we'll say on a 200 response i'm not going to use item here i'm going to use just an object and we're going to say the type is going to be an object and then properties we're just going to have a message on this so properties let's say message which is going to be the type of a string okay and then the handler is going to be delete item which we haven't created yet but we'll set it and then we'll bring it in up here so delete item and then in our controller let's create our delete item so const delete item request reply and before i forget i'm just going to add it down here delete item all right now as far as deleting it i mean we're just we're just going to use filter so first of all we need to get the id which is on request.params right so let's say const will destructure the id from request.params so we have the id now i'm going to just set items which is basically our state we're going to set it to items.filter and then we're going to pass in our arrow function and say for each item we want a filter where item dot id is not equal to the id from the params so basically it'll just take it out and then we'll reply dot send and i'm going to just send a message and actually let's use back ticks here so we can say item id has been removed all right so we'll save that and let's go over here and let's create i'll just copy this create our delete requests so we'll change this to delete item and let's change the method here to delete and let's delete let's do um we'll do three all right so let's try that out if we go ahead and click that we get item three has been removed and if i go up here to get all items we should see just one and two and again that's not persisting it's just in memory all right so that's our delete now i want to be able to update as well so let's go to our routes and let's add that so i'm just going to copy this and we'll say update item fastify this is going to be put items id and then let's call this update item options which we need to create up here which is pretty much the same as like the get single because it's just going to return an object an item object so i can just copy get item ops and we'll go down here at the bottom right above the function and let's call this update item options it's going to be a 200 with the item and then the handler is going to be called update item which we have to bring in from our controller and create so let's say update item go into our controller and i'll just copy the delete here and let's change that to update item and before i forget we'll go ahead and bring that here and then as far as what we want to do here for update we do want to get the id from the params we also want to get let's just get rid of this we also want to get the um actually no we'll keep that there well i'll yeah we'll just keep that there for now but let's get the name from the body because that's really the only thing we can update right unless you add other fields so let's get that from request.body now there's a few ways we can do this what i'm going to do is take our items and i'm going to set it to items.map so we can loop through the items and basically return whatever we want from it and i want to return the the entire array with the updated item so let's say for each item we want to have a condition where we test and see if the item id is equal to the id from the param if so we're going to return the id with the new name from the body else it's just going to return the item as is okay just how you know the default and then down here we want to return just that single item so we can use dot find so instead of dot filter let's do dot find and this is just all regular javascript this has nothing to do with with fastify but basically i want to say where the item id is equal to the id and then as far as what we want to return or send is just the single item and that should do it so let's create our last request here i'm going to copy the pope the ad item the post because we want to be able whoops we want to be able to update the name so down here let's paste that in and let's say update item and we want this to be a put request to item slash and we'll do two for the update and we'll change the name to update updated item like that all right so now if i send my request it's going to give us back a 200 response with the new updated item name and if i were to get all my items you'll see the second one has the name of updated item so we now have a full crud api uh and we have you know our options inside of our routes with some a little bit of validation with some schemas or a schema and you know we have our swagger documentation which we can actually take a quick look at so if i reload this it should show all of our different routes we have our post our our two gets are put in our delete all right so this is really just scratching the surface of fastify there's so much more you can do with this and you know there's a ton of different plugins to do different things which i'd really like to get into so let me know if you guys like this and you want me to continue on and maybe do some authentication deal with the database um you know there's plugins for cores and just a whole bunch of stuff so that's it guys i hope you found this useful and i will see you next time
Info
Channel: Traversy Media
Views: 77,386
Rating: undefined out of 5
Keywords: node.js, fastify, fastify.js, fastify crash course, REST API, node.js rest api
Id: Lk-uVEVGxOA
Channel Id: undefined
Length: 39min 43sec (2383 seconds)
Published: Fri Jun 18 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.