Using axios, swapi, and NodeJS

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello welcome thanks for joining me i'm going to do try to keep this short and do a quick demonstration of using node with the axios package to fetch some data from an api a server api i'm going to be using the star wars api because it's free and fun and what we're going to do time permitting is get some data from the api and generate a markdown file with node just to kind of get a little practice and take a look at using the async await syntax and promises working with axios and doing a little data fetching over http so let's get started first off i don't have a plan so i'm just kind of making this up as we go along so we're going to go ahead and get started i'm going to make a new folder i'll be using vs code for this i'm just going to call this fetch axios swappy was what we'll call this let me go ahead and open vs code up to this folder now and go ahead and get started so i'm going to first need to figure out what our markdown is going to look like so i think well first let's take a look at the data we get back from swappy my thoughts were maybe we'll make a little fact sheet about a star wars character of our choosing so we'll make a little command line tool where you enter the name of a character actually we're just going to make it hard coded for luke skywalker let's just do that so luke skywalker looks like we get at people one so we'll grab luke and then we're going to go ahead and create a little fact sheet using markdown about luke so we're going to go ahead and call this care we'll just call it factsheet.markdown factsheet.md and then if we're using luke skywalker as an example i think we'll just put his name up top skywalker facts like so go make a little heading with markdown if you're not familiar with markdown uh you should check it out i will when i have a moment when i have the time i'll add a link to some documentation on what markdown is all about um but let's continue on so we're going to put a the name of the character across the top and then we'll include height guess by these numbers is we're dealing with centimeters i'm not as familiar with metrics so i'm going to say 177 cm 2 feet so 5.8 feet seems a little short to be honest 172 even shorter but forgive me if that's you but i just thought luke would be taller five and a half feet so um luke i'm going to go with centimeters that seems the most reasonable so let's do that luke skywalker and then we'll have um biometrics and then we'll say something like and we'll give him a we'll make height bold so we'll say height 172 cm and this being marked down in order to get a new line we have to put an extra empty line in between mass i'm guessing those are kilograms 77 kg two pounds just get an idea yep seems reasonable so we'll go with mass okay his hair color and that's going to be blonde we'll do eye color let's call this info and that way we can just kind of keep going and we'll say blue and gender mail and let's see um i want to do one extra request so i think what i'll do is i'll go ahead and do the home world that way we have to do a second request to get into some promise chaining so we're going to go ahead and do homeworld and that way we have to go to another page oh we want to do birth here because why not earth year 1 9 bb y okay and then finally let's go get a home world so we're going to take this request now which looks like i need planets 1 we'll request planets 1 here i did one one so and we'll just get the name of the homeworld tattooine and i think we'll stop right there so there's a little fact sheet we'll use a markdown preview just to see how this looks um go ahead and open preview i'm using an extension to make my markdown preview like it would look on github so if you're interested in that extension it is called um markdown preview github styling and that allows you to see what your your markdown so like your readme files will look like when you publish them on github all right so there's our little fact sheet on luke skywalker and so let's go ahead and work on our app now that we kind of have an example of what the output is going to look like so i'm going to add another file index.js also we're going to need some packages so let's go ahead and run npm init and i'm just going to take dash y to take all the default options and then we're going to be using axio so i'm going to go ahead and npm install axios so npmi axios we'll add that package great all right so i think we're basically going to want to write two functions because there's two phases to this app right we need to get data and then once we have the data we want to create our markdown file so since i already have the market down file it might be a good idea to actually start with that so let's let's go ahead and do that i'm going to just copy and paste all of this and i'm going to go here in my file we're going to write a little function called let's see render markdown and that's going to return a markdown string so we're going to return and then what we can do is use a template literal in javascript that's going to make this pretty easy i can just take everything i've pasted on my clipboard and drop it in here and then we can basically go and play fill in the blanks kind of like a giant mad lib right so here i can replace this with height right so we put a dollar sign in curly braces and then we can just say we'll make this take um i guess two parameters we want our person and our homeworld parameter since homeworld comes separate so we're going to call render markdown with a person in a home world in fact let's just make the whole thing um let's call it data and then what we'll do here is say going back to the documentation for swappy oops go forward please go back please board please okay go back to swappy so we have the name properties we're going to say data dot name we're going to say data.mass data dot hair underscore color data dot i underscore color and i'm figuring this out just by reading the documentation here on the right hand side from the swappy api all i'm looking at data dot gender data dot birth underscore year and then finally homeworld how are we going to take care of homeworld i i guess we'll just make it part of data so i'll just say data.homeworld name that's what we'll call it perfect or maybe we'll just yeah we'll let's not overcomplicate things we'll just leave it like that all right great um finally um yeah i think that works pretty well um the problem is is with template strings all the white space so the new line here all this space to the left all of that gets preserved and marked down so what i think i'm going to do is i know it's not pretty but we're going to go ahead and kind of make this code a bit ugly but i feel like this is the easiest fastest way to just make everything work so this function returns our markdown string oops i almost forgot the name data.name up here and this should have been data.height right here i'm glad i noticed that get.name and there we go so now we've got our render markdown function working let's go ahead and um test it out i suppose no let's not test it out i'm feeling lazy let's just build um so next up normally i would test this out but next up we're going to build our fetch person function and for now we're just going to fetch luke so the url to fetch luke is this url right here we're going to say const url equals people one and then we're going to use the axios package so i'm gonna say const axios equals require axios and that's gonna import the axios package from npm which already installed um so that should be over here in our node modules so we can see and in order to do a get request with axios we can just return axios dot get and then pass in our url and that should work out so let's let's test our fetch person function so right above it i'm going to call fetch person and then we're going to say then console that's going to get a response object and i just want to console.log response.data to see what that looks like and we'll add a catch in case something goes wrong to accept an error console.log the error if one occurs all right great so we've got fetch person axios which returns are called axios meaning that i'm going to get a promise which i can chain this dot then call onto log the data for now and then catch if there's an error let's just test that out so i'm going to open up my terminal by right clicking over on the left hand side here in the explore area vs code and choose open an integrated terminal and then i'm going to type node index to run our code and see if it works it looks like it does just awesome so this gets me the person so i have everything but uh oh we also want to grab the home world so i'm going to make another function called fetch homeworld actually yeah fetch fetch homeworld i guess or fetch planet we'll call it fetch planet and this takes planet a planet url and we'll go ahead and return axios dot get planet url so it's almost like you know what i'm not going to make a separate function instead what we're going to do is return axios.get url and then what are we going to do here i think let's back this up so i'm not going to separate out our axios calls so i'm going to back this up a second just so that way we can demonstrate promise chaining a little more clearly so instead i'm just going to write a function main and that's going to do our url to fetch the person which then we can say axios.get url here and then we can say then so now that i have the person so this is going to be response and then we have our our data for our person with response.data and what i want to do is do another request so what i could do is say axios.get and then we could take response.data.homeworld and that's going to then we could chain another dot then and now i have another arrow function which let's say we got homeworld response with it i'll call it homeworld res to differentiate it from our person res and then i could call and then i could say const homeworld name equals homeworldres.data.name like so and then i could finally call our render markdown function so const md and we'll call render markdown and and that i could take my person so let's go ahead and make const data equal response.data right that's our person data we'll call it person data equals response.data and then we want to add to that so we're going to say person data dot homeworld name equals homeworldres.response.name and that would be the name of the homeworld then we could just pass in person data and then console.log the markdown and let's go ahead and run that code now uh-oh i forgot to call main gotta call main otherwise nothing's gonna happen all right let's give this a shot and it looks like we have an error so let's add some error handling so my outer dot then needs a dot catch by the way we're going to change this because this is not really getting any benefit from promises we're kind of going into a little call back hell here but let's go ahead and take an error here we'll console.log the error and then we need to do the same for the inner promise so dot catch here as well with an error and console.log error i have an extra semicolon there to get rid of format our code here let's just say homeworld name equals homeworld and like so okay let's try this one out for size okay now it's working sometimes the swappy api i've noticed does that so looks like we're getting everything including the name of the homeworld which is pretty awesome but our code's kind of a mess right now we're not really using promises the way they are meant to be used so if we want to be able to flatten this out and chain these promises what we should do in our dot then here is return our second called axios dot get like so but there's a little issue because i need to get my person data as well as the homeworld data i'm going to need to lift those up so we're going to say let person data right here and then when we get our first response i'm going to say person data equals response dot data right here and now my now that i'm returning my axios.get i can take everything i had originally put in this dot get and we can chain that to the outer promise see how that cleans things up and now we get the homeworld name and we don't want to do person data any anymore here we just want to add homeworld name to our person data which we lift it up a level and then once we have that we can render our markdown and then console.log it so that that gets us out of our our callback hell situation by making sure that as soon as we hit another promise that we needed to wait for pardon me my headset cut out there but as soon as we hit the second promise that we needed to wait for we can just return that promise and then chain another dot then on and that keeps us from creating that callback hell situation it allows us to have a nice linear easier to read flow in our code and that's the whole point of promises really is they just make the code easier to read and now because i have these chained i don't need two dot catches i mean i can leave that if i needed some special handling for homeworld but i can instead of instead of putting two dot catches now this one will catch if the first dot then fails or the second dot then fails either one will skip down to my dot catch so let's test this code i'm going to run it one more time down on my terminal here and we can see that it worked which is pretty awesome so finally let's go ahead and get the file system utility so we're going to say const fs equals require fs we're going to use the file system package and we're going to continue working with promises so i'm going to bring in a utility the util package for node because that has a utility that can convert something that uses a typical callback signature so it takes a function that accepts a callback as the last parameter and then it can convert that into a promise for us so i'm going to grab util and we're going to make our own custom const write file async function that returns a promise and we can use util.promisify and then pass it fs.writefile and that's going to create a promisified version of write file which is pretty awesome so finally after render markdown i can call i can return again because this returns a promise now instead of console logging the markdown i'm going to return write file async and we're going to call this factsheet.md is the name of the file and md is the content right the markdown that we got from calling render markdown and now that that's chained i can add another dot then and that can print some kind of success message so i'll just console.log created fact sheet.md all right so let's try that one more time going to run and it says created fact sheet dot md and if we go look we've got our fact sheet just to verify that let's delete fact sheet by running our code again should create fact sheet and there it is voila now we could enhance this maybe by letting the user enter the id of the character they want or we could even put a list of character names and maybe use a package like inquirer to map whatever name the user chose to an id we could we could add some extra enhancements i will leave that to you because i am running out of time i wanted to show one more thing so here we're using a chain series of promises what about using the async await syntax instead so we're going to rewrite this main function to use async await so to begin doing that first thing we need to do is put the async keyword in front of our function and now we can start rewriting these promise chain these chain promises to use async away instead so i'm just going to comment that out for now and what we're going to do is say we're going to start with const person data equals actually we're going to make a generic variable let's say let data and then we're going to say await axios.get url and that's actually not going to get me data that's going to get me a response so if i want data we're just going to say response we're going to reuse response and now i can say const person data equals response dot data like so and then now we want to get the homeworld info so i'm going to let response equal await axios.get persondata.homeworld has the url that we got back for the person's homeworld right or we're sticking with what we did before let's use response.data.homeworld and now we can get we can say persondata.homeworldname equals response.data which is what we did before to get the name of the homeworld so we got our person data let's create some visual separation here so we create our person data we add the homeworld name to it and then finally let's await write file async and then we'll grab our arguments to write file async that we used before so i almost forgot to render the markdown so we'll say const md equals render markdown and we'll pass in person data and then finally we want to log our success message once that's done so we'll go ahead and put that message here now what about errors so when we use async await instead of the dot then dot catch syntax of promises what we need to do is create a try catch block so i'm just going to wrap all my code on a try catch block and so all basically the success path is inside our try block and then in our catch block we'll just console.log.error and if at any point one of these promises rejects or we have any errors in our code execution will stop and immediately jump down to the catch block and run our catch block so that's how you can convert our promise chain into the async 08 syntax let's make sure our code works i'm going to delete our fact sheet file if i do ls we can see there's no fact sheet and now i can run node index and it should generate our fact sheet markdown file and now if we do an ls we can see there's fact sheet.markdown if i open a preview there's our luke skywalker facts all right time's up thank you so much for watching i hope you found this helpful maybe it sheds a little light on different ways you can express asynchronous code in javascript whether using the promis syntax or the async await syntax
Info
Channel: Median Man
Views: 1,691
Rating: undefined out of 5
Keywords:
Id: tOd6FGOBd3A
Channel Id: undefined
Length: 26min 25sec (1585 seconds)
Published: Wed Sep 30 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.